形状为(2,)的不可广播输出操作数与广播形状(1,2)不匹配

时间:2019-04-11 08:49:59

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

我正在尝试通过提供输入来训练感知器。 有一个名为

的问题

“ ValueError:形状为(2,)的不可广播的输出操作数与广播形状(1,2)不匹配 验尸停止时出现错误:“

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)

1 个答案:

答案 0 :(得分:0)

您能解释一下您在这个区块中打算做什么吗?

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

我认为这是您搞砸的代码

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

检查输入和权重是否具有相同的形状