矢量化前向传播

2024-10-02 12:36:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我从头制作了一个神经网络,希望它运行得更快一点。我想知道矢量化我的前进道具是否会使它更快。 我当前的前进道具代码是:

def forwardProp(self, inputs):
    for i in range (self.dimensions[1]):
        self.secondLayerNeurons[i] = self.relu(np.dot(self.firstLayerWeights[i], inputs)+self.firstLayerBiases[i])
    for i in range (self.dimensions[2]):
        self.outputNeurons[i] = self.sigmoid(np.dot(self.secondLayerWeights[i], self.secondLayerNeurons)+self.secondLayerBiases[i])

如果矢量化可以加快速度,我将如何进行矢量化?提前谢谢


Tags: 代码inselffordefnprange神经网络
2条回答

我想知道将我的前进道具矢量化是否会使它更快

对!

如何将其矢量化?

你想消除循环,找出向量代数,也能做同样的事情

让我们说self.firstLayerWeights.shape(N, D)。你想要calculate the row-wise dot product of this matrix with ^{}。假设您在一个名为rowwise_dot的函数中实现了这个逻辑

def rowwise_dot(inpA, inpB):
    # Calculate and return rowwise dot

现在有了rowwise_dot函数,可以添加整个self.firstLayerBiases向量,而无需循环

rowwise_dot(self.firstLayerWeights, inputs) + self.firstLayerBiases

接下来,确保self.reluself.sigmoid可以获取向量,并为向量的每个元素返回所需的内容。这可能涉及类似的把戏,如矢量化逐行点积

因此,最后你有:

def forwardProp(self, inputs):
    self.secondLayerNeurons = self.relu(rowwise_dot(self.firstLayerWeights, inputs) + self.firstLayerBiases)
    self.outputNeurons = self.sigmoid(rowwise_dot(self.secondLayerWeights, self.secondLayerNeurons) + self.secondLayerBiases)

矢量化前进道具使MLP跑得更快。我用了@operator

    def forwardProp(self, inputs):
        self.secondLayerNeurons = self.sigmoid(self.w1 @ inputs + self.b1)
        self.outputNeurons = self.sigmoid(self.w2 @ self.secondLayerNeurons + self.b2)

相关问题 更多 >

    热门问题