Search code examples
python-3.xmachine-learningperceptron

Perceptron Code in Python on Iris data not converging


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()

The above code is copied from a book but unfortunately the error is not converging to 0 on Iris data. The error is bouncing between two values 3.0 and 2.0. Need help to understand where I am going wrong.

Please consider me a novice in machine learning arena and any insight would be much appreciated.


Solution

  • I have just reviewed your code and found out some problems. Don't worry I have corrected it.

    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()
    

    Result from your code enter image description here

    Result from corrected code enter image description here