Gradient Checks for ANN Yujia Bao Mar 7, 2017
Finite Difference Let 𝑓(𝑥) be any differentiable function, we can approximate its derivative by d𝑓(𝑥) d𝑥 = 𝑓 𝑥+𝜖 −𝑓(𝑥−𝜖) 2𝜖 +𝑂( 𝜖 2 ) for some very small number 𝜖.
How to compare the numerical gradient with the analytic gradient?
Relative Error Let 𝑓 𝑛 ′ be the numerical gradient calculated using finite difference, and 𝑓 𝑎 ′ be the analytic gradient calculated using back prop. Define the relative error 𝑒𝑟𝑟𝑜𝑟= 𝑓 𝑎 ′ − 𝑓 𝑛 ′ max 𝑓 𝑎 ′ , 𝑓 𝑛 ′ , 𝑒𝑝𝑠𝑖𝑙𝑜𝑛
Relative Error 𝑒𝑟𝑟𝑜𝑟> 10 −4 usually means the analytic gradient is wrong. 𝑒𝑟𝑟𝑜𝑟< 10 −4 is fine for sigmoid activation (including logistic, tanh, softmax). But if you are using (leaky) ReLU, then 10 −4 might be too large. 𝑒𝑟𝑟𝑜𝑟< 10 −7 means your analytic gradient is correct.
Debugging Procedure Goal: Check the gradient for a single weight 𝑤 is computed correctly. Given: One example (Input features with a label) Forward prop and Backward prop to get the gradient for 𝑤. Let 𝑤←𝑤+𝜖 (I usually choose 𝜖= 10 −5 ). Forward prop to get the output, and then compute the loss. Let 𝑤←𝑤−2𝜖 (Now 𝑤 is 𝑤 𝑜𝑟𝑖𝑔𝑖𝑛 −𝜖). Check the relative error. Recover the origin weight by 𝑤←𝑤+𝜖.
Debugging Procedure Suppose our network has the following structure: Input -> Conv1 -> Pool1 -> Conv2 -> Pool2 -> ReLU -> Output If the gradients from Input to Conv1 are correct, then we are done! Otherwise, we check the gradients from Pool1 to Conv2 (since there is no weights from Conv1 to Pool1). If it is correct, then this means there are some bugs in our Back prop code from Pool1 to Input. And so on…
Thanks.