14、改善深层神经网络之梯度检验
什么为梯度检验???
梯度检验可以作为检验神经网络是否有bug的一种方法,现神经网络的反向传播算法含有许多细节,在编程实现中很容易出现一些微妙的bug,但往往这些bug并不会影响你的程序运行,而且你的损失函数看样子也在不断变小。但最终,你的程序得出的结果误差将会比那些无bug的程序高出一个数量级,最终的结果可能并不是最优解。
梯度检验的原理
梯度检验法是通过一种简单的方法取得近似的梯度,将这个近似的梯度与真正的梯度对比,如果很接近,则认为梯度正确,否则认为梯度有误。
将J(θ)和θ放入直角坐标系,下图所示是θ取定值时J(θ)的导数:
ε 是一个很小的值:
如上图所示:
当ε→0时,这趋近于导数的定义:
在实际的应用中,θ往往是一个向量,梯度下降算法要求我们对向量中的每一个分量进行偏导数的计算,对于偏导数,我们同样可以用以下式子进行近似计算:
梯度检验代码检验
1、构建一个AI模型来判断是否可靠
首先我们需要先导入相关的库
import numpy as np from testCases import * from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector
在这里我们所用到的testCases.py与gc_utils.py代码如下:
import numpy as np def sigmoid(x): """ Compute the sigmoid of x Arguments: x -- A scalar or numpy array of any size. Return: s -- sigmoid(x) """ s = 1/(1+np.exp(-x)) return s def relu(x): """ Compute the relu of x Arguments: x -- A scalar or numpy array of any size. Return: s -- relu(x) """ s = np.maximum(0,x) return s def dictionary_to_vector(parameters): """ Roll all our parameters dictionary into a single vector satisfying our specific required shape. """ keys = [] count = 0 for key in ["W1", "b1", "W2", "b2", "W3", "b3"]: # flatten parameter new_vector = np.reshape(parameters[key], (-1,1)) keys = keys + [key]*new_vector.shape[0] if count == 0: theta = new_vector else: theta = np.concatenate((theta, new_vector), axis=0) count = count + 1 return theta, keys def vector_to_dictionary(theta): """ Unroll all our parameters dictionary from a single vector satisfying our specific required shape. """ parameters = {} parameters["W1"] = theta[:20].reshape((5,4)) parameters["b1"] = theta[20:25].reshape((5,1)) parameters["W2"] = theta[25:40].reshape((3,5)) parameters["b2"] = theta[40:43].reshape((3,1)) parameters["W3"] = theta[43:46].reshape((1,3)) parameters["b3"] = theta[46:47].reshape((1,1)) return parameters def gradients_to_vector(gradients): """ Roll all our gradients dictionary into a single vector satisfying our specific required shape. """ count = 0 for key in ["dW1", "db1", "dW2", "db2", "dW3", "db3"]: # flatten parameter new_vector = np.reshape(gradients[key], (-1,1)) if count == 0: theta = new_vector else: theta = np.concatenate((theta, new_vector), axis=0) count = count + 1 return theta
gc_utils
import numpy as np def gradient_check_n_test_case(): np.random.seed(1) x = np.random.randn(4,3) y = np.array([1, 1, 0]) W1 = np.random.randn(5,4) b1 = np.random.randn(5,1) W2 = np.random.randn(3,5) b2 = np.random.randn(3,1) W3 = np.random.randn(1,3) b3 = np.random.randn(1,1) parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2, "W3": W3, "b3": b3} return x, y, parameters
testCases
首先我们进行简单的1维的梯度检验,后面再学N维的,便于理解
假设我们有一个简单的1维线性函数J(θ)=θxJ这个函数(这个模型)只有一个参数θ;x是输入。下面我们会用代码来计算出J(.)J(.)(用前向传播计算出成本)然后计算出
(用反向传播计算出梯度)。最后我们用梯度检验来证明反向传播计算出来的梯度是正确的。
上面的流程图显示出了关键的步骤:输入 x;然后计算出 J(x)J前向传播);然后计算出梯度(反向传播),代码如下:
# 前向传播 def forward_propagation(x, theta): J = np.dot(theta, x) return J
x, theta = 2, 4 J = forward_propagation(x, theta) print ("J = " + str(J))
J = 8
# 反向传播 def backward_propagation(x, theta): # 这个函数的导数就是x,这是由微积分公式得来的,如果你没有学过微积分,没有关系,不用弄明白为什么。重点不在于此。 dtheta = x return dtheta
x, theta = 2, 4 dtheta = backward_propagation(x, theta) print ("dtheta = " + str(dtheta))
dtheta = 2
下面我们将用梯度检验来确认上面反向传播计算出来的梯度dtheta是正确的。主要步骤如下:
def gradient_check(x, theta, epsilon=1e-7): # 利用前向传播计算出一个梯度 thetaplus = theta + epsilon thetaminus = theta - epsilon J_plus = forward_propagation(x, thetaplus) J_minus = forward_propagation(x, thetaminus) gradapprox = (J_plus - J_minus) / (2 * epsilon) # 利用反向传播也计算出一个梯度 grad = backward_propagation(x, theta) # 对比两个梯度相差多远 numerator = np.linalg.norm(grad - gradapprox) denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) difference = numerator / denominator if difference < 1e-7: print("反向传播是正确的!") else: print("反向传播有问题!") return difference
x, theta = 2, 4 difference = gradient_check(x, theta) print("difference = " + str(difference))
反向传播是正确的! difference = 2.919335883291695e-10
但是通常情况下,神经网络的成本函数不仅仅只有一个1维的参数。在神经网络模型中,θθ通常是由多个W[l]W[l]和b[l]b[l]矩阵构成的。所以学会如何给多维参数做梯度检验是很重要的。下面我们就来学习多维参数的梯度检验!
上图展示了你的支付可靠度预测模型的前向传播和反向传播流程,下面为前向传播和反向传播的代码实现:
def forward_propagation_n(X, Y, parameters): m = X.shape[1] W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] W3 = parameters["W3"] b3 = parameters["b3"] # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID Z1 = np.dot(W1, X) + b1 A1 = relu(Z1) Z2 = np.dot(W2, A1) + b2 A2 = relu(Z2) Z3 = np.dot(W3, A2) + b3 A3 = sigmoid(Z3) logprobs = np.multiply(-np.log(A3), Y) + np.multiply(-np.log(1 - A3), 1 - Y) cost = 1. / m * np.sum(logprobs) cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) return cost, cache
def backward_propagation_n(X, Y, cache): m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache dZ3 = A3 - Y dW3 = 1. / m * np.dot(dZ3, A2.T) db3 = 1. / m * np.sum(dZ3, axis=1, keepdims=True) dA2 = np.dot(W3.T, dZ3) dZ2 = np.multiply(dA2, np.int64(A2 > 0)) dW2 = 1. / m * np.dot(dZ2, A1.T) * 2 # ~~ db2 = 1. / m * np.sum(dZ2, axis=1, keepdims=True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, np.int64(A1 > 0)) dW1 = 1. / m * np.dot(dZ1, X.T) db1 = 4. / m * np.sum(dZ1, axis=1, keepdims=True) # ~~ gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3, "dA2": dA2, "dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1} return gradients
下面进行多维度梯度检验:
多维检验中的θ不再是一个数值,而是一个字典,字典里面包含了很多个参数。现在实现一个函数”dictionary_to_vector()
“,用它可以将这个字典转换成一个向量,它会改变字典里参数(W1, b1, W2, b2, W3, b3)的维度并且将它们连接起来构成一个大向量,这个向量我们用”values”来表示,同时也另外一个逆操作的函数”vector_to_dictionary
“,它会将向量转换回字典形式。
转化代码如下:
# 友情赠送向量转换为字典 def vector_to_dictionary(theta): parameters = {} parameters["W1"] = theta[:20].reshape((5,4)) parameters["b1"] = theta[20:25].reshape((5,1)) parameters["W2"] = theta[25:40].reshape((3,5)) parameters["b2"] = theta[40:43].reshape((3,1)) parameters["W3"] = theta[43:46].reshape((1,3)) parameters["b3"] = theta[46:47].reshape((1,1)) return parameters def gradients_to_vector(gradients): count = 0 for key in ["dW1", "db1", "dW2", "db2", "dW3", "db3"]: # flatten parameter new_vector = np.reshape(gradients[key], (-1,1)) if count == 0: theta = new_vector else: theta = np.concatenate((theta, new_vector), axis=0) count = count + 1 return theta
向量转换为字典
代码如下:
def gradient_check_n(parameters, gradients, X, Y, epsilon=1e-7): parameters_values, _ = dictionary_to_vector(parameters) grad = gradients_to_vector(gradients) num_parameters = parameters_values.shape[0] J_plus = np.zeros((num_parameters, 1)) J_minus = np.zeros((num_parameters, 1)) gradapprox = np.zeros((num_parameters, 1)) # 计算gradapprox for i in range(num_parameters): thetaplus = np.copy(parameters_values) thetaplus[i][0] = thetaplus[i][0] + epsilon J_plus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaplus)) thetaminus = np.copy(parameters_values) thetaminus[i][0] = thetaminus[i][0] - epsilon J_minus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaminus)) gradapprox[i] = (J_plus[i] - J_minus[i]) / (2 * epsilon) numerator = np.linalg.norm(grad - gradapprox) denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) difference = numerator / denominator if difference > 2e-7: print("\033[93m" + "反向传播有问题! difference = " + str(difference) + "\033[0m") else: print("\033[92m" + "反向传播很完美! difference = " + str(difference) + "\033[0m") return difference
X, Y, parameters = gradient_check_n_test_case() cost, cache = forward_propagation_n(X, Y, parameters) gradients = backward_propagation_n(X, Y, cache) difference = gradient_check_n(parameters, gradients, X, Y)
[93m反向传播有问题! difference = 0.2850931566540251[0m
注意:
- 梯度检验是很缓慢的。通过
来计算梯度非常消耗计算力。所以,我们不会在训练的每一个回合都执行梯度检验。仅仅偶尔执行几次。
- 梯度检验是无法与dropout共存的。所以在执行梯度检验时,要把dropout关掉,检验完毕后再开启。
**本次实战编程需要记住的几点**:
-
梯度检验通过用前向传播的方式求出一个梯度,然后将其与反向传播求出的梯度进行对比来判断梯度是否正确
-
梯度检验很浪费计算力。所以只在需要验证代码是否正确时才开启。确认代码没有问题后,就关闭掉梯度检验。
参考:https://gitee.com/bijingrui1997/deep_learning_notes/blob/master/