参考:https://www.cnblogs.com/xzh0001/p/5660632.html
1 import numpy as np 2 3 def creatDataSet( ): 4 group=np.array([[3,3],[4,3],[1,1]]) 5 label=[1,1,-1] 6 return group,label 7 8 def update( x , y ): 9 global w , b10 for i in range( len( x ) ):11 w[ i ] += y * x[ i ]12 b = b + y13 14 def cal( x , y ):15 global w , b16 result=017 for i in range( len( x ) ):18 result += w[ i ] * x[ i ]19 result += b20 result *= y21 return result22 23 def perceptron_func( group , label ):24 global w , b25 isFind = False26 n=group.shape[0]27 x_col=group.shape[1]28 w = [0] * x_col29 b = 030 while isFind == False:31 for i in range( n ):32 if cal(group[ i ] , label[ i ]) <= 0:33 update(group[ i ] , label[ i ])34 print(i+1,w,b)35 break36 elif i == n - 1:37 print(i+1,w,b)38 isFind = True39 40 g , l = creatDataSet( )41 print('x w b')42 perceptron_func(g,l)
运行结果:
x w b
1 [3, 3] 13 [2, 2] 03 [1, 1] -13 [0, 0] -21 [3, 3] -13 [2, 2] -23 [1, 1] -33 [1, 1] -3