defcalcGramMaxtrix(X): m = X.shape[0] gram = np.zeros((m, m))for i inrange(m):for j inrange(i, m): gram[i, j]= X[i].dot(X[j]) gram[j, i]= X[i].dot(X[j])return gramdefcalcI(X,y,a,b,i,gram):#print (X.shape, y.shape, a. shape)sum=0for j inrange(X.shape[0]):sum+= a[j]*y[j]* gram[j, i]return (sum+ b)*y[i]# 感知机原始形式defperceptron(X,y,eta): a, b = np.zeros(X.shape[0]),0 gram =calcGramMaxtrix(X) isFinished =Falsewhilenot isFinished: isFinished =Truefor i inrange(X.shape[0]):ifcalcI(X, y, a, b, i, gram)<=0: isFinished =False a[i]+= eta b += eta * y[i]deff(x):sum=0for j inrange(X.shape[0]):sum+= a[j]*y[j]* X[j].dot(x)returnsum+ breturn a, b, f