参考: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 ):  #更新w,b
 9     global w , b
10     for i in range( len( x ) ):
11         w[ i ] += y * x[ i ]
12     b = b + y
13     
14 def cal( x , y ):  #计算 y*( w * x + b )
15     global w , b
16     result=0
17     for i in range( len( x ) ):
18         result += w[ i ] *  x[ i ]
19     result += b
20     result *= y
21     return result
22 
23 def perceptron_func( group , label ):  
24     global w , b
25     isFind = False
26     n=group.shape[0]
27     x_col=group.shape[1]
28     w = [0] * x_col
29     b = 0
30     while isFind == False:
31         for i in range( n ):
32             if cal(group[ i ] , label[ i ]) <= 0:  #仍存在误分点,则更新w,b,记录每次更新的结果
33                 update(group[ i ] , label[ i ])
34                 print(w,b)
35                 break  #退出for循环,进入while判断
36             elif i == n - 1:  #无误分点
37                 print(w,b)
38                 isFind = True  
39 
40 g , l = creatDataSet( )
41 perceptron_func(g,l)

 运行结果:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

[3, 3] 1
[2, 2] 0
[1, 1] -1
[0, 0] -2
[3, 3] -1
[2, 2] -2
[1, 1] -3
[1, 1] -3

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄