1. 程式人生 > >python簡單實現感知機對偶形式

python簡單實現感知機對偶形式

完全對照統計學習方法

from numpy import *
data_set=array([[[3,3],1],[[4,3],1],[[1,1],-1]])
eta=1
n=len(data_set)
gram=zeros((n,n))
a=[0,0,0]
b=0
def cal_gram(data_set):
    for i in range(len(data_set)):
        for j in range(len(data_set)):
            gram[i][j]=data_set[i][0][0]*data_set[j][0][0]+data_set[i][0][1]*data_set[j][0
][1] return gram def f(x): ans=0 for j in range(len(data_set)): ans+=a[j]*gram[x][j]*data_set[j][1] ans+=b return ans def perception(data_set): global b flag=True for i in range(len(data_set)): if data_set[i][1]*f(i)<=0: flag=False a[i]+=eta b+=eta*data_set[i][1
] if flag==False: perception(data_set) cal_gram(data_set) print(gram) perception(data_set) print(a,b)