1 # 神经网络,单层感知器
2 # 参考《人工神经网络教程》韩力群
3 # 2018-3-28
4
5 import numpy
6
7 # 定义一个符号函数
8
9
10 class Perceptron(object):
11
12 def __init__(self, eta=0.01, iter_num=20):
13 self.eta = eta
14 self.iter_num = iter_num
15 self.x = numpy.array([[0, 0, 1, 1], [0, 1, 0, 1]])
16 self.x = numpy.array([[-1, -1, -1, -1], [0, 0, 1, 1], [0, 1, 0, 1]])
17 self.y_output = numpy.array([0, 0, 0, 1])
18 # self.b = numpy.zeros(1)
19 self.w = numpy.array([0.5, 0, 0]) # 权重w和偏置b初始化为0,0.5
20
21 def Train(self):
22 for index in range(4):
23 print('第%s列'%index)
24 m = self.x[:, index]
25
26 for i in range(self.iter_num):
27 y = numpy.dot(self.w, m)
28
29 y = numpy.sign(y)
30 dy = self.y_output[index] - y
31 self.w = self.w + self.eta*dy*m.T
32 print(self.w)
33 return self.w
34
35
36 p1 = Perceptron()
37 p1.Train()