使用Numpy实现与运算感知器

背景说明

参考PHP实现感知器

实现代码

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
import numpy as np

data = np.array([
[1, 1, 1],
[1, 0, 0],
[0, 1, 0],
[0, 0, 0],
], dtype=np.int)
bias = np.ones((4, 1))
data = np.concatenate((bias, data), 1) # 偏置值作为输入


def predict(x, w):
"""
预测结果
"""
x = x.reshape(x.shape[0], 1) # 输入
w = w.reshape(1, w.shape[0]) # 权重
return 1 if w.dot(x)[0][0] > 0 else 0


rate = 0.009 # 学习率
weight = np.zeros(data.shape[1] - 1) # 初始权重

for _ in range(10):
for _, item in enumerate(data):
t = item[-1] # Label
d = item[0: -1] # Data
weight = weight + rate * (t - predict(d, weight)) * d

print(weight)