欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

感知机算法实现(原始形式)

程序员文章站 2022-07-07 08:24:21
参考:https://www.cnblogs.com/xzh0001/p/5660632.html 运行结果: x w b1 [3, 3] 13 [2, 2] 03 [1, 1] -13 [0, 0] -21 [3, 3] -13 [2, 2] -23 [1, 1] -33 [1, 1] -3 ......

参考: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 , b
10     for i in range( len( x ) ):
11         w[ i ] += y * x[ i ]
12     b = b + y
13     
14 def cal( x , y ):
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:
33                 update(group[ i ] , label[ i ])
34                 print(i+1,w,b)
35                 break
36             elif i == n - 1:
37                 print(i+1,w,b)
38                 isfind = true
39 
40 g , l = creatdataset( )
41 print('x   w    b')
42 perceptron_func(g,l)

 

 运行结果:

x   w    b
1 [3, 3] 1
3 [2, 2] 0
3 [1, 1] -1
3 [0, 0] -2
1 [3, 3] -1
3 [2, 2] -2
3 [1, 1] -3
3 [1, 1] -3