1. 程式人生 > >網易雲深度學習第一課第三週程式設計作業

網易雲深度學習第一課第三週程式設計作業

具有一個隱藏層的平面資料分類
第三週的程式設計任務:
構建一個含有一層隱藏層的神經網路,你將會發現這和使用邏輯迴歸有很大的不同。
首先先匯入在這個任務中你需要的所有的包。
-numpy是Python中與科學計算相關的基礎包
-sklearn提供簡單高效的資料探勘和資料分析
-matplotlib是Python中的繪製圖形庫
-testCase提供了一些測試的例子來評估你的函式的正確性
-planar_utils提供在這個任務中有用的函式

//from module import *把module中的成員全部導到了當前的global namespace,訪問起來就比較方便了。
//seed( ) 用於指定隨機數生成時所用演算法開始的整數值,如果使用相同的seed( )值,則每次生成的隨即數都相同,如果不設定這個值,則系統根據時間來自己選擇這個值,此時每次生成的隨機數因時間差異而不同。

1-Packages

#Package imports
import numpy as np
import matplotlib.pyplot as plt
from testCases import *
import sklearn
import sklearn.datasets
import sklearn.linear_modelfrom 
from planar_utils.py import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
np.random.seed(1) # 設定一個統一的隨機數

2-Dataset

首先,讓我們得到你將用到的資料集,下面的程式碼會載入一個2-calss的資料集“花”到變數X、Y

def load_planar_dataset():
    np.random.seed(1)
    m=400 #樣本總量
    N=int(m/2) #每個類別的樣本量
    D=2      #維度數
    X=np.zeros((m,D)) #初始化X
    Y=np.zeros((m,1),dtype='uint8') #初始化Y
    a=4   #花兒最大長度

    for j in range(2):
        ix=range(N*j,N*(j+1
)) t = np.linspace(j*3.12,(j+1)*3.12,N) +np.random.randn(N)*0.2 #角度 r = a*np.sin(4*t) + np.random.randn(N)*0.2 #半徑 X[ix] = np.c_[r*np.sin(t), r*np.cos(t)] Y[ix] = j X = X.T Y = Y.T return X, Y X, Y = load_planar_dataset() # Visualize the data: plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);

這裡寫圖片描述
X包含你的特徵(x1,x2)
Y包含你的標籤(red:0,blue:1)

Exercise: How many training examples do you have? In addition, what is the shape of the variables X and Y?

### START CODE HERE ### (≈ 3 lines of code)
shape_X = X.shape
shape_Y = Y.shape
m = X.shape[1]  # training set size
### END CODE HERE ###

print ('The shape of X is: ' + str(shape_X))
print ('The shape of Y is: ' + str(shape_Y))
print ('I have m = %d training examples!' % (m))

The shape of X is: (2, 400)
The shape of Y is: (1, 400)
I have m = 400 training examples!

3 - Simple Logistic Regression

在建立一個完整的神經網路之前,首先看看邏輯迴歸是如何解決這個問題的,你可以使用sklearn的內建函式做這件事情。執行以下程式碼執行資料集的分類。

運用sklearn中的提供logistic迴歸模型,對花朵樣本進行分類

# Train the logistic regression classifier
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, Y.T);`

You can now plot the decision boundary of these models. Run the code below.

# Plot the decision boundary for logistic regression
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")

# Print accuracy
LR_predictions = clf.predict(X.T)
print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
       '% ' + "(percentage of correctly labelled datapoints)")

這裡寫圖片描述

解釋:資料集不是線性可分的,所以邏輯迴歸表現不好。
神經網路可能能做的更好,我們來嘗試下!

4 - Neural Network model

邏輯迴歸對“花”資料集不能很好的分類。你現在將訓練一個單層隱藏層的神經網路。
模型:
這裡寫圖片描述
數學推導:
這裡寫圖片描述
損失函式:
這裡寫圖片描述

提示:建立一個神經網路的通用方法是:
1.定義神經網路的結構(輸入單元、隱藏單元等)
2.初始化模型引數
3.迴圈:
-執行前向傳播
-計算loss
-執行反向傳播得到梯度
-更新引數(梯度下降)
你通常構建輔助函式執行步驟1-3,然後合併他們進入一個函式,我們通常稱為nn_model()。一旦你構建了nn_model就可以開始學習引數得到模型了。通過模型,你就可以預測新的資料。

4.1 - Defining the neural network structure

練習:定義三個變數
-n_x:輸入層的size
-n_h:隱藏層的size
-n_y:輸出層的size

Hint: Use shapes of X and Y to find n_x and n_y. Also, hard code the hidden layer size to be 4.

#隱藏層
def layer_sizes(X,Y):
    n_x=X.shape[0]
    n_h=4
    n_y=Y.shape[0]

    return (n_x,n_h,n_y)


X_assess, Y_assess = layer_sizes_test_case()
# layer_sizes_test_case()來自於testCases
(n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess)
print("The size of the input layer is: n_x = " + str(n_x))
print("The size of the hidden layer is: n_h = " + str(n_h))
print("The size of the output layer is: n_y = " + str(n_y))

結果:

The size of the input layer is: n_x = 5
The size of the hidden layer is: n_h = 4
The size of the output layer is: n_y = 2

4.2 - Initialize the model’s parameters

Exercise: Implement the function initialize_parameters().
說明:
-確信你的引數的size是對的,
-你將通過隨機數初始化權重矩陣
-使用np.random.randn(a,b)*0.01隨機初始化一個形狀為(a,b)的矩陣
-初始化你的bias向量為zeros
-np.zeros((a,b))去初始化形狀為(a,b)的矩陣

#初始化函式
def initialize_parameters(n_x, n_h, n_y):
    """
    Argument:
    n_x -- 輸入層的神經元個數
    n_h -- 隱藏層的神經元個數
    n_y -- 輸出層的神經元個數
    Returns:
    params -- python dictionary containing your parameters:
                    W1 -- weight matrix of shape (n_h, n_x)
                    b1 -- bias vector of shape (n_h, 1)
                    W2 -- weight matrix of shape (n_y, n_h)
                    b2 -- bias vector of shape (n_y, 1)
    """

    np.random.seed(2) # we set up a seed so that your output matches ours although the initialization is random.

    ### START CODE HERE ### (≈ 4 lines of code)
    W1 = np.random.randn(n_h, n_x)
    b1 = np.zeros((n_h, 1))
    W2 = np.random.randn(n_y, n_h)
    b2 = np.zeros((n_y, 1))
    ### END CODE HERE ###

    assert (W1.shape == (n_h, n_x))
    assert (b1.shape == (n_h, 1))
    assert (W2.shape == (n_y, n_h))
    assert (b2.shape == (n_y, 1))

    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}

    return parameters
# initialize_parameters_test_case()儲存在testCases中
#內部為
#def initialize_parameters_test_case():
   # n_x, n_h, n_y = 2, 4, 1
   # return n_x, n_h, n_y
n_x, n_h, n_y = initialize_parameters_test_case()
parameters = initialize_parameters(n_x, n_h, n_y)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

4.3 - The Loop

Question: Implement forward_propagation().
說明:
-檢視前面分類器的數學推導
-你能使用sigmoid函式,它是內建函式
-你能使用np.tanh()函式,它在numpy庫中
-你需要執行以下步驟
1.從“parameters”中取得每一個引數
2.執行前向傳播,計算Z1、A1、Z2、A2
3.反向傳播所需要的值儲存在“快取”,快取將作為反向傳播的輸入

#前向傳播函式
def forward_propagation(X, parameters):
    """
    Argument:
    X -- input data of size (n_x, m)
    parameters -- python dictionary containing your parameters (output of initialization function)

    Returns:
    A2 -- The sigmoid output of the second activation
    cache -- a dictionary containing "Z1", "A1", "Z2" and "A2"
    """
    # Retrieve each parameter from the dictionary "parameters"
    ### START CODE HERE ### (≈ 4 lines of code)
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    ### END CODE HERE ###

    # Implement Forward Propagation to calculate A2 (probabilities)
    ### START CODE HERE ### (≈ 4 lines of code)
    Z1 = np.dot(W1, X) + b1
    A1 = np.tanh(Z1)
    Z2 = np.dot(W2, A1) + b2 
    A2 = sigmoid(Z2)
    ### END CODE HERE ###

    cache = {"Z1": Z1,
             "A1": A1,
             "Z2": Z2,
             "A2": A2}

    return A2, cache

X_assess, parameters = forward_propagation_test_case()
A2, cache = forward_propagation(X_assess, parameters)
print("Z1:"+str(cache["Z1"]))
print("A1:"+str(cache["A1"]))
print("Z2:"+str(cache["Z2"]))
print("A2:"+str(cache["A2"]))

Exercise: Implement compute_cost() to compute the value of the cost J.
這裡寫圖片描述
這裡寫圖片描述

#計算交叉熵 損失函式coss
def compute_cost(A2, Y, parameters):
    """
    Computes the cross-entropy cost given in equation (13)

    Arguments:
    A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
    Y -- "true" labels vector of shape (1, number of examples)
    parameters -- python dictionary containing your parameters W1, b1, W2 and b2

    Returns:
    cost -- cross-entropy cost given equation (13)
    """

    m = Y.shape[1] # number of example

    # Compute the cross-entropy cost
    ### START CODE HERE ### (≈ 2 lines of code)
    logprobs = np.multiply(np.log(A2), Y) + (1-Y)*np.multiply(np.log(1-A2), (1-Y))
    cost = -(1.0/m)*np.sum(logprobs)
    ### END CODE HERE ###

    cost = np.squeeze(cost)     # makes sure cost is the dimension we expect. 
                                # E.g., turns [[17]] into 17 
    assert(isinstance(cost, float))

    return cost

A2, Y_assess, parameters = compute_cost_test_case()

print("cost = " + str(compute_cost(A2, Y_assess, parameters)))

Question: Implement the function backward_propagation().

說明:
反向傳播(數學推導)通常是dl中最困難的一部分,為了幫助你這裡有需要使用的六個方程。你需要建立這六個方程的向量形式。
這裡寫圖片描述

#反向傳播
def backward_propagation(parameters, cache, X, Y):
    """
    Implement the backward propagation using the instructions above.

    Arguments:
    parameters -- python dictionary containing our parameters 
    cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
    X -- input data of shape (2, number of examples)
    Y -- "true" labels vector of shape (1, number of examples)

    Returns:
    grads -- python dictionary containing your gradients with respect to different parameters
    """
    m = X.shape[1]

    # First, retrieve W1 and W2 from the dictionary "parameters".
    ### START CODE HERE ### (≈ 2 lines of code)
    W1 = parameters["W1"]
    W2 = parameters["W2"]
    ### END CODE HERE ###

    # Retrieve also A1 and A2 from dictionary "cache".
    ### START CODE HERE ### (≈ 2 lines of code)
    A1 = cache["A1"]
    A2 = cache["A2"]
    ### END CODE HERE ###

    # Backward propagation: calculate dW1, db1, dW2, db2. 
    ### START CODE HERE ### (≈ 6 lines of code, corresponding to 6 equations on slide above)
    dZ2 = A2 - Y
    dW2 = 1.0/m*np.dot(dZ2, A1.T)
    db2 = 1.0/m*np.sum(dZ2, axis=1, keepdims=True)
    dZ1 = np.dot(W2.T, dZ2)*(1-np.power(A1, 2))
    dW1 = 1.0/m*np.dot(dZ1, X.T)
    db1 = 1.0/m*np.sum(dZ1, axis=1, keepdims=True)
    ### END CODE HERE ###

    grads = {"dW1": dW1,
             "db1": db1,
             "dW2": dW2,
             "db2": db2}

    return grads
parameters, cache, X_assess, Y_assess = backward_propagation_test_case()

grads = backward_propagation(parameters, cache, X_assess, Y_assess)
print ("dW1 = "+ str(grads["dW1"]))
print ("db1 = "+ str(grads["db1"]))
print ("dW2 = "+ str(grads["dW2"]))
print ("db2 = "+ str(grads["db2"]))

Question: Implement the update rule. Use gradient descent. You have to use (dW1, db1, dW2, db2) in order to update (W1, b1, W2, b2).
這裡寫圖片描述

#更新引數
def update_parameters(parameters, grads, learning_rate = 1.2):
    """
    Updates parameters using the gradient descent update rule given above

    Arguments:
    parameters -- python dictionary containing your parameters 
    grads -- python dictionary containing your gradients 

    Returns:
    parameters -- python dictionary containing your updated parameters 
    """
    # Retrieve each parameter from the dictionary "parameters"
    ### START CODE HERE ### (≈ 4 lines of code)
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    ### END CODE HERE ###

    # Retrieve each gradient from the dictionary "grads"
    ### START CODE HERE ### (≈ 4 lines of code)
    dW1 = grads["dW1"]
    db1 = grads["db1"]
    dW2 = grads["dW2"]
    db2 = grads["db2"]
    ## END CODE HERE ###

    # Update rule for each parameter
    ### START CODE HERE ### (≈ 4 lines of code)
    W1 = W1 - learning_rate*dW1
    b1 = b1 - learning_rate*db1
    W2 = W2 - learning_rate*dW2
    b2 = b2 - learning_rate*db2
    ### END CODE HERE ###

    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}

    return parameters
parameters, grads = update_parameters_test_case()
parameters = update_parameters(parameters, grads)

print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

4.4 - Integrate parts 4.1, 4.2 and 4.3 in nn_model()

Question: Build your neural network model in nn_model().
說明:各個函式以正確的順序整合到神經網路模型中

#整合模型
def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):
    """
    Arguments:
    X -- dataset of shape (2, number of examples)
    Y -- labels of shape (1, number of examples)
    n_h -- size of the hidden layer
    num_iterations -- Number of iterations in gradient descent loop
    print_cost -- if True, print the cost every 1000 iterations

    Returns:
    parameters -- parameters learnt by the model. They can then be used to predict.
    """

    np.random.seed(3)
    n_x = layer_sizes(X, Y)[0]
    n_y = layer_sizes(X, Y)[2]

    # Initialize parameters, then retrieve W1, b1, W2, b2. Inputs: "n_x, n_h, n_y". Outputs = "W1, b1, W2, b2, parameters".
    ### START CODE HERE ### (≈ 5 lines of code)
    parameters = initialize_parameters(n_x, n_h, n_y)
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    ### END CODE HERE ###

    # Loop (gradient descent)

    for i in range(0, num_iterations):

        ### START CODE HERE ### (≈ 4 lines of code)
        # Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache".
        A2, cache = forward_propagation(X, parameters)

        # Cost function. Inputs: "A2, Y, parameters". Outputs: "cost".
        cost = compute_cost(A2, Y, parameters)

        # Backpropagation. Inputs: "parameters, cache, X, Y". Outputs: "grads".
        grads = backward_propagation(parameters, cache, X, Y)

        # Gradient descent parameter update. Inputs: "parameters, grads". Outputs: "parameters".
        parameters = update_parameters(parameters, grads, learning_rate = 1.2)

        ### END CODE HERE ###

        # Print the cost every 1000 iterations
        if print_cost and i % 1000 == 0:
            print ("Cost after iteration %i: %f" %(i, cost))

    return parameters
X_assess, Y_assess = nn_model_test_case()
parameters = nn_model(X_assess, Y_assess, 4, num_iterations=10000, print_cost=True)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

4.5 Predictions

Question: Use your model to predict by building predict().
Use forward propagation to predict results.

這裡寫圖片描述

def predict(parameters, X):
    """
    Using the learned parameters, predicts a class for each example in X

    Arguments:
    parameters -- python dictionary containing your parameters 
    X -- input data of size (n_x, m)

    Returns
    predictions -- vector of predictions of our model (red: 0 / blue: 1)
    """

    # Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold.
    ### START CODE HERE ### (≈ 2 lines of code)
    A2, cache = forward_propagation(X, parameters)
    predictions = (A2 > 0.5)
    ### END CODE HERE ###

    return predictions
parameters, X_assess = predict_test_case()

predictions = predict(parameters, X_assess)
print("predictions mean = " + str(np.mean(predictions)))

是時候執行模型,看她是如何在一個平面的資料集上執行的。執行以下程式碼來測試你那擁有一個隱藏層每層隱藏層有nh個神經元的模型。

# Build a model with a n_h-dimensional hidden layer
parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)

# Plot the decision boundary
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
plt.title("Decision Boundary for hidden layer size " + str(4))

這裡寫圖片描述

神經網路模型相比於邏輯迴歸模型,其精度更高。通過對花資料集的測試,我們可以得知,神經網路能夠學習高度非線性的決策邊界,而邏輯迴歸不行。

現在我們可以嘗試改變隱藏層的size

4.6 - Tuning hidden layer size (optional/ungraded exercise)

Run the following code. It may take 1-2 minutes. You will observe different behaviors of the model for various hidden layer sizes.

# This may take about 2 minutes to run

plt.figure(figsize=(16, 32))
hidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50]
for i, n_h in enumerate(hidden_layer_sizes):
    plt.subplot(5, 2, i+1)
    plt.title('Hidden Layer of size %d' % n_h)
    parameters = nn_model(X, Y, n_h, num_iterations = 5000)
    plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
    predictions = predict(parameters, X)
    accuracy = float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100)
    print ("神經元個數為 {} 時分類準確度為: {} %".format(n_h, accuracy))

這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述

解釋:
-較大的模型(擁有更多的神經元)更適合這個訓練集,最終,最大的模型會對資料過擬合。
-最好的隱藏層神經元個數似乎在n_h=5左右,事實上, a value around here seems to fits the data well without also incurring noticable overfitting.
-稍後你將學習正則化,它將使你用非常大的模型(n_h=50)也不會引起過擬合。

你已經學會了:
-建立一個完整的神經網路隱藏層
-使用一個非線性單元
-實現前向傳播和反向傳播,並訓練一個神經網路
-瞭解隱藏層size的影響,例如過擬合。