Yavuzhan Erdem
Yavuzhan Erdem

Reputation: 23

Non-broadcastable output operand with shape (2,) doesn't match the broadcast shape (1,2)

I am trying to train a perceptron by giving inputs. There are a problem called

"ValueError: non-broadcastable output operand with shape (2,) doesn't match the broadcast shape (1,2) We've got an error while stopping in post-mortem: "

import numpy as np


class Perceptron(object):

    def __init__(self, no_of_inputs, threshold=1000, learning_rate=0.01):
        self.threshold = threshold
        self.learning_rate = learning_rate
        self.weights = np.zeros(no_of_inputs + 1)

    def predict(self, inputs):
        summation = np.dot(inputs, self.weights[1:]) + self.weights[0]
        if summation > 0:
            activation = 1
        else:
            activation = -1
        return activation

    def train(self, training_inputs, labels):
        for _ in range(self.threshold):
            for inputs, label in zip(training_inputs, labels):
                prediction = self.predict(inputs)

                self.weights[1:] += self.learning_rate * (label - prediction) * inputs
                self.weights[0] += self.learning_rate * (label - prediction)


try:
    training_inputs=[]
    labels =[]
    temp = []
    test_data=[]
    for i in range(4):
        s=input()
        s=s.split(',')
        labels.append((np.array([s.pop()]).astype(np.int)))
        training_inputs.append((np.array([s]).astype(np.float)))

    perceptron = Perceptron(2)

    perceptron.train(training_inputs, labels)

    for test in range(4):
        s = input()
        s = s.split(',')
        test_data.append(np.array([s]))
        result=perceptron.predict(test_data)
        if result > 0:
            print("+{}".format(result))
        else:
            print(result)

Upvotes: 0

Views: 904

Answers (1)

Shubham Shaswat
Shubham Shaswat

Reputation: 1310

can you explain what are you trying to do in this block?

for i in range(4):
    s=input()
    s=s.split(',')
    labels.append((np.array([s.pop()]).astype(np.int)))
    training_inputs.append((np.array([s]).astype(np.float)))

I think this the code where you messed up

def predict(self, inputs):
    summation = np.dot(inputs, self.weights[1:]) + self.weights[0]

check if inputs and weights have same shape

Upvotes: 0

Related Questions