【问题标题】:Weights in Neural Network神经网络中的权重
【发布时间】:2020-05-07 06:04:07
【问题描述】:

我正在阅读:https://towardsdatascience.com/how-to-build-your-own-neural-network-from-scratch-in-python-68998a08e4f6

我看到了以下代码:

import numpy as np

def sigmoid(x):
    return 1.0/(1+ np.exp(-x))

def sigmoid_derivative(x):
    return x * (1.0 - x)

class NeuralNetwork:
    def __init__(self, x, y):
        self.input      = x
        self.weights1   = np.random.rand(self.input.shape[1],4) 
        self.weights2   = np.random.rand(4,1)                 
        self.y          = y
        self.output     = np.zeros(self.y.shape)

    def feedforward(self):
        self.layer1 = sigmoid(np.dot(self.input, self.weights1))
        self.output = sigmoid(np.dot(self.layer1, self.weights2))

    def backprop(self):
        # application of the chain rule to find derivative of the loss function with respect to weights2 and weights1
        d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output)))
        d_weights1 = np.dot(self.input.T,  (np.dot(2*(self.y - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1)))

        # update the weights with the derivative (slope) of the loss function
        self.weights1 += d_weights1
        self.weights2 += d_weights2


if __name__ == "__main__":
    X = np.array([[0,0,1],
                  [0,1,1],
                  [1,0,1],
                  [1,1,1]])
    y = np.array([[0],[1],[1],[0]])
    nn = NeuralNetwork(X,y)

    for i in range(1500):
        nn.feedforward()
        nn.backprop()

    print(nn.output)

权重不应该是 4x4 随机矩阵吗,因为我们在隐藏层中有 4 个神经元和 4 个输入值,所以权重的总数应该是 16,但是下面的代码在 init 函数中分配了一个 2x4 的矩阵并创建了一个点积?

【问题讨论】:

  • 这个网络只有一个隐藏层和一个输出层,不是四个。
  • 对不起,我的意思是隐藏层中有 4 个神经元。

标签: python machine-learning neural-network


【解决方案1】:

您的输入矩阵X 表明样本数为 4,特征数为 3。神经网络输入层中的神经元数等于特征数*,而不是样本数。例如,假设您有 4 辆汽车,您为每辆汽车选择了 3 个特征:颜色、座位数和原产国。对于每个汽车样本,您将这 3 个特征提供给网络并训练您的模型。即使你有 4000 个样本,输入神经元的数量也不会改变;现在是 3。

所以self.weights1 的形状为(3, 4),其中 3 是特征数,4 是隐藏神经元数(这 4 与样本数无关),正如预期的那样。

*:有时输入会增加1(或-1)以解决偏差,因此在这种情况下输入神经元的数量将是num_features + 1;但这是一个选择是否单独处理偏差。

【讨论】:

  • 谢谢你,这很有帮助,多个在线教程使用相同数量的输入作为输入层中的神经元数量。我从您的回答中了解到,它的特征是输入中的列数,它定义了输入层的大小。如果我理解正确,请告诉我。
  • 是的,特征的数量总是决定输入神经元的数量。设计矩阵 X 的通常约定是具有形状 (num_samples, num_features) 所以是的,它通常是输入矩阵的列数。看来你明白了。
猜你喜欢
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
  • 2019-01-23
  • 2015-05-03
  • 2019-02-09
  • 2017-09-01
相关资源
最近更新 更多