我从头到尾做了一个神经网络,想让它运行得更快一点。我在想,把我的前道具矢量化是否会让它更快。我目前的前向道具代码是:
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])如果矢量化将使这更快,我将如何向量化呢?提前感谢!
发布于 2020-08-10 18:02:38
,我在想,将我的前支柱矢量化是否会使它更快,
是!
,我怎么把这个矢量化呢?
你想要消除循环,找出向量代数来做同样的事情。
假设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.relu和self.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)发布于 2020-10-12 19:37:33
矢量法向前支柱使MLP运行得更快。我用了@接线员。
def forwardProp(self, inputs):
self.secondLayerNeurons = self.sigmoid(self.w1 @ inputs + self.b1)
self.outputNeurons = self.sigmoid(self.w2 @ self.secondLayerNeurons + self.b2)https://stackoverflow.com/questions/63345498
复制相似问题