1. 程式人生 > >改善深層神經網路第一週-Regularization(正則化)

改善深層神經網路第一週-Regularization(正則化)

Regularization

Welcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that overfitting can be a serious problem, if the training dataset is not big enough. Sure it does well on the training set, but the learned network doesn’t generalize to new examples

 that it has never seen!

You will learn to: Use regularization in your deep learning models.

Let’s first import the packages you are going to use.

# 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 * plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'
] = 'nearest' plt.rcParams['image.cmap'] = 'gray'

Problem Statement: You have just been hired as an AI expert by the French Football Corporation. They would like you to recommend positions where France’s goal keeper should kick the ball so that the French team’s players can then hit it with their head. (你剛剛被法國足球公司聘為AI專家。他們希望你推薦法國守門員應該踢球的位置,這樣法國隊的球員可以用頭打)


Figure 1 Football field
The goal keeper kicks the ball in the air, the players of each team are fighting to hit the ball with their head

They give you the following 2D dataset from France’s past 10 games.

會出現維度不匹配的錯誤,即c of shape (1, 211) not acceptable as a color sequence for x with size 211, y with size 211,好像這個問題在做題過程中一直在出現。這本題中解決方法為:找到load_2D_dataset()這個函式的py檔案,也就reg_utils.py,在這個函式裡面把 plt.scatter(train_X[0, :], train_X[1, :], c=c=train_Y, s=40, cmap=plt.cm.Spectral);中的c=train_Y替換為c=np.squeeze(train_Y)就可以了,也就是刪除單維條目。

train_X, train_Y, test_X, test_Y = load_2D_dataset()
plt.show()

Each dot corresponds to a position on the football field where a football player has hit the ball with his/her head after the French goal keeper has shot the ball from the left side of the football field.(每個點對應於足球運動員在足球場左側擊球之後,用頭將球擊中的足球場上的位置
- If the dot is blue, it means the French player managed to hit the ball with his/her head(如果這個點是藍色的,這意味著這個法國球員設法用他/她的頭擊球
- If the dot is red, it means the other team’s player hit the ball with their head(如果這個點是紅色的,這意味著另一個隊的球員用頭撞球)

Your goal: Use a deep learning model to find the positions on the field where the goalkeeper should kick the ball.(* 
使用深度學習模式來找到守門員應該踢球的場地位置*)

Analysis of the dataset: This dataset is a little noisy, but it looks like a diagonal line separating the upper left half (blue) from the lower right half (red) would work well. (這個資料集有點嘈雜,但是看起來像是左上角(藍色)和右下角(紅色)分開的對角線,效果很好)

You will first try a non-regularized model. Then you’ll learn how to regularize it and decide which model you will choose to solve the French Football Corporation’s problem.(你將首先嚐試一個非正規化的模型。然後,您將學習如何正規化,並決定選擇哪種模式來解決法國足球公司的問題)

1 - Non-regularized model

You will use the following neural network (already implemented for you below). This model can be used: 
- in regularization mode – by setting the lambd input to a non-zero value. We use “lambd” instead of “lambda” because “lambda” is a reserved keyword in Python. (在正則化模式中 - 通過將lambd輸入設定為一個非零值。我們使用”lambd“代替”lambda“,因為”lambda“是Python中的保留關鍵字) 
- in dropout mode – by setting the keep_prob to a value less than one(在* dropout模式下* - 通過將keep_prob設定為小於1的值)

You will first try the model without any regularization. Then, you will implement: 
L2 regularization – functions: “compute_cost_with_regularization()” and “backward_propagation_with_regularization()” 
Dropout – functions: “forward_propagation_with_dropout()” and “backward_propagation_with_dropout()

In each part, you will run this model with the correct inputs so that it calls the functions you’ve implemented. Take a look at the code below to familiarize yourself with the model.

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)
    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:
            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:
            cost = compute_cost(a3, Y)
        else:
            cost = compute_cost_with_regularization(a3, Y, parameters, lambd)

        # Backward propagation.
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:
            grads = backward_propagation(X, Y, cache)
        elif lambd != 0:
            grads = backward_propagation_with_regularization(X, Y, cache, lambd)
        elif keep_prob < 1:
            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

Let’s train the model without any regularization, and observe the accuracy on the train/test sets.

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
The train accuracy is 94.8% while the test accuracy is 91.5%. This is the **baseline model( 

基準模型)** (you will observe the impact of regularization on this model). Run the following code to plot the decision boundary of your model.


The non-regularized model is obviously overfitting the training set. It is fitting the noisy points! Lets now look at two techniques to reduce overfitting.(非正則化模型顯然是過度訓練集合。這是適合的嘈雜點!現在讓我們看看兩種技術來減少過度擬合)

2 - L2 Regularization

The standard way to avoid overfitting is called L2 regularization. It consists of appropriately modifying your cost function, from: 

np.sum(np.square(Wl))
Note that you have to do this for W[1]W[2] and W[3], then sum the three terms and multiply by 1mλ2

.

def compute_cost_with_regularization(A3, Y, parameters, lambd):
    """
    Implement the cost function with L2 regularization. See formula (2) above.
    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))
    """
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 =(1./m)*(lambd/2)*(np.sum(np.square(W1)) + np.sum(np.square(W2)) + np.sum(np.square(W3)))
    ### 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

Of course, because you changed the cost, you have to change backward propagation as well! All the gradients have to be computed with respect to this new cost.


def backward_propagation_with_regularization(X, Y, cache, lambd):
    """
    Implements the backward propagation of our baseline model to which we added an L2 regularization.
    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()
    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/m)*W3
    ### 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/m)*W2
    ### 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/m)*W1
    ### 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
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]]

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.26849188732822393
Cost after iteration 20000: 0.2680916337127301
On the train set:
Accuracy: 0.9383886255924171
On the test set:
Accuracy: 0.93

Congrats, the test set accuracy increased to 93%. You have saved the French football team!

You are not overfitting the training data anymore. Let’s plot the decision boundary.

Observations
- The value of λ is a hyperparameter that you can tune using a dev set.(λ的值是一個超引數,您可以使用開發集進行調優
- L2 regularization makes your decision boundary smoother. If λ is too large, it is also possible to “oversmooth”, resulting in a model with high bias.(L2正則化使得你的決策邊界更加平滑。如果λ太大,也有可能“過度平滑”,從而導致高偏差的模型)

What is L2-regularization actually doing?:

L2-regularization relies on the assumption that a model with small weights is simpler than a model with large weights. Thus, by penalizing the square values of the weights in the cost function you drive all the weights to smaller values. It becomes too costly for the cost to have large weights! This leads to a smoother model in which the output changes more slowly as th