【问题标题】:Non-broadcastable output operand with shape (2,) doesn't match the broadcast shape (1,2)形状为 (2,) 的不可广播输出操作数与广播形状 (1,2) 不匹配
【发布时间】:2019-09-01 20:16:12
【问题描述】:

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

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

【问题讨论】:

  • 你修好了吗?

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


【解决方案1】:

你能解释一下你在这个街区想要做什么吗?

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]

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

【讨论】:

  • 例如我的用户发送20,10,30(Inpu1,Input2,输出)的输入。我通过使用split命令来分离,我添加到Training_Inputs和标签。顺便说一下,我通过使用S.POP函数来从输入数据中分开OUTPU数据。 span>
猜你喜欢
  • 2021-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 2018-05-09
  • 2020-03-07
  • 2020-08-03
  • 2019-06-13
相关资源
最近更新 更多