向量化前向传播

Vectorize Forward Propagation

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

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

如果矢量化可以使它更快,我将如何对其进行矢量化?提前致谢!

我想知道对我的前向 prop 进行矢量化是否会使它更快

是的!

我如何对其进行矢量化?

您想消除循环并找出可以做同样事情的向量代数。

假设 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的整个vector相加而不用循环,

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

下一步,确保 self.reluself.sigmoid 可以使用向量,并且 return 可以为向量的每个元素使用任何你需要的东西。这可能涉及与向量化逐行点积类似的恶作剧。

所以最后你有:

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)