Error in my implemetation of Python perceptron algorithm

Viewed 34

I'm trying to implement this Perceptron Algorithm by using Python. However, when I run my code, the result is not correct. Can anyone help me point the mistakes in my code. I'm very grateful for this.

The version of Perceptron Algorithm I use: enter image description here

This is my code:

import numpy as np
class Perceptron(object):
    def __init__(self, eta=0.5, iter_=20):
        self.eta = eta # learning rate
        self.iter = iter_
        self.w = []
        self.theta = 0
 
    def summation(self, x):
        y = np.dot(x, self.w)
        return y
 
    def predict(self, x):
        return np.where(self.summation(x) >= 0, 1, 0)
 
    def train(self, x, y):
        # Initiallize w = [0,...,0] with no. 0 equals size of x_i, or dimension of 1 sample in x
        # shape of w = (dim of 1 sample of x, ), blank means w just having 1 row
        self.w = np.zeros(shape=(x.shape[1],))
 
        np.insert(x, 0, 1, axis=1) # x0 = 1
        np.insert(self.w, 0, -self.theta, axis=0) # w0 = -theta  
 
        for _ in range(self.iter):
            flag = 0
            for inputs, targets in zip(x,y): # run inputs in x, targets in y parallelly
                pred_output = self.predict(inputs)
                if targets < pred_output:
                    flag = 1
                    self.w += self.eta * inputs
                    self.theta += self.eta  
                if targets > pred_output:
                    flag = 1
                    self.w -= self.eta * inputs
                    self.theta -= self.eta
 
            if flag == 0: # Complete training
                return self
 
ann = Perceptron(0.5,10)
 
x = np.array([
    [0,0],
    [0,1],
    [1,0],
    [1,1],
])
 
y = np.array([0,0,0,1])
 
ann.train(x,y)
 
ann.predict([0,1])
0 Answers
Related