如何解决向量化正向传播
我从头开始制作了一个神经网络,并希望使其运行更快。我想知道矢量化我的前进道具是否会使它更快。 我当前的前向道具代码是:
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.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)
,
向量化前向道具使MLP的运行速度大大加快。我使用了@运算符。
def forwardProp(self,inputs):
self.secondLayerNeurons = self.sigmoid(self.w1 @ inputs + self.b1)
self.outputNeurons = self.sigmoid(self.w2 @ self.secondLayerNeurons + self.b2)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。