如果打不开,也可以复制链接到https://nbviewer.jupyter.org中打开。
正则化 Regularization
欢迎来到本周的第二个作业。DL模型具有很大的灵活性和容量,如果训练集不够大,那么过拟合可能是一个严重的问题。此时,模型在训练集上当然会做的很好,但是不能泛化到它从没有看到过的新样本。
通过本作业,你将学习:在你的DL模型中使用正则。
首先引入你要使用的库。
# import packages
import numpy as np
import matplotlib.pyplot as plt
from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
import sklearn
import sklearn.datasets
import scipy.io
from testCases import *
#%matplotlib inline Notebook中使用
plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
运行代码,如果是python 3会有以下报警,可以忽略
reg_utils.py:86: SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert(parameters['W' + str(l)].shape == layer_dims[l], 1)
问题描述:你作为一个AI专家被一个法国足球公司雇佣。公司希望你推荐一个位置,门将朝这个位置开球,法国队球员就可以用头顶到球。
公司给了你球队过去10场比赛的2D数据集。
获取数据代码如下
train_X, train_Y, test_X, test_Y = load_2D_dataset()
plt.show()
显示图像如下
图中的每个点表示,法国队门将从球场左边开球后,球被他/她顶到的位置。
- 蓝色表示法国队顶到球的位置
- 红色表示对手顶到球的位置
你的目标:使用DL模型找到一个位置,门将应该朝这里开球(自己的队友可以顶到球)。
数据集分析:这个数据集有一点点杂音,但是总体上来说,看上去可以用一条从左下到右上的对角线把数据一分为二,左上部分蓝色,右下部分红色。
你首先尝试没有正则化的模型。然后学习如何正则化它,最终找到一个模型来解决法国队的问题。
1.非正则化模型
你将使用以下NN(在前面已经实现)。该模型可以被用于:
- 正则化模式:将lambd输入设置为非零值。 我们使用“lambd”而不是“lambda”,因为“lambda”是Python中的保留关键字。
- dropout模式(随机删除神经元):设置keep_prob小于1。
你首先尝试非正则化模型。然后你将实现
- L2正则化:函数compute_cost_with_regularization()和backward_propagation_with_regularization()
- Dropout:函数forward_propagation_with_dropout()和backward_propagation_with_dropout()
在每个部分中,你将使用正确的输入运行此模型,以便它调用您已实现的函数。
观察以下代码,熟悉你的模型。
def model(X, Y, learning_rate = 0.3, num_iterations = 30000, print_cost = True, lambd = 0, keep_prob = 1):
"""
Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.
实现一个三层的神经网络
Arguments:
X -- input data, of shape (input size, number of examples) 输入的数据,维度为(2, 样本的数量)
Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (output size, number of examples)
learning_rate -- learning rate of the optimization 学习率
num_iterations -- number of iterations of the optimization loop 迭代次数
print_cost -- If True, print the cost every 10000 iterations
lambd -- regularization hyperparameter, scalar 正则化的超参,实数
keep_prob - probability of keeping a neuron active during drop-out, scalar. 随机删除节点的概率
Returns:
parameters -- parameters learned by the model. They can then be used to predict. 模型学习后的参数
"""
grads = {}
costs = [] # to keep track of the cost
m = X.shape[1] # number of examples
layers_dims = [X.shape[0], 20, 3, 1]
# Initialize parameters dictionary. 初始化参数
parameters = initialize_parameters(layers_dims)
# Loop (gradient descent)
for i in range(0, num_iterations):
#前向传播
# Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID.
if keep_prob == 1: #不随机删除节点(不使用dropout)
a3, cache = forward_propagation(X, parameters)
elif keep_prob < 1: #随机删除节点
a3, cache = forward_propagation_with_dropout(X, parameters, keep_prob)
# Cost function 成本函数
if lambd == 0: #不使用L2正则化
cost = compute_cost(a3, Y)
else: #使用L2
cost = compute_cost_with_regularization(a3, Y, parameters, lambd)
#反向传播
# Backward propagation.
#可以同时使用L2正则化和dropout,但是本次实验不同时使用。
assert(lambd == 0 or keep_prob == 1) # it is possible to use both L2 regularization and dropout,
# but this assignment will only explore one at a time
if lambd == 0 and keep_prob == 1: # 不使用L2正则化和不使用随机删除节点
grads = backward_propagation(X, Y, cache)
elif lambd != 0: # 使用L2正则化和不使用随机删除节点
grads = backward_propagation_with_regularization(X, Y, cache, lambd)
elif keep_prob < 1: # 不使用L2正则化和使用随机删除节点
grads = backward_propagation_with_dropout(X, Y, cache, keep_prob)
# Update parameters. 更新参数
parameters = update_parameters(parameters, grads, learning_rate)
# Print the loss every 10000 iterations
if print_cost and i % 10000 == 0:
print("Cost after iteration {}: {}".format(i, cost))
if print_cost and i % 1000 == 0:
costs.append(cost)
# plot the cost
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (x1,000)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters #返回学习后的参数
尝试不使用正则化训练模型,观察训练集/测试集正确率。
parameters = model(train_X, train_Y)
print("On the training set:")
predictions_train = predict(train_X, train_Y, parameters)
print("On the test set:")
predictions_test = predict(test_X, test_Y, parameters)
运行结果
Cost after iteration 0: 0.6557412523481002
Cost after iteration 10000: 0.16329987525724213
Cost after iteration 20000: 0.13851642423245572
On the training set:
Accuracy: 0.9478672985781991
On the test set:
Accuracy: 0.915
成本曲线如下
根据结果,训练正确率是 94.8%,测试准确率是91.5%.
这是基线模型baseline model(你将观察到正则化对这个模型的影响)。
运行以下代码来绘制模型的决策边界。
plt.title("Model without regularization")
axes = plt.gca()
axes.set_xlim([-0.75, 0.40])
axes.set_ylim([-0.75, 0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
plt.show()
观察上图。非正则化模型显然对训练集过拟合了。它把噪音点也拟合了进去。
现在我们来看看2种减少过拟合的技术。
2.L2正则化
标准的避免过拟合的方法是L2正则化。它包括适当修改你的成本函数,从
J
=
−
1
m
∑
i
=
1
m
(
y
(
i
)
log
(
a
[
L
]
(
i
)
)
+
(
1
−
y
(
i
)
)
log
(
1
−
a
[
L
]
(
i
)
)
)
(1)
J = -\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} \tag{1}
J=−m1i=1∑m(y(i)log(a[L](i))+(1−y(i))log(1−a[L](i)))(1) 到:
J
r
e
g
u
l
a
r
i
z
e
d
=
−
1
m
∑
i
=
1
m
(
y
(
i
)
log
(
a
[
L
]
(
i
)
)
+
(
1
−
y
(
i
)
)
log
(
1
−
a
[
L
]
(
i
)
)
)
⏟
cross-entropy cost
+
1
m
λ
2
∑
l
∑
k
∑
j
W
k
,
j
[
l
]
2
⏟
L2 regularization cost
(2)
J_{regularized} = \small \underbrace{-\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} }_\text{cross-entropy cost} + \underbrace{\frac{1}{m} \frac{\lambda}{2} \sum\limits_l\sum\limits_k\sum\limits_j W_{k,j}^{[l]2} }_\text{L2 regularization cost} \tag{2}
Jregularized=cross-entropy cost
−m1i=1∑m(y(i)log(a[L](i))+(1−y(i))log(1−a[L](i)))+L2 regularization cost
m12λl∑k∑j∑Wk,j[l]2(2)
让我们修改一下成本函数,然后观察一下效果。
练习: 实现compute_cost_with_regularization()计算公式2的成本。
使用np.sum(np.square(Wl))
计算
∑
k
∑
j
W
k
,
j
[
l
]
2
\sum\limits_k\sum\limits_j W_{k,j}^{[l]}2
k∑j∑Wk,j[l]2。
注意,你要利用它来计算
W
[
1
]
W^{[1]}
W[1],
W
[
2
]
W^{[2]}
W[2],
W
[
3
]
W^{[3]}
W[3],然后把3项求和后再乘
1
m
λ
2
\frac{1}{m} \frac{\lambda}{2}
m12λ。
# GRADED FUNCTION: compute_cost_with_regularization
def compute_cost_with_regularization(A3, Y, parameters, lambd):
"""
Implement the cost function with L2 regularization. See formula (2) above.
计算L2正则化成本函数
Arguments:
正向传播的输出结果,维度(输出节点数量,样本的数量)
A3 -- post-activation, output of forward propagation, of shape (output size, number of examples)
标签向量,维度(输出节点数量,样本的数量)
Y -- "true" labels vector, of shape (output size, number of examples)
parameters -- python dictionary containing parameters of the model 包含模型的参数的字典
Returns:
cost - value of the regularized loss function (formula (2)) 使用公式2计算出来的正则化损失函数的值
"""
m = Y.shape[1]
W1 = parameters["W1"]
W2 = parameters["W2"]
W3 = parameters["W3"]
cross_entropy_cost = compute_cost(A3, Y) # This gives you the cross-entropy part of the cost
### START CODE HERE ### (approx. 1 line)
L2_regularization_cost = lambd * (np.sum(np.square(W1)) + np.sum(np.square(W2)) + np.sum(np.square(W3))) / (2 * m)
### END CODER HERE ###
cost = cross_entropy_cost + L2_regularization_cost
return cost
测试一下
A3, Y_assess, parameters = compute_cost_with_regularization_test_case()
print("cost = " + str(compute_cost_with_regularization(A3, Y_assess, parameters, lambd = 0.1)))
运行结果
cost = 1.7864859451590758
显然,因为你改变了成本,所以反向传播也要变化。所有的梯度都必须根据这个新的成本值来计算。
练习: 考虑正则化,实现反向传播的必要修改。修改只涉及dW1, dW2和dW3。每一个你都需要增加正则项的梯度 ( d d W ( 1 2 λ m W 2 ) = λ m W \frac{d}{dW} ( \frac{1}{2}\frac{\lambda}{m} W^2) = \frac{\lambda}{m} W dWd(21mλW2)=mλW)。
# GRADED FUNCTION: backward_propagation_with_regularization
def backward_propagation_with_regularization(X, Y, cache, lambd):
"""
Implements the backward propagation of our baseline model to which we added an L2 regularization.
实现添加了L2正则化的模型的后向传播。
Arguments:
X -- input dataset, of shape (input size, number of examples)
Y -- "true" labels vector, of shape (output size, number of examples)
cache -- cache output from forward_propagation() 来自forward_propagation()的cache输出
lambd -- regularization hyperparameter, scalar 正则超参,实数
Returns:
一个包含了每个参数、激活值和预激活值变量的梯度的字典
gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables
"""
m = X.shape[1]
(Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache
dZ3 = A3 - Y
### START CODE HERE ### (approx. 1 line)
dW3 = 1. / m * np.dot(dZ3, A2.T) + (lambd * W3) / m
### END CODE HERE ###
db3 = 1. / m * np.sum(dZ3, axis=1, keepdims=True)
dA2 = np.dot(W3.T, dZ3)
dZ2 = np.multiply(dA2, np.int64(A2 > 0))
### START CODE HERE ### (approx. 1 line)
dW2 = 1. / m * np.dot(dZ2, A1.T) + (lambd * W2) / m
### END CODE HERE ###
db2 = 1. / m * np.sum(dZ2, axis=1, keepdims=True)
dA1 = np.dot(W2.T, dZ2)
dZ1 = np.multiply(dA1, np.int64(A1 > 0))
### START CODE HERE ### (approx. 1 line)
dW1 = 1. / m * np.dot(dZ1, X.T) + (lambd * W1) / m
### END CODE HERE ###
db1 = 1. / 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
测试一下
X_assess, Y_assess, cache = backward_propagation_with_regularization_test_case()
grads = backward_propagation_with_regularization(X_assess, Y_assess, cache, lambd=0.7)
print ("dW1 = " + str(grads["dW1"]))
print ("dW2 = " + str(grads["dW2"]))
print ("dW3 = " + str(grads["dW3"]))
运行结果
dW1 = [[-0.25604646 0.12298827 -0.28297129]
[-0.17706303 0.34536094 -0.4410571 ]]
dW2 = [[ 0.79276486 0.85133918]
[-0.0957219 -0.01720463]
[-0.13100772 -0.03750433]]
dW3 = [[-1.77691347 -0.11832879 -0.09397446]]
现在让我们运行带L2正则的模型 ( λ = 0.7 ) (\lambda = 0.7) (λ=0.7)。模型 model()
- 使用compute_cost_with_regularization替代compute_cost
- 使用backward_propagation_with_regularization替代backward_propagation
运行代码
parameters = model(train_X, train_Y, lambd=0.7)
print("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print("On the test set:")
predictions_test = predict(test_X, test_Y, parameters)
结果
Cost after iteration 0: 0.6974484493131264
Cost after iteration 10000: 0.2684918873282239
Cost after iteration 20000: 0.2680916337127301
On the train set:
Accuracy: 0.9383886255924171
On the test set:
Accuracy: 0.93
成本曲线
恭喜你,测试准确率达到了93%,你拯救了法国队。
训练集不再过拟合。看一下决策边界。
plt.title("Model with L2-regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
plt.show()
结果如下
观察上图
- 超参 λ \lambda λ的值,你可以用开发集优化
- L2正则化让你的决策边界更加平滑。如果 λ \lambda λ 太大,也可能会“过度平滑”,从而导致模型高偏差。
L2正则化到底做了什么?
可以参见链接。
L2正则化依赖于这样一个假设,即具有小权重的模型比大权重的模型更简单(更加接近线性模型)。
因此,通过惩罚/消减成本函数中权重的平方值,可以将所有权重变为更小的值。本成越大权重值越不会大。小权重值会让模型更加平滑,其中输入变化时输出变化更慢,但是你需要花费更多的时间。
- 成本计算:成本中增加了正则化项
- 反向传播计算:在权重矩阵方面,梯度计算时也要增加额外项
- 权重变小(权重衰减):权重被逐渐改变到较小的值。
3.Dropout
Dropout是在DL中广泛使用的正则化技术。它在每次迭代中随机删除一些神经元。
观察下面2图,你就会明白是什么意思。
如上图,NN的第二层启用dropout。
在每一次迭代中,删除(设置为零)这一层的神经元,删除概率为
1
−
k
e
e
p
_
p
r
o
b
1 - keep\_prob
1−keep_prob,保持概率为
k
e
e
p
_
p
r
o
b
keep\_prob
keep_prob(这里为50%)。删除的节点不参与迭代时的前向和后向传播。
如上图,在NN的第一层和第三层启用dropout。
第一层平均删除了40%的神经元, 第三层平均删除了20%的神经元。
当你删除了一些神经元,实际上你修改了你的模型。Dropout算法的实质就是,每次迭代时候训练不同模型,这个模型是你所有神经元集合的子集。使用dropout,你的神经元对另一个特定神经元的激活(输出)变得不那么敏感,因为另一个神经元随时可能被关闭。
3.1Dropout的前向传播
练习: 实现dropout的前向传播。你将使用一个3层NN,第一和第二隐层使用dropout。输入层和输出层不使用dropout。
提示: 你将删除第一和第二隐层的一些神经元。为了实现它,你需要执行以下4步
- 在课程中,我们学习了使用
np.random.rand()
来初始化和 a [ 1 ] a^{[1]} a[1]具有相同维度的 d [ 1 ] d^{[1]} d[1]。在这里,我们将使用向量化实现,我们先来实现一个和 A [ 1 ] A^{[1]} A[1]相同的随机矩阵 D [ 1 ] = [ d [ 1 ] ( 1 ) d [ 1 ] ( 2 ) … d [ 1 ] ( m ) ] D^{[1]} = [d^{[1](1)} d^{[1](2)} … d^{[1](m)}] D[1]=[d[1](1)d[1](2)…d[1](m)]。 - 如果
D
[
1
]
D^{[1]}
D[1]低于 (keep_prob)的值我们就把它设置为0,如果高于(keep_prob)的值我们就设置为1。提示:对于矩阵X的所有输入,如果小于0.5设置为0,大于0.5设置为1,
X = (X < 0.5)
,注意:0和1等价于False和True。 - 把 A [ 1 ] A^{[1]} A[1]更新为 A [ 1 ] A^{[1]} A[1]∗ D [ 1 ] D^{[1]} D[1]。 (我们已经关闭了一些节点)。我们可以把 D [ 1 ] D^{[1]} D[1]看作掩码,做矩阵相乘的时候,关闭的那些神经元(值为0)就会不参与计算,因为0乘以任何值都为0。
- 把 A [ 1 ] A^{[1]} A[1]除以 keep_prob。这样做的话(通过缩放)可以确保计算成本的时候仍然具有相同的期望值。(这技术叫做反向dropout)
实现代码
# GRADED FUNCTION: forward_propagation_with_dropout
def forward_propagation_with_dropout(X, parameters, keep_prob=0.5):
"""
Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
实现dropout的前向传播
Arguments:
X -- input dataset, of shape (2, number of examples) 输入数据集,维度(2,样本数)
parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":
W1 -- weight matrix of shape (20, 2) 权重矩阵,维度为(20,2)
b1 -- bias vector of shape (20, 1) 偏置向量,维度为(20,1)
W2 -- weight matrix of shape (3, 20)
b2 -- bias vector of shape (3, 1)
W3 -- weight matrix of shape (1, 3)
b3 -- bias vector of shape (1, 1)
keep_prob - probability of keeping a neuron active during drop-out, scalar dropout的概率,实数
Returns:
最后的激活值,维度为(1,1),正向传播的输出
A3 -- last activation value, output of the forward propagation, of shape (1,1)
存储了一些用于计算反向传播的数值的元组
cache -- tuple, information stored for computing the backward propagation
"""
np.random.seed(1)
# retrieve parameters
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)
#步骤1-4。
### START CODE HERE ### (approx. 4 lines) # Steps 1-4 below correspond to the Steps 1-4 described above.
#步骤1:初始化矩阵D1 = np.random.rand(..., ...)
D1 = np.random.rand(A1.shape[0], A1.shape[1]) # Step 1: initialize matrix D1 = np.random.rand(..., ...)
#步骤2:将D1的值转换为0或1(使用keep_prob作为阈值)
D1 = D1 < keep_prob # Step 2: convert entries of D1 to 0 or 1 (using keep_prob as the threshold)
#步骤3:舍弃A1的一些节点(将它的值变为0或False)
A1 = A1 * D1 # Step 3: shut down some neurons of A1
#步骤4:缩放未舍弃的节点(不为0)的值
A1 = A1 / keep_prob # Step 4: scale the value of neurons that haven't been shut down
### END CODE HERE ###
Z2 = np.dot(W2, A1) + b2
A2 = relu(Z2)
#步骤1-4。
### START CODE HERE ### (approx. 4 lines)
D2 = np.random.rand(A2.shape[0], A2.shape[1]) # Step 1: initialize matrix D2 = np.random.rand(..., ...)
D2 = D2 < keep_prob # Step 2: convert entries of D2 to 0 or 1 (using keep_prob as the threshold)
A2 = A2 * D2 # Step 3: shut down some neurons of A2
A2 = A2 / keep_prob # Step 4: scale the value of neurons that haven't been shut down
### END CODE HERE ###
Z3 = np.dot(W3, A2) + b3
A3 = sigmoid(Z3)
cache = (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3)
return A3, cache
测试一下
X_assess, parameters = forward_propagation_with_dropout_test_case()
A3, cache = forward_propagation_with_dropout(X_assess, parameters, keep_prob=0.7)
print ("A3 = " + str(A3))
运行结果
A3 = [[0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]]
3.2Dropout的反向传播
练习: 实现dropout的反向传播。前面你已经训练了一个3层NN。使用存储在cache中的掩码 D [ 1 ] D^{[1]} D[1]和 D [ 2 ] D^{[2]} D[2]将删除的节点位置信息添加到第一个和第二隐层。
提示: 使用dropout的反向传播其实很简单。你需要执行以下2步
- 你已经在前向传播时候通过在 A [ 1 ] A^{[1]} A[1]上应用掩码 D [ 1 ] D^{[1]} D[1]删除了一些神经元。反向传播时,你同样需要在dA1上应用掩码 D [ 1 ] D^{[1]} D[1]来删除相同的神经元。
- 前向传播时,你用A1除以keep_prob。因此,反向传播时候,你用dA1除以keep_prob。(微积分解释:如果 A [ 1 ] A^{[1]} A[1]由keep_prob缩放,那么它的导数dA1也应该由keep_prob缩放)
实现代码
# GRADED FUNCTION: backward_propagation_with_dropout
def backward_propagation_with_dropout(X, Y, cache, keep_prob):
"""
Implements the backward propagation of our baseline model to which we added dropout.
实现dropout模型的后向传播。
Arguments:
X -- input dataset, of shape (2, number of examples)
Y -- "true" labels vector, of shape (output size, number of examples)
cache -- cache output from forward_propagation_with_dropout()
keep_prob - probability of keeping a neuron active during drop-out, scalar
Returns:
关于每个参数、激活值和预激活变量的梯度值的字典
gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables
"""
m = X.shape[1]
(Z1, D1, A1, W1, b1, Z2, D2, 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)
### START CODE HERE ### (≈ 2 lines of code)
dA2 = dA2 * D2 # Step 1: Apply mask D2 to shut down the same neurons as during the forward propagation
dA2 = dA2 / keep_prob # Step 2: Scale the value of neurons that haven't been shut down
### END CODE HERE ###
dZ2 = np.multiply(dA2, np.int64(A2 > 0))
dW2 = 1. / m * np.dot(dZ2, A1.T)
db2 = 1. / m * np.sum(dZ2, axis=1, keepdims=True)
dA1 = np.dot(W2.T, dZ2)
### START CODE HERE ### (≈ 2 lines of code)
#步骤1
dA1 = dA1 * D1 # Step 1: Apply mask D1 to shut down the same neurons as during the forward propagation
#步骤2
dA1 = dA1 / keep_prob # Step 2: Scale the value of neurons that haven't been shut down
### END CODE HERE ###
dZ1 = np.multiply(dA1, np.int64(A1 > 0))
dW1 = 1. / m * np.dot(dZ1, X.T)
db1 = 1. / 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
测试一下
X_assess, Y_assess, cache = backward_propagation_with_dropout_test_case()
gradients = backward_propagation_with_dropout(X_assess, Y_assess, cache, keep_prob=0.8)
print ("dA1 = " + str(gradients["dA1"]))
print ("dA2 = " + str(gradients["dA2"]))
运行结果
dA1 = [[ 0.36544439 0. -0.00188233 0. -0.17408748]
[ 0.65515713 0. -0.00337459 0. -0. ]]
dA2 = [[ 0.58180856 0. -0.00299679 0. -0.27715731]
[ 0. 0.53159854 -0. 0.53159854 -0.34089673]
[ 0. 0. -0.00292733 0. -0. ]]
现在让我们运行一下使用dropout的模型(keep_prob = 0.86)。也就是说每次迭代都会以14%的概率删除第一和第二隐层的神经元。函数model() 会调用
- 用forward_propagation_with_dropout替代forward_propagation
- 用backward_propagation_with_dropout替代backward_propagation
运行代码
parameters = model(train_X, train_Y, keep_prob=0.86, learning_rate=0.3)
print("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print("On the test set:")
predictions_test = predict(test_X, test_Y, parameters)
结果如下
Cost after iteration 0: 0.6543912405149825
Cost after iteration 10000: 0.0610169865749056
Cost after iteration 20000: 0.060582435798513114
On the train set:
Accuracy: 0.9289099526066351
On the test set:
Accuracy: 0.95
成本曲线
dropout正则化工作的很好。测试集正确率提高到 95%。你的模型在训练集上不再过拟合。法国队会永远感谢你的。
再看一下dropout模型的决策边界。
plt.title("Model with dropout")
axes = plt.gca()
axes.set_xlim([-0.75, 0.40])
axes.set_ylim([-0.75, 0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
plt.show()
注意:
- 有一个经常会犯的错误,在训练集和测试集上都使用dropout。你应该只在训练集上使用dropout。
- DL框架tensorflow, PaddlePaddle, keras或者caffe都有dropout的实现。
- dropout是一种正则化技术。
- 应该在正向传播和反向传播都应用dropout。
4.结论
以下是3个模型的运行结果。
注意:正则化会减低训练集性能。这是因为它限制了网络的能力防止在训练集上过拟合。不过最终它提供了更好的测试准确度,所以它对你的系统是有帮助的。
- 正则化可以帮助你减少过拟合
- 正则化使你的权重更加小
- L2和dropout是2种很有效的正则化技术。