-
Notifications
You must be signed in to change notification settings - Fork 0
/
Perceptron
47 lines (30 loc) · 1.32 KB
/
Perceptron
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# sign function
def sign(v):
if v > 0:
return 1
else:
return -1
#Define main function
def Perceptron(pos_sample, neg_sample, learning_rate = 1, iter = 5):
train_datas = pos_sample + neg_sample # 样本集
weight = [0, 0] # 权重
bias = 0 # 偏置量
learning_rate = learning_rate # 学习速率
train_num = iter # 迭代次数
for i in range(train_num):
train = random.choice(train_datas)
x1, x2, y = train
predict = sign(weight[0] * x1 + weight[1] * x2 + bias) # 输出
print("train data: x: (%d, %d) y: %d ==> predict: %d" % (x1, x2, y, predict))
if y * predict <= 0: # 判断误分类点
weight[0] = weight[0] + learning_rate * y * x1 # 更新权重
weight[1] = weight[1] + learning_rate * y * x2
bias = bias + learning_rate * y # 更新偏置量
print("update weight and bias: "),
print(weight[0], weight[1], bias)
print("trained weights and bias: "),
print(weight[0], weight[1], bias)
return weight, bias
train_data1 = [[1, 3, 1], [2, 5, 1], [3, 8, 1], [2, 6, 1]] # 正样本/positive sample
train_data2 = [[3, 1, -1], [4, 1, -1], [6, 2, -1], [7, 3, -1]] # 负样本/negative sample
weight, bias = Perceptron(train_data1, train_data2, learning_rate = 0.4, iter = 5)