《统计学习方法》第二章——感知机 python实现
import numpy as np
from sklearn import datasets
iris=datasets.load_iris()
X_all=iris.data
y_all=iris.target
X=X_all[:100,:]
y=y_all[:100]
y[y==0]=-1
class perceptron:
def __init__(self,x,y,a=1):
self.x = x
self.y = y
self.w = np.zeros((x.shape[1],1))
self.b = 0
self.a = a
def sign(self,w,b,x):
result = 0
y = np.dot(x,w)+b
return int(y)
def train(self):
flag = True
length = len(self.x)
while flag:
count = 0
for i in range(length):
tmpY = self.sign(self.w,self.b,self.x[i,:])
if tmpY*self.y[i]<=0:
tmp = self.y[i]*self.a*self.x[i,:]
tmp = tmp.reshape(self.w.shape)
self.w = tmp +self.w
print('######',i,'######')
print(self.w)
self.b = self.b + self.y[i]
print(self.b)
count +=1
if count == 0:
flag = False
return self.w,self.b
percp=perceptron(X,y)
percp.train()