首页 > 解决方案 > ValueError:形状(2,)和(5,)未对齐:2(dim 0)!= 5(dim 0)

问题描述

在看到神经网络的 youtube 视频后,我尝试用 numpy 从头开始​​创建一个,但它给了我一个错误,即尺寸错误。我对矩阵或 numpy 不太了解,这就是我无法得到答案的原因。如果有人可以帮助我建立我的网络,我会非常高兴。

import numpy as np

class NeuralNetwork:

    def __init__(self, input_size, hidden_size, output_size):
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.w1 = np.random.randn(self.input_size, self.hidden_size)
        self.w2 = np.random.randn(self.hidden_size, self.output_size)

    def sigmoid(self, n):
        return 1 / (1 + np.exp(-n))

    def sigmoid_prime(self, n):
        return self.sigmoid(n) * (1 - self.sigmoid(n))

    def propagation(self, x, y):
        # forward 
        hidden1 = np.dot(x, self.w1)
        hidden = self.sigmoid(hidden1)
        output1 = np.dot(hidden, self.w2)
        output = self.sigmoid(output1)
        # backward
        output_error = y - output
        output_delta = output_error * self.sigmoid_prime(output)
        hidden_error = output_delta.dot(self.w2.T)
        hidden_delta = hidden_error*self.sigmoid_prime(hidden)
        self.w1 += x.T.dot(hidden_delta)
        self.w2 += hidden.T.dot(output_delta)

    def predict(self, x):
        hidden1 = np.dot(x, self.w1)
        hidden = self.sigmoid(hidden1)
        output1 = np.dot(hidden, self.w2)
        output = self.sigmoid(output1)
        return(output)


MyNet = NeuralNetwork(2, 5, 1)

for _ in range(500):
    MyNet.propagation(
        np.array([0, 1]),
        np.array([1])
    )

print(MyNet.predict( np.array([0, 1])))

标签: pythonnumpymatrixneural-network

解决方案


为了方便帮助,请在帖子中指出错误发生在哪里以及哪一个。

正如我所看到的,您正在尝试执行以下操作(在数学公式中是正确的):

在此处输入图像描述

您遇到的问题是,当您的向量只有一个维度时,您正在尝试执行矩阵乘法。要解决这个问题,您应该简单地使用 reshape:

self.w1 + = x.T.reshape(-1, 1).dot(hidden_delta.reshape(1, -1))
self.w2 + = hidden.T.reshape(-1, 1).dot(output_delta.reshape(1, -1))

我建议您在使用 sigmoid 时不要使用 MSE 错误(|| y - y_pred||^2),而是使用交叉熵。当您处理概率时,这是一个更好的衡量标准。

交叉熵定义如下:

在此处输入图像描述

# cross_entropy = - y log(x) + (1 - y) log(1 - x)
# dcross_entropy/dx = - y / x + (1 - y) / (1 - x)
output_error = (-y / (output + 1e-10)) + ((1 - y) / ( (1 - output) + 1e-10))

编辑

import numpy as np

class NeuralNetwork:

    def __init__(self, input_size, hidden_size, output_size, lr=0.1):
        self.lr = lr
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.w1 = np.random.randn(self.input_size, self.hidden_size)
        self.w2 = np.random.randn(self.hidden_size, self.output_size)

    def sigmoid(self, n):
        return 1 / (1 + np.exp(-n))

    """def sigmoid_prime(self, n):
        return self.sigmoid(n) * (1 - self.sigmoid(n))"""

    def propagation(self, x, y):
        # forward 
        hidden1 = np.dot(x, self.w1)
        hidden = self.sigmoid(hidden1)
        output1 = np.dot(hidden, self.w2)
        output = self.sigmoid(output1)

        loss = -np.sum(y*np.log(output) + (1 - y)*np.log(1 - output), axis=-1)
        print('Loss:', np.mean(loss))

        # backward
        #output_error = (-y / (output + 1e-10)) + ((1 - y) / ( (1 - output) + 1e-10))
        #output_delta = output_error * output * (1 - output)
        # simplified
        output_delta = - y*(1 - output) + (1 - y)*output
        self.w2 += - self.lr*hidden.T.dot(output_delta) / x.shape[0]

        hidden_error = output_delta.dot(self.w2.T)
        hidden_delta = hidden_error* hidden * (1 - hidden)
        self.w1 += - self.lr*x.T.dot(hidden_delta) / x.shape[0]

    def predict(self, x):
        hidden1 = np.dot(x, self.w1)
        hidden = self.sigmoid(hidden1)
        output1 = np.dot(hidden, self.w2)
        output = self.sigmoid(output1)
        return(output)


MyNet = NeuralNetwork(2, 10, 1)

for _ in range(50000):
    MyNet.propagation(
        np.array([[0, 1], [1, 0], [1, 1], [0, 0]]),
        np.array([[1], [1], [0], [0]])
    )

print(MyNet.predict( np.array([0, 0]).reshape(1, -1)))
print(MyNet.predict( np.array([0, 1]).reshape(1, -1)))
print(MyNet.predict( np.array([1, 0]).reshape(1, -1)))
print(MyNet.predict( np.array([1, 1]).reshape(1, -1)))


推荐阅读