感知机算法实现(对偶形式)

 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 , i ):
 9     global a , b , G
10     a[ i ] += 1
11     b = b + y
12     
13 def cal( x ,  label , row ):
14     global a , b , G
15     result=0
16     for i in range( len(G[ row ]) ):
17         result += label[ i ] * a[ i ] * G[ row ][ i ]
18     result += b
19     result *= label[ row ]
20     return result
21 
22 def perceptron_func( group , label ):
23     global a , b , G
24     isFind = False
25     n=group.shape[0]
26     x_col=group.shape[1]
27     a = np.zeros(n,dtype=np.int)
28     b = 0
29     G=np.zeros((n,n),dtype=np.int)
30 
31     #计算Gam矩阵
32     for i in range( n ):        
33         for j in range( n ):          
34             G[i][j] = group[ i ][ 0 ] * group[ j ][ 0 ] + group[ i ][ 1 ] * group[ j ][ 1 ]
35 
36 
37     while isFind == False:
38         for i in range( n ):
39             if cal(group[ i ] ,  label , i ) <= 0:
40                 update(group[ i ] , label[ i ] , i )
41                 print(a,b)
42                 break
43             elif i == n - 1:
44                 print(a,b)
45                 isFind = True
46        
47                 
48 g , l = creatDataSet( )
49 perceptron_func(g,l)

运行结果:(格式:[a1 a2 a3] b)

[1 0 0] 1
[1 0 1] 0
[1 0 2] -1
[1 0 3] -2
[2 0 3] -1
[2 0 4] -2
[2 0 5] -3
[2 0 5] -3

猜你喜欢

转载自www.cnblogs.com/bobomain/p/10727671.html