Python上的Perceptron代码对Iris数据没有收敛

时间:2017-08-02 07:01:47

标签: python-3.x machine-learning perceptron

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

class Perceptron(object):
    def __init__(self, eta=0.01, n_iter=10):
        self.eta = eta
        self.n_iter = n_iter

    def fit(self, X, y):
        self.w_ = np.zeros(1 + X.shape[1])
        self.errors_ = []

        for _ in range(self.n_iter):
            errors = 0
            for xi, target in zip(X, y):
                update = self.eta * (target - self.predict(xi))
                self.w_[1:] += update * xi
                self.w_[0] += update
                errors += int(update != 0.0)
            self.errors_.append(errors)
        return self

    def net_input(self, X):
        """Calculate net input"""
        return np.dot(X, self.w_[1:]) + self.w_[0]

    def predict(self, X):
        """Return class label after unit step"""
        return np.where(self.net_input(X) >= 0.0, 1, -1)


df = pd.read_csv('D:\\TUT\\IRIS_DATA\\iris_data.csv', header=None)
print(df.tail())
y = df.iloc[0:100, 4].values
#print(y)

y = np.where(y == 'Iris-setosa', -1, 1)
#print(y)

X = df.iloc[0:100,0:2].values
print(X)

plt.scatter(X[:50, 0], X[:50,1], label='setosa', color='red', marker='o')
plt.scatter(X[50:100,0], X[50:100, 1], label='versicolor', color='blue',marker='x')
plt.xlabel('petal length')
plt.ylabel('sepal length')
plt.legend()
plt.show()

ppn = Perceptron(0.01, 100)
ppn.fit(X,y)
plt.plot(range(1,len(ppn.errors_)+1), ppn.errors_, marker='o')
plt.xlabel('epoch')
plt.ylabel('Number of misclassification')
plt.show()

上面的代码是从书中复制的,但不幸的是,在Iris数据上错误没有收敛到0。错误在两个值3.0和2.0之间反弹。 需要帮助来了解我哪里出错了。

请认为我是机器学习领域的新手,非常感谢任何见解。

1 个答案:

答案 0 :(得分:1)

我刚刚审核了您的代码并发现了一些问题。 别担心我已经纠正过了。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

class Perceptron(object):
    def __init__(self, eta=0.01, n_iter=10):
        self.eta = eta
        self.n_iter = n_iter

    def fit(self, X, y):
        self.w_ = np.zeros(1 + X.shape[1])
        self.errors_ = []

        for _ in range(self.n_iter):
            errors = 0
            for xi, target in zip(X, y):
                update = self.eta * (target - self.predict(xi))
                self.w_[1:] += update * xi
                self.w_[0] += update
                errors += int(update != 0.0)
            self.errors_.append(errors)
        return self

    def net_input(self, X):
        """Calculate net input"""
        return np.dot(X, self.w_[1:]) + self.w_[0]

    def predict(self, X):
        """Return class label after unit step"""
        return np.where(self.net_input(X) >= 0.0, 1, -1)


df = pd.read_csv('iris.csv', header=None)
print(df.tail())
y = df.iloc[0:100, 4].values
#print(y)

y = np.where(y == 'Iris-setosa', -1, 1)
#print(y)

X = df.iloc[0:100,[0,2]].values
print(X)

plt.scatter(X[:50, 0], X[:50,1], label='setosa', color='red', marker='o')
plt.scatter(X[50:100,0], X[50:100, 1], label='versicolor', color='blue',marker='x')
plt.xlabel('petal length')
plt.ylabel('sepal length')
plt.legend()
plt.show()

ppn = Perceptron(0.1, 10)
ppn.fit(X,y)
plt.plot(range(1,len(ppn.errors_)+1), ppn.errors_, marker='o')
plt.xlabel('epoch')
plt.ylabel('Number of misclassification')
plt.show()

您的代码的结果 enter image description here

更正后的代码的结果 enter image description here