向量化正向传播

问题描述

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

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

如果向量化可以使其更快,我将如何向量化呢?预先感谢!

解决方法

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

是的!

我将如何对此向量化?

您要消除循环并找出向量代数,它们将做同样的事情。

假设self.firstLayerWeights.shape(N,D)。您想calculate the row-wise dot product of this matrix with inputs。假设您在名为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的运行速度大大加快。我使用了@运算符。

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