1. 程式人生 > >統計學習方法第二章例題2.2程式碼實踐,感知機的對偶形式的程式碼實現

統計學習方法第二章例題2.2程式碼實踐,感知機的對偶形式的程式碼實現

def judge_functon(dataMat,labels,labelsMat,b,m,AMat): for i in range(m): if (labels[i] * (sum(multiply(dataMat * dataMat[i].T, multiply(AMat, labelsMat))) + b)) <= 0: #if (labels[i]*(sum(array(dataMat*dataMat[i].T)*labels*array(AMat.T))+b))<=0: return True return False #演算法主程式
def perceptron(dataset,labels,alpha): dataMat=mat(dataset) m,n=shape(dataMat) aArr=zeros((m,1)) AMat=mat(aArr);b=0 w=mat(zeros((n,1))) labelsMat=mat(labels).T #while ([function_sign(j) for j in array(dataMat * w+b)]) != labels: while judge_functon(dataMat,labels,labelsMat,b,m,AMat): #print array(dataMat*dataMat[i].T
for i in range(m): #print sum(multiply(dataMat*dataMat[i].T,multiply(AMat,labelsMat)) if (labels[i]*(sum(multiply(dataMat*dataMat[i].T,multiply(AMat,labelsMat)))+b))<=0: #if (labels[i]*(sum(array(dataMat*dataMat[i].T)*labels*array(AMat.T))+b))<=0: #print array(dataMat*dataMat[i].T)*labels*array(AMat.T)
AMat[i] += alpha b += alpha*labels[i] #print AMat #print b return AMat,b dataSet,labels=loadDataset() dataMat=mat(dataSet);labelsMat=mat(labels) AMat,b=perceptron(dataSet,labels,1) print AMat,b w=mat(calc_w(dataMat,AMat,labels)) print w,'\n',b