我在机器学习方面很天真,遵循教科书(Pyhton 机器学习)和 coursera 上的在线类(class)。我正在尝试在仅包含两个类('sentosa' 和 'versicolor')的标准鸢尾花数据集上实现单一感知器算法,但误差函数没有收敛。这是我的代码:-
import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
class perceptron(object):
def __init__(self,a,iter):
self.a=a
self.iter=iter
def fit(self,x,y):
self.w_=np.zeros(1+x.shape[1])
self.errors_=[]
for i in range(self.iter):
errors = 0
for xi ,target in zip(x,y):
update=self.a*(target-self.predict(xi))
self.w_[1:]=xi*update
self.w_[0]=update
errors+=int(update != 0.0)
self.errors_.append(errors)
print(self.errors_)
return self
def net_input(self,x):
return np.dot(x,self.w_[1:])
def predict(self,x):
return np.where(self.net_input(x)>=0.0,1,-1)
iris=datasets.load_iris()
x=iris.data[:100,:2]
y=iris.target
y=np.where(y==0,-1,1)
ppn=perceptron(a=0.01,iter=10)
ppn.fit(x,y)
plt.plot(range(1, len(ppn.errors_) + 1),ppn.errors_,marker='_')
plt.xlabel('epochs')
plt.ylabel('number of classification')
plt.show()
错误分类(错误)的数量在每次迭代中保持不变
请您参考如下方法:
这些行是错误的:
self.w_[1:]=xi*update
self.w_[0]=update
将它们更改为:
self.w_[1:] += update * xi
self.w_[0] += update
看起来您的输入实现也是错误的:
def net_input(self,x):
return np.dot(x,self.w_[1:])
应该是:
return np.dot(X, self.w_[1:]) + self.w_[0]
你可以在我的 github 上看到完整的实现
如果这不能解决您的问题,请告诉我。
