【问题标题】:Cost function is not converging成本函数未收敛
【发布时间】:2018-06-05 08:19:03
【问题描述】:

我在机器学习方面很天真,遵循教科书(Pyhton 机器学习)和 coursera 上的在线课程。我正在尝试在仅包含两个类(“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()

每次迭代中错误分类(错误)的数量保持不变

【问题讨论】:

    标签: python machine-learning perceptron


    【解决方案1】:

    这些行是错误的:

    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看到完整的实现

    如果这不能解决您的问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多