【发布时间】:2020-06-17 11:28:31
【问题描述】:
我一直在尝试从头开始制作自己的神经网络。一段时间后,我做到了,但遇到了一个我无法解决的问题。我一直在关注tutorial,它展示了如何做到这一点。我遇到的问题是我的网络如何更新权重和偏差。好吧,我知道梯度下降不会总是减少损失,并且在几个时期它甚至可能会增加一点,它仍然应该减少并且比我的工作得更好。有时整个过程卡在损失 9 和 13 上,无法摆脱。我检查了许多教程、视频和网站,但我在我的代码中找不到任何错误。
self.activate、self.dactivate、self.loss 和 self.dloss:
# sigmoid
self.activate = lambda x: np.divide(1, 1 + np.exp(-x))
self.dactivate = lambda x: np.multiply(self.activate(x), (1 - self.activate(x)))
# relu
self.activate = lambda x: np.where(x > 0, x, 0)
self.dactivate = lambda x: np.where(x > 0, 1, 0)
# loss I use (cross-entropy)
clip = lambda x: np.clip(x, 1e-10, 1 - 1e-10) # it's used to squeeze x into a probability between 0 and 1 (which I think is required)
self.loss = lambda x, y: -(np.sum(np.multiply(y, np.log(clip(x))) + np.multiply(1 - y, np.log(1 - clip(x))))/y.shape[0])
self.dloss = lambda x, y: -(np.divide(y, clip(x)) - np.divide(1 - y, 1 - clip(x)))
我用于前向传播的代码:
self.activate(np.dot(X, self.weights) + self.biases) # it's an example for first hidden layer
这就是反向传播的代码:
第一部分,DenseNeuralNetwork 类:
last_derivative = self.dloss(output, y)
for layer in reversed(self.layers):
last_derivative = layer.backward(last_derivative, self.lr)
第二部分,Dense 类:
def backward(self, last_derivative, lr):
w = self.weights
dfunction = self.dactivate(last_derivative)
d_w = np.dot(self.layer_input.T, dfunction) * (1./self.layer_input.shape[1])
d_b = (1./self.layer_input.shape[1]) * np.dot(np.ones((self.biases.shape[0], last_derivative.shape[0])), last_derivative)
self.weights -= np.multiply(lr, d_w)
self.biases -= np.multiply(lr, d_b)
return np.dot(dfunction, w.T)
我还做了一个repl,这样你就可以检查整个代码并毫无问题地运行它。
【问题讨论】:
标签: python numpy machine-learning deep-learning neural-network