Skip to main content
 首页 » 编程设计

python之我的梯度检查实现中是否存在这些可接受的梯度差异

2025年01月19日9java哥

我正在构建一个带有几个 FC 层的 CNN 来预测图像中描绘的类。

架构:

X -> CNN -> ReLU -> POOL -> FC -> ReLU -> FC -> SOFTMAX -> Y_hat

我正在实现梯度检查以检查我的梯度下降实现是否正确。我读到可接受的差异大约为 10e-9。下面的差异看起来可以接受吗?

Epoch: 0 
Cost: 2.8568426944476157 
Numerical Grad           Computed Grad 
-5.713070134419862e-11   -6.616929226765933e-11 
-5.979710331310053e-11   -6.94999613415348e-11 
-5.87722383797037e-11    -6.816769371198461e-11 
-5.948114792212038e-11   -6.905587213168474e-11 
-5.756886551189494e-11   -6.683542608243442e-11 
-5.995452767971952e-11   -6.94999613415348e-11 
-5.772401095738584e-11   -6.705747068735946e-11 
-5.5480026579651e-11     -6.439293542825908e-11 
-5.8138150324971285e-11  -6.727951529228449e-11 
-5.76037967235867e-11    -6.683542608243442e-11 

作为引用,这里是我的梯度检查实现:

def gradient_check(self, layer): 
    # get grads from layer 
    grads = layer.backward_cache['dW'] 
    # flatten layer W 
    shape = layer.W.shape 
    W_flat = layer.W.flatten() 
 
    epsilon = 0.001 
 
    print('Numerical Grad', 'Computed Grad') 
    # loop through first few W's 
    for i in range(0, 10): 
        W_initial = W_flat[i] 
        W_plus = W_initial + epsilon 
        W_minus = W_initial - epsilon 
 
        W_flat[i] = W_plus 
        layer.W = W_flat.reshape(shape) 
        cost_plus = self.compute_cost(self.forward_propogate()) 
 
        W_flat[i] = W_minus 
        layer.W = W_flat.reshape(shape) 
        cost_minus = self.compute_cost(self.forward_propogate()) 
 
        computed_grad = (cost_plus - cost_minus) / (2 * epsilon) 
 
        print(grads.flatten()[i], computed_grad) 
 
        # reset layers W's 
        W_flat[i] = W_initial 
        layer.W = W_flat.reshape(shape) 
 
    return layer 

请您参考如下方法:

在研究了梯度接近于零的原因后,我发现我的网络可能存在梯度平台问题。解决方案是添加以下一项或全部:动量、RMS prop 或 Adam 优化。我将尝试实现 Adam 优化,因为它封装了动量和 RMS prop,如果可行,我会将我的答案标记为正确。

后续编辑:不幸的是,当我实现 Adam 时,这只会导致梯度爆炸。即使学习率非常小 1e-5。通过添加两个更多的 conv->relu->pool 层,我确实在增加数值梯度方面取得了一些进展。但无论哪种方式,梯度计算似乎都不正确。问题一定出在我对反向传播的实现上。