2020-6-13 吳恩達-NN&DL-w3 淺層NN(課後編程-Planar data classification with one hidden layer)

原文鏈接
如果打不開,也可以複製鏈接到https://nbviewer.jupyter.org中打開。

本次練習將構建一個單隱層NN。你會發現這個模型和ML的邏輯迴歸模型有很大的區別。

單隱層NN是非線性的。而ML的邏輯迴歸模型是線性的。

你將會學習

  • 構建一個單隱層2分分類NN
  • 使用具有非線性激活函數神經元,例如tanh函數
  • 計算交叉熵損失(損失函數)
  • 實現前向傳播和反向傳播

1.本文涉及的基本庫

本作業涉及以下幾個python庫

  • numpy :是用Python進行科學計算的基本軟件包。
  • sklean :是數據挖掘和數據分析簡單有效的工具。
  • matplotlib:是一個著名的庫,用於在Python中繪製圖表。
  • testCases.py:提供了一些測試樣本來評估你的函數的正確性。
  • planar_utils.py:提供了在本作業中會使用的各種有用的函數。
import numpy as np
import matplotlib.pyplot as plt
from testCases import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets

#%matplotlib inline #如果你使用用的是Jupyter Notebook的話請取消註釋。

np.random.seed(1) # set a seed so that the results are consistent設置一個固定的隨機種子,以保證接下來的步驟中結果是一致的。

2.數據集 Dataset

首先,讓我們獲取將要使用的數據集, 下面的代碼會將一個包含“花的圖形”的2分分類數據集加載到變量X和Y中。

X, Y = load_planar_dataset()

使用 matplotlib可視化數據集。看上去就象一朵花,它由一些紅色點(標籤y=0)和藍色點(標籤y=1)組成。
你的目標就是要構建一個模型擬合(fit)這些數據。

# Visualize the data: 可視化數據
plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);#繪製散點圖
plt.show()

運行結果如下圖
在這裏插入圖片描述

補充,load_planar_dataset函數內容如下

def load_planar_dataset():
    np.random.seed(1)
    m = 400 # number of examples
    N = int(m/2) # number of points per class
    D = 2 # dimensionality
    X = np.zeros((m,D)) # data matrix where each row is a single example
    Y = np.zeros((m,1), dtype='uint8') # labels vector (0 for red, 1 for blue)
    a = 4 # maximum ray of the flower

    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 # theta
        r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius
        X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
        Y[ix] = j
        
    X = X.T
    Y = Y.T

    return X, Y

現在你已經有了

  • 一個numpy矩陣X,包含特徵x1x_1x2x_2
  • 一個numpy矩陣Y,包含分類標籤(紅色:0, 藍色:1)

讓我們更好地瞭解我們的數據是什麼樣的。例如

  • 有多少訓練樣本
  • 變量X和Y的形狀是怎麼樣的

代碼如下

### START CODE HERE ### (≈ 3 lines of code)
shape_X = X.shape
shape_Y = Y.shape
m = Y.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.簡單邏輯迴歸分類器(線性分類)–效果不佳

在構建完整的NN之前,讓我們先看看邏輯迴歸在這個問題上的表現如何。你可以使用sklearn的內置函數來實現。

在數據集上訓練邏輯迴歸分類器,代碼如下。

clf = sklearn.linear_model.LogisticRegressionCV()
clf.fit(X.T,Y.T)

運行後顯示結果如下

C:\Users\toddc\Anaconda3\lib\site-packages\sklearn\utils\validation.py:526: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  y = column_or_1d(y, warn=True)

你可以繪製模型的決策邊界。代碼如下

# Plot the decision boundary for logistic regression 繪製邏輯迴歸決策邊界
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")
plt.show()

# 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)")
print ("邏輯迴歸的準確率: %d " % float((np.dot(Y, LR_predictions) + 
		np.dot(1 - Y,1 - LR_predictions)) / float(Y.size) * 100) +
       "% " + "(正確標籤的數據點所佔的百分比)")

運行結果如下

邏輯迴歸的準確率: 47 % (正確標籤的數據點所佔的百分比)

分類結果如下
在這裏插入圖片描述

準確率只有47%的原因是該數據集顯然不是線性可分的,所以邏輯迴歸分類器表現不佳。
希望NN可以表現的更好。

4.單隱層NN模型

邏輯迴歸在“花”數據集上表現不佳。現在我們來訓練單隱層NN。

下圖是我們的模型
在這裏插入圖片描述

模型的數學公式,可以參見鏈接

對於訓練樣本x(i)x^{(i)}:
z[1](i)=W1]x(i)+b[1](i)z^{[1](i)}=W^{1]}x^{(i)}+b^{[1](i)}
a[1](i)=tanh(z[1](i))a^{[1](i)}=tanh(z^{[1](i)})
z[2](i)=W[2]a[1](i)+b[2](i)z^{[2](i)}=W^{[2]}a^{[1](i)}+b^{[2](i)}
預測值爲y^(i)=a[2](i)=σ(z[2](i))={1,if a[2](i)>0.50,otherwise\hat y^{(i)}=a^{[2](i)}=σ(z^{[2](i)})=\begin{cases} 1, & \text {if $a^{[2](i)} > 0.5$} \\ 0, & \text{otherwise} \end{cases}
獲得所有樣本的預測值之後,你可以計算成本
J=1mi=0m(y(i)log(a[2](i))+(1y(i))log(1a[2](i)))J=−\frac 1m \sum_{i=0}^m(y^{(i)}log(a^{[2](i)})+(1−y^{(i)})log(1−a^{[2](i)}))

建立NN的一般辦法如下

  • 定義NN結構(輸入單元,隱藏單元等等)
  • 初始化模型的參數
  • 循環
    • 實現前向傳播
    • 計算損失
    • 實現反向傳播,獲得梯度
    • 更新參數(梯度下降)

通常將上述1-3步分別定義成一個輔助函數,再把它們合併到一個函數中nn_model()。在構築好nn_model(),並迭代獲取到正確的參數之後,即可對新數據進行預測。

4.1定義NN結構

定義3個變量

  • n_x: 輸入層(單元)的數量
  • n_h: 隱藏層(單元)的數量-在這裏設置爲4
  • n_y: 輸出層(單元)的數量

使用矩陣X和Y的大小定義n_x和n_y。同時n_h賦值爲4。代碼如下

# GRADED FUNCTION: layer_sizes

def layer_sizes(X, Y):
    """
    Arguments:
    X -- input dataset of shape (input size, number of examples) 輸入數據集,維度爲(輸入的數量,樣本的數量)
    Y -- labels of shape (output size, number of examples) 標籤,維度爲(輸出的數量,樣本的數量)
    
    Returns:
    n_x -- the size of the input layer
    n_h -- the size of the hidden layer
    n_y -- the size of the output layer
    """
    ### START CODE HERE ### (≈ 3 lines of code)
    n_x = X.shape[0] # size of input layer
    n_h = 4
    n_y = Y.shape[0] # size of output layer
    ### END CODE HERE ###
    return (n_x, n_h, n_y)

利用testCases.py的測試函數layer_sizes_test_case(),可以試一下效果

X_assess, Y_assess = layer_sizes_test_case()
(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_parameters()函數來完成。

說明:

  • 請根據上面NN的模型圖,確保你參數的大小是正確的。
  • 用隨機值初始化你的權重矩陣。利用np.random.randn(a,b) * 0.01來隨機初始化一個維度爲(a,b)的矩陣。
  • 偏移向量初始化爲零。利用np.zeros((a,b))來給一個維度爲(a,b)的矩陣賦值零。

初始化代碼如下

# GRADED FUNCTION: initialize_parameters

def initialize_parameters(n_x, n_h, n_y):
    """
    Argument:
    n_x -- size of the input layer
    n_h -- size of the hidden layer
    n_y -- size of the output layer
    
    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) * 0.01
    b1 = np.zeros(shape=(n_h, 1))
    W2 = np.random.randn(n_y, n_h) * 0.01
    b2 = np.zeros(shape=(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

利用testCases.py的測試函數initialize_parameters_test_case()試一下效果

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"]))

運行後,得到結果如下

W1 = [[-0.00416758 -0.00056267]
 [-0.02136196  0.01640271]
 [-0.01793436 -0.00841747]
 [ 0.00502881 -0.01245288]]
b1 = [[ 0.]
 [ 0.]
 [ 0.]
 [ 0.]]
W2 = [[-0.01057952 -0.00909008  0.00551454  0.02292208]]
b2 = [[ 0.]]

initialize_parameters_test_case()定義如下

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賦值,在這裏似乎可以直接使用實際數據,完全沒有必要搞個測試函數。
當然,如果你數據量很大的情況,可以用上述的方法,使用測試函數,而不必導入實際數據集來獲得結構數據n_x, n_h, n_y,節省初始化參數函數initialize_parameters()的測試時間。

4.3循環

4.3.1實現前向傳播

說明:

  • 請參照上面分類器模型的數學公式
  • 使用sigmoid()函數,它包含在planar_utils.py中。
  • 使用np.tanh()函數,它是numpy的內置函數。
  • 實現步驟如下
    • 使用parameters[".."]從字典“parameters”中獲取參數。它是由initialize_parameters()函數輸出的。
    • 實現向前傳播, 計算Z[1]Z^{[1]},A[1]A^{[1]},Z[2]Z^{[2]},A[2]A^{[2]}( 訓練集裏面所有樣本的預測向量)。
    • 反向傳播需要的值都保存在”cache“中。cache將作爲反向傳播函數的輸入。

4.3.1.1 構建forward_propagation()函數。

代碼如下

# GRADED FUNCTION: forward_propagation

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)
    # 實現前向傳播計算A2(預測值)
    ### 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 ###
    
    #使用斷言確保我的數據格式是正確的
    assert(A2.shape == (1, X.shape[1]))
    
    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)

# Note: we use the mean here just to make sure that your output matches ours. 
print("forward_propagation:",np.mean(cache['Z1']), np.mean(cache['A1']), np.mean(cache['Z2']), np.mean(cache['A2']))

運行結果如下

forward_propagation: -0.000499755777742 -0.000496963353232 0.000438187450959 0.500109546852

現在我們已經計算了A[2]A^{[2]}(或者說y^\hat y),其中a[2](i)a^{[2](i)}包含了訓練集裏每個樣本預測值,下面就可以構建成本函數了。

4.3.1.2 構建compute_cost()函數

實現compute_cost()函數,計算整個數據集的成本值
J=1mi=0m(y(i)log(a[2](i))+(1y(i))log(1a[2](i)))J=−\frac 1m \sum_{i=0}^m(y^{(i)}log(a^{[2](i)})+(1−y^{(i)})log(1−a^{[2](i)}))

說明:

  • 有很多方法可以計算交叉熵損失。在python中計算交叉熵損失函數i=0my(i)log(a[2](i))−\sum_{i=0}^my^{(i)}log(a^{[2](i)})可以用如下的兩步驟實現:
logprobs = np.multiply(np.log(A2),Y) #對應元素相乘
cost = - np.sum(logprobs)            # 不需要使用循環就可以直接算出來。

當然,你也可以使用np.multiply()然後使用np.sum()或者直接使用np.dot()。

成本計算實現如下

# GRADED FUNCTION: compute_cost

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
    
    # Retrieve W1 and W2 from parameters
    ### START CODE HERE ### (≈ 2 lines of code)
    W1 = parameters['W1']
    W2 = parameters['W2']
    ### END CODE HERE ###
    
    # Compute the cross-entropy cost#計算成本
    ### START CODE HERE ### (≈ 2 lines of code)
    logprobs = np.multiply(np.log(A2), Y) + np.multiply((1 - Y), np.log(1 - A2))
    cost = - np.sum(logprobs) / m
    ### 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)))

運行結果如下

cost = 0.692919893776

4.3.2實現反向傳播

使用前向傳播計算得到的cache,我們可以來實現反向傳播backward_propagation()。

說明:反向傳播通常是DL中最難(數學意義上)部分。爲了幫助你,我們把講義中的內容再次歸納如下。爲了構建向量化的實現,你需要6個方程式。
在這裏插入圖片描述
提示:

  • 爲了計算dZ1,你需要計算 g[1](Z[1])g^{[1]′}(Z^{[1]})g[1]()g^{[1]}()是tanh激活函數。如果a=g[1](z)a=g^{[1]}(z),那麼g[1](Z)=1a2g^{[1]′}(Z)=1−a^2。所以我們需要使用 (1 - np.power(A1, 2))來計算 g[1](Z[1])g^{[1]′}(Z^{[1]})

4.3.2.1 構建backward_propagation()函數

代碼如下

# GRADED FUNCTION: backward_propagation

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
                  包含W和b的導數(梯度)一個字典類型的變量
    """
    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 / m) * np.dot(dZ2, A1.T)
    db2 = (1 / m) * np.sum(dZ2, axis=1, keepdims=True)
    dZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2))
    dW1 = (1 / m) * np.dot(dZ1, X.T)
    db1 = (1 / 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"]))

運行結果如下

dW1 = [[ 0.01018708 -0.00708701]
 [ 0.00873447 -0.0060768 ]
 [-0.00530847  0.00369379]
 [-0.02206365  0.01535126]]
db1 = [[-0.00069728]
 [-0.00060606]
 [ 0.000364  ]
 [ 0.00151207]]
dW2 = [[ 0.00363613  0.03153604  0.01162914 -0.01318316]]
db2 = [[ 0.06589489]]

4.3.2.2 更新參數

使用梯度下降。你可以使用(dW1, db1, dW2, db2)來更新(W1, b1, W2, b2)。

梯度下降規則:θ=θαJθ\theta = \theta - \alpha \frac{\partial J }{ \partial \theta }

  • α\alpha:學習率
  • θ\theta:待更新的參數

選擇好的學習率,迭代纔會收斂(converging),如下圖
在這裏插入圖片描述

否則迭代過程不斷振盪,呈發散狀態(diverging),如下圖
在這裏插入圖片描述

實現代碼如下

# GRADED FUNCTION: update_parameters

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 
                           包含更新參數的python 字典類型的變量
    """
    # 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"]))

運行結果

W1 = [[-0.00643025  0.01936718]
 [-0.02410458  0.03978052]
 [-0.01653973 -0.02096177]
 [ 0.01046864 -0.05990141]]
b1 = [[ -1.02420756e-06]
 [  1.27373948e-05]
 [  8.32996807e-07]
 [ -3.20136836e-06]]
W2 = [[-0.01041081 -0.04463285  0.01758031  0.04747113]]
b2 = [[ 0.00010457]]

4.4把4.1,4.2,4.3整合到nn_model()

把你的NN模型整合到nn_model()

說明:NN模型必須以正確的順序使用先前的函數。

代碼如下

# GRADED FUNCTION: 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
                           如果爲True,則每1000次迭代打印一次成本數值
    
    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)
        
        ### 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=False)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

運行結果如下

1.py:136: RuntimeWarning: divide by zero encountered in log
  logprobs = np.multiply(np.log(A2), Y) + np.multiply((1 - Y), np.log(1 - A2))
C:\planar_utils.py:34: RuntimeWarning: overflow encountered in exp
  s = 1/(1+np.exp(-x))
W1 = [[-4.18494482  5.33220319]
 [-7.52989354  1.24306197]
 [-4.19295428  5.32631786]
 [ 7.52983748 -1.24309404]]
b1 = [[ 2.32926815]
 [ 3.7945905 ]
 [ 2.33002544]
 [-3.79468791]]
W2 = [[-6033.83672179 -6008.12981272 -6033.10095329  6008.06636901]]
b2 = [[-52.66607704]]

4.5預測

構建函數predict(),使用你的模型進行預測。利用前向傳播獲得預測結果。

預測公式
prediction={1,if activation > 0.50,otherwiseprediction=\begin{cases} 1, & \text {if activation > 0.5} \\ 0, & \text{otherwise} \end{cases}

如果你想根據閾值設置矩陣X的項爲0或者1 ,你可以用以下方式X_new = (X > threshold)

代碼如下

# GRADED FUNCTION: predict

def predict(parameters, X):
    """
    Using the learned parameters, predicts a class for each example in X
                 使用學習的參數,爲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 = np.round(A2)
    ### END CODE HERE ###
    
    return predictions

測試一下

parameters, X_assess = predict_test_case()

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

運行結果

predictions mean = 0.666666666667

現在我們終於可以運行整個模型,看看它在平面數據集上的性能如何。

運行代碼

# 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))
plt.show()

運行結果

Cost after iteration 0: 0.693048
Cost after iteration 1000: 0.288083
Cost after iteration 2000: 0.254385
Cost after iteration 3000: 0.233864
Cost after iteration 4000: 0.226792
Cost after iteration 5000: 0.222644
Cost after iteration 6000: 0.219731
Cost after iteration 7000: 0.217504
Cost after iteration 8000: 0.219504
Cost after iteration 9000: 0.218571

10000次迭代後,損失收斂。

分類結果如下圖
在這裏插入圖片描述

對比原圖
在這裏插入圖片描述

分類效果還是不錯的。

再來看看準確率

# Print accuracy
predictions = predict(parameters, X)
print ('Accuracy: %d' % float((np.dot(Y, predictions.T) + np.dot(1 - Y, 1 - predictions.T)) / float(Y.size) * 100) + '%')

預測結果準確率爲

Accuracy: 90%

對比邏輯迴歸線性模型分類的結果49%,準確率還是很高的。

單隱層NN模型準確學習到了花的葉子形狀。不像邏輯迴歸模型,NN甚至可以學習高度非線性決策邊界

4.6調整隱藏層(單元)的數量

運行下面的代碼,我們觀察不同隱藏層(單元)數量模型的表現。

# 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 ("Accuracy for {} hidden units: {} %".format(n_h, accuracy))
plt.show()

運行結果如下

Accuracy for 1 hidden units: 67.5 %
Accuracy for 2 hidden units: 67.25 %
Accuracy for 3 hidden units: 90.75 %
Accuracy for 4 hidden units: 90.5 %
Accuracy for 5 hidden units: 91.25 %
Accuracy for 20 hidden units: 90.0 %
Accuracy for 50 hidden units: 90.75 %

說明:

  • 較大的模型(具有更多隱藏單元)能夠更好地擬合訓練集,直到最終出現大模型過度擬合數據。
  • 最佳的隱藏層單元數看上去應該是n_h = 5。事實上,它可以很好的擬合數據,也不會出現過擬合現象。
  • 後面會學習的正則化,它允許我們使用非常大的模型(如n_h = 50),而不會出現太多過擬合。

7種隱藏單元數量的分類效果如下
在這裏插入圖片描述

總結

到現在爲止,你已經學習了

  • 構建一個完整的單隱層NN
  • 很好的利用了一個非線性單元(激活函數tanh)
  • 實現前向傳播和反向傳播,訓練NN
  • 觀察隱藏單元數量變化的影響,例如:過擬合

5.單隱層NN模型在其他數據集上的表現

在planar_utils.py中還有其他幾個數據集,如果你有興趣,可以單隱層NN在不同數據集上的表現

把代碼中原來加載數據集的代碼

X, Y = load_planar_dataset()

替換爲

# Datasets
noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets()

datasets = {"noisy_circles": noisy_circles,
            "noisy_moons": noisy_moons,
            "blobs": blobs,
            "gaussian_quantiles": gaussian_quantiles}

### START CODE HERE ### (choose your dataset)
dataset = "noisy_moons"
### END CODE HERE ###

X, Y = datasets[dataset]
X, Y = X.T, Y.reshape(1, Y.shape[0])

一共有4個數據集。這裏我們嘗試noisy_moons,如下圖
在這裏插入圖片描述

  • 數據集基本情況如下
The shape of X is: (2, 200)
The shape of Y is: (1, 200)
I have m = 200 training examples!

使用ML的邏輯迴歸算法分類結果如下
在這裏插入圖片描述

  • 線性邏輯歸回分類準確率
邏輯迴歸的準確率: 86 % (正確標籤的數據點所佔的百分比)

由於數據點在平面上的分佈比“花”圖案要更加接近上下兩分,所以線性分類的準確率要比“花”數據集高。

  • 使用noisy_moon數據集訓練NN的模型結構是一樣的。
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
  • 迭代10000次訓練後的預測分類效果如下
    在這裏插入圖片描述

顯然是非線性的分類。

  • 損失情況
Cost after iteration 0: 0.693001
Cost after iteration 1000: 0.316565
Cost after iteration 2000: 0.316976
Cost after iteration 3000: 0.316195
Cost after iteration 4000: 0.099362
Cost after iteration 5000: 0.094746
Cost after iteration 6000: 0.093921
Cost after iteration 7000: 0.093484
Cost after iteration 8000: 0.093183
Cost after iteration 9000: 0.093096
  • 單隱層NN(4個神經元)預測準確率
Accuracy: 96%
  • 不同數量隱藏單元預測準確率
Accuracy for 1 hidden units: 86.0 %
Accuracy for 2 hidden units: 88.0 %
Accuracy for 3 hidden units: 97.0 %
Accuracy for 4 hidden units: 96.5 %
Accuracy for 5 hidden units: 96.0 %
Accuracy for 20 hidden units: 86.0 %
Accuracy for 50 hidden units: 86.0 %

6.完整代碼

全部代碼下載鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章