主頁 >  其他 > 吳恩達《神經網路和深度學習》第三周編程作業—用一層隱藏層的神經網路分類二維資料

吳恩達《神經網路和深度學習》第三周編程作業—用一層隱藏層的神經網路分類二維資料

2021-11-13 20:12:05 其他

吳恩達《神經網路和深度學習》—用一層隱藏層的神經網路分類二維資料

  • 1 安裝包
  • 2 資料集
  • 3 簡單Logistic回歸
  • 4 神經網路模型
    • 4.1 定義神經網路結構
    • 4.2 初始化模型的引數
    • 4.3 回圈
      • 4.3.1 前向傳播
      • 4.3.2 計算成本
      • 4.3.3 后向傳播
      • 4.3.4 使用梯度下降演算法實作引數更新
    • 4.4 集成
    • 4.5 預測
    • 4.6 調整隱藏層大小
  • 5 模型在其他資料集上的性能

※※※※※上一篇:【用神經網路思想實作邏輯回歸】※※※※※


??現在是時候建立你的第一個神經網路了,它將具有一層隱藏層,你將看到此模型與你使用邏輯回歸實作的模型之間的巨大差異,

做完該作業將掌握的技能:
?? ? \bullet ? 實作具有單個隱藏層的二分類神經網路
?? ? \bullet ? 使用具有非線性激活函式的神經元,例如tanh
?? ? \bullet ? 計算交叉熵損失
?? ? \bullet ? 實作前向和后向傳播

??本文所使用的資料:【點擊下載】,提取碼:rc4u,請在開始之前下載好所需資料,然后將檔案解壓到你的代碼檔案同一級目錄下,請確保你的代碼那里有planar_utils.pytestCases.py檔案夾,

1 安裝包

??讓我們首先匯入在作業程序中需要的所有軟體包,

?? ? \bullet ? numpy:是Python科學計算的基本包,
?? ? \bullet ? sklearn:提供了用于資料挖掘和分析的簡單有效的工具,
?? ? \bullet ? matplotlib:是一個著名的Python圖形庫,
?? ? \bullet ? testCases:提供了一些測驗示例來評估函式的正確性,參見下載的資料或者在底部查看它的代碼,
?? ? \bullet ? planar_utils:提供了在這個任務中使用的各種有用的功能,參見下載的資料或者在底部查看它的代碼,

??如果你沒有以上的庫,請自行安裝,并且在需要時按如下方式加載到程式中,

# Package imports
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) #設定一個固定的隨機種子,以保證接下來的步驟中我們的結果是一致的,

2 資料集

??首先,讓我們獲取處理的資料集,以下代碼會將flower 二分類資料集加載到變數 X X X Y Y Y 中,

X, Y = load_planar_dataset() 

??把資料集加載完成了,然后使用matplotlib可視化資料集,代碼如下:

【代碼】

# Visualize the data:
plt.scatter(X[0, :], X[1, :], c=Y.reshape(X[0,:].shape), s=40, cmap=plt.cm.Spectral)

【結果】
在這里插入圖片描述

??資料看起來像是帶有一些紅色(標簽 y y y = 0)和一些藍色( y y y = 1)點的“花”,我們的目標是建立一個適合該資料的分類模型,現在,我們已經有了以下的東西:

?? ? \bullet ? X X X:包含特征( x 1 x1 x1 x 2 x2 x2)的numpy陣列(矩陣)
?? ? \bullet ? Y Y Y:包含標簽(紅色:0,藍色:1)的numpy陣列(向量)

??接著,讓我們深入地了解一下我們的資料,

【代碼】

shape_X = X.shape
shape_Y = Y.shape
m = Y.shape[1]  # 訓練集里面的數量

print("X的維度為: " + str(shape_X))
print("Y的維度為: " + str(shape_Y))
print("資料集里面的資料有:" + str(m) + " 個")

【結果】

X的維度為: (2, 400)
Y的維度為: (1, 400)
資料集里面的資料有:400

3 簡單Logistic回歸

??在構建完整的神經網路之前,首先讓我們看看邏輯回歸在此問題上的表現,你可以使用sklearn的內置函式來執行此操作,運行以下代碼以在資料集上訓練邏輯回歸分類器,

【代碼】

# 訓練邏輯回歸分類器
clf = sklearn.linear_model.LogisticRegressionCV()
clf.fit(X.T, Y.T)

【結果】
??這里會列印出以下的資訊(不同的機器提示大同小異):

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_decision_boundary(lambda x: clf.predict(x), X, Y)  # 繪制決策邊界
plt.title("Logistic Regression")                        # 圖示題
LR_predictions = clf.predict(X.T)                       # 預測結果
print('邏輯回歸的準確性: %d ' % float((np.dot(Y, LR_predictions) +
                                                      np.dot(1-Y, 1-LR_predictions))/float(Y.size)*100) +
      '% ' + "(正確標記的資料點所占的百分比)")

【結果】

邏輯回歸的準確性: 47 % (正確標記的資料點所占的百分比)

在這里插入圖片描述

??可以看到,利用邏輯回歸分類器得到的準確性只有47%,這主要是因為資料集不是線性可分類的,而邏輯回歸分類器是線性分類器,因此邏輯回歸效果不佳, 讓我們試試是否神經網路會做得更好吧!

4 神經網路模型

??從上面我們可以得知Logistic回歸不適用于flower資料集,現在你將訓練帶有單個隱藏層的神經網路,

【模型】
在這里插入圖片描述

【數學原理】

??對于樣本 x ( i ) x^{\left ( i \right )} x(i)
z [ 1 ] ( i ) = W [ 1 ] x ( i ) + b [ 1 ] ( i ) (1) z^{\left [ 1 \right ]\left ( i \right )} = W^{\left [ 1 \right ]}x^{\left ( i \right )}+b^{\left [ 1 \right ]\left ( i \right )} \tag{1} z[1](i)=W[1]x(i)+b[1](i)(1) a [ 1 ] ( i ) = t a n h ( z [ 1 ] ( i ) ) (2) a^{\left [ 1 \right ]\left ( i \right )}=tanh\left ( z^{\left [ 1 \right ]\left ( i \right )} \right )\tag{2} a[1](i)=tanh(z[1](i))(2) z [ 2 ] ( i ) = W [ 2 ] a [ 1 ] ( i ) + b [ 2 ] ( i ) (3) z^{\left [ 2 \right ]\left ( i \right )} = W^{\left [ 2 \right ]}a^{\left [ 1 \right ] \left ( i \right )}+b^{\left [ 2 \right ]\left ( i \right )} \tag{3} z[2](i)=W[2]a[1](i)+b[2](i)(3) y ^ ( i ) = a [ 2 ] ( i ) = σ ( z [ 2 ] ( i ) ) (4) \hat{y}^{\left ( i \right )}=a^{\left [ 2 \right ]\left ( i \right )}=\sigma \left ( z^{\left [ 2 \right ]\left ( i \right )} \right ) \tag{4} y^?(i)=a[2](i)=σ(z[2](i))(4) y p r e d i c t i o n ( i ) = { 1 if a [ 2 ] ( i ) > 0.5 0 o t h e r w i s e (5) y_{prediction}^{\left ( i \right )}=\begin{cases} 1 & \text{ if } a^{\left [ 2 \right ]\left ( i \right )}>0.5 \\ 0 & otherwise \end{cases} \tag{5} yprediction(i)?={10? if a[2](i)>0.5otherwise?(5)
??根據所有的樣本資料,可以根據下式計算損失 J J J J = ? 1 m ∑ i = 1 m ( y ( i ) l o g ( a [ 2 ] ( i ) ) + ( 1 ? y ( i ) ) l o g ( 1 ? a [ 2 ] ( i ) ) ) (6) J = -\frac{1}{m}\sum_{i=1}^{m}\left ( y^{\left ( i \right )}log\left ( a^{\left [ 2 \right ]\left ( i \right )} \right ) + \left ( 1-y^{\left ( i \right )} \right )log\left ( 1-a^{\left [ 2 \right ]\left ( i \right )} \right ) \right ) \tag{6} J=?m1?i=1m?(y(i)log(a[2](i))+(1?y(i))log(1?a[2](i)))(6)

【構建神經網路的步驟】

??1. 定義神經網路結構(輸入單元數,隱藏單元數等)
??2. 初始化模型的引數
??3. 回圈:
???? ? \bullet ? 實作前向傳播
???? ? \bullet ? 計算成本
???? ? \bullet ? 后向傳播以獲得梯度
???? ? \bullet ? 更新引數(梯度下降)

??我們通常會構建輔助函式來計算第1-3步,然后將它們合并為nn_model()函式,一旦構建了nn_model()并學習了正確的引數,就可以對新資料進行預測,

4.1 定義神經網路結構

??首先,我們需要宣告以下3個變數來定義神經網路的結構:

?? ? \bullet ? n_x:輸入層的大小
?? ? \bullet ? n_h:隱藏層的大小(將其設定為4)
?? ? \bullet ? n_y:輸出層的大小

【代碼】

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
    """
    n_x = X.shape[0]  # size of input layer
    n_h = 4
    n_y = Y.shape[0]  # size of output layer

    return n_x, n_h, n_y

【測驗】

# 測驗layer_sizes
print("=========================測驗layer_sizes=========================")
X_asses, Y_asses = layer_sizes_test_case()
(n_x, n_h, n_y) = layer_sizes(X_asses, Y_asses)
print("輸入層的節點數量為: n_x = " + str(n_x))
print("隱藏層的節點數量為: n_h = " + str(n_h))
print("輸出層的節點數量為: n_y = " + str(n_y))

【結果】

=========================測驗layer_sizes=========================
輸入層的節點數量為: n_x = 5
隱藏層的節點數量為: n_h = 4
輸出層的節點數量為: n_y = 2

4.2 初始化模型的引數

??接下來,我們需要實作初始化模型引數的函式initialize_parameters()

【說明】

?? ? \bullet ? 請確保引數大小正確, 如果需要,也可參考上面的神經網路圖,
?? ? \bullet ? 使用隨機值初始化權重矩陣:使用:np.random.randn(a,b)* 0.01隨機初始化維度為(a,b)的矩陣,
?? ? \bullet ? 將偏差向量初始化為零:使用:np.zeros((a,b))初始化維度為(a,b)零的矩陣,

【代碼】

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)  # 指定一個隨機種子,以便你的輸出與我們的一樣,

    W1 = np.random.randn(n_h, n_x) * 0.01
    b1 = np.zeros((n_h, 1))
    W2 = np.random.randn(n_y, n_h) * 0.01
    b2 = np.zeros((n_y, 1))

    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
print("=========================測驗initialize_parameters=========================")
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"]))

【結果】

=========================測驗initialize_parameters=========================
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.]]

4.3 回圈

4.3.1 前向傳播

??在這一步中,我們需要根據以下說明來實作前向傳播函式forward_propagation()

?? ? \bullet ? 可以使用sigmoid()函式,也可以使用np.tanh()函式,
?? ? \bullet ? 使用parameters [“..”]從字典 parameters(這是initialize_parameters()的輸出)中檢索出每個引數,
?? ? \bullet ? 實作正向傳播,計算 Z [ 1 ] , ? A [ 1 ] , ? Z [ 2 ] , ? Z [ 2 ] Z^{\left [ 1 \right ]},\, A^{\left [ 1 \right ]},\,Z^{\left [ 2 \right ]},\,Z^{\left [ 2 \right ]} Z[1],A[1],Z[2],Z[2](所有訓練資料的預測結果向量),
?? ? \bullet ? 向后傳播所需的值存盤在cache中, cache將作為反向傳播函式的輸入,

【代碼】

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"
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]

    # Implement Forward Propagation to calculate A2 (probabilities)
    Z1 = np.dot(W1, X) + b1
    A1 = np.tanh(Z1)
    Z2 = np.dot(W2, A1) + b2
    A2 = sigmoid(Z2)

    assert (A2.shape == (1, X.shape[1]))

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

    return A2, cache

【測驗】

# 測驗forward_propagation
print("=========================測驗forward_propagation=========================")
X_assess, parameters = forward_propagation_test_case()
A2, cache = forward_propagation(X_assess, parameters)
print(np.mean(cache["Z1"]), np.mean(cache["A1"]), np.mean(cache["Z2"]), np.mean(cache["A2"]))

【結果】

=========================測驗forward_propagation=========================
-0.0004997557777419913 -0.0004969633532317802 0.0004381874509591466 0.500109546852431

4.3.2 計算成本

??現在,我們已經計算了包含每個示例的 a [ 2 ] ( i ) a^{\left [ 2 \right ]\left ( i \right )} a[2](i) A [ 2 ] A^{\left [ 2 \right ]} A[2](在Python變數“A2”中),然后就可以根據公式(6)來實作成本函式compute_cost()

【說明】
??有很多的方法都可以計算交叉熵損失,比如對于下面的這個公式, ? ∑ i = 1 m y ( i ) l o g ( a [ 2 ] ( i ) ) -\sum_{i=1}^{m}y^{\left ( i \right )}log\left ( a^{\left [ 2 \right ]\left ( i \right )} \right ) ?i=1m?y(i)log(a[2](i))

我們在python中可以這么實作:

logprobs = np.multiply(np.log(A2),Y)
cost = - np.sum(logprobs)                # 不需要使用回圈就可以直接算出來,

??當然,我們也可以直接使用np.dot()來進行計算,

【代碼】

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
    logprobs = Y * np.log(A2) + (1 - Y) * np.log(1 - A2)
    cost = -1 / m * np.sum(logprobs)

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

    return cost

【測驗】

# 測驗compute_cost
print("=========================測驗compute_cost=========================")
A2, Y_assess, parameters = compute_cost_test_case()
print("cost = " + str(compute_cost(A2, Y_assess, parameters)))

【結果】

=========================測驗compute_cost=========================
cost = 0.6929198937761265

4.3.3 后向傳播

??接下來,就可以使用在正向傳播期間計算的快取,來實作后向傳播backward_propagation()

【數學原理】

??反向傳播通常是深度學習中最難(數學)的部分,為了幫助你更好地了解,你可以借助以下六個方程式來構建向量化實作,

在這里插入圖片描述

【說明】

?? ? \bullet ? ? \ast ? 表示對應元素相乘,
?? ? \bullet ? 使用在深度學習中很常見的編碼表示方法: d W 1 = ? J ? W 1 dW1=\frac{\partial J}{\partial W_1} dW1=?W1??J? d b 1 = ? J ? b 1 db1=\frac{\partial J}{\partial b_1} db1=?b1??J? d W 2 = ? J ? W 2 dW2=\frac{\partial J}{\partial W_2} dW2=?W2??J? d b 2 = ? J ? b 2 db2=\frac{\partial J}{\partial b_2} db2=?b2??J??? ? \bullet ? 要計算 d Z 1 dZ1 dZ1,首先需要計算 g [ 1 ] ′ ( z [ 1 ] ) g^{\left [ 1 \right ]'}\left ( z^{[1]} \right ) g[1](z[1]),由于 g [ 1 ] ( ? ) g^{\left [ 1 \right ]}\left ( \cdot \right ) g[1](?)tanh激活函式,因此如果 a = g [ 1 ] ( z ) a = g^{\left [ 1 \right ]}\left ( z \right ) a=g[1](z),則 g [ 1 ] ′ ( z ) = 1 ? a 2 g^{\left [ 1 \right ]'}\left ( z \right ) = 1-a^{2} g[1](z)=1?a2,所以,可以使用(1 - np.power(A1, 2))計算 g [ 1 ] ′ ( z [ 1 ] ) g^{\left [ 1 \right ]'}\left ( z^{[1]} \right ) g[1](z[1])

【代碼】

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".
    W1 = parameters["W1"]
    W2 = parameters["W2"]

    # Retrieve also A1 and A2 from dictionary "cache".
    A1 = cache["A1"]
    A2 = cache["A2"]

    # Backward propagation: calculate dW1, db1, dW2, db2.
    dZ2 = A2 - Y
    dW2 = 1 / m * np.dot(dZ2, A1.T)
    db2 = 1 / m * np.sum(dZ2, axis=1, keepdims=True)
    dZ1 = 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)

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

    return grads

【測驗】

# 測驗backward_propagation
print("=========================測驗backward_propagation=========================")
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"]))

【結果】

=========================測驗backward_propagation=========================
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.4 使用梯度下降演算法實作引數更新

??現在,我們就可以利用梯度下降演算法來實作引數的更新了,使用梯度下降,必須使用 ( d W 1 , d b 1 , d W 2 , d b 2 ) (dW1,db1,dW2,db2) dW1db1dW2db2才能更新 ( W 1 , b 1 , W 2 , b 2 ) (W1,b1,W2,b2) W1b1W2b2,一般的梯度下降規則為: θ = θ ? α ? J ? θ \theta =\theta -\alpha\frac{\partial J}{\partial \theta } θ=θ?α?θ?J?其中 α \alpha α 是學習率,而 θ \theta θ 代表一個引數,

??下面兩幅圖展示了具有良好的學習速率(收斂)和較差的學習速率(發散)的梯度下降演算法,

在這里插入圖片描述
在這里插入圖片描述

【代碼】

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"
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]

    # Retrieve each gradient from the dictionary "grads"
    dW1 = grads["dW1"]
    db1 = grads["db1"]
    dW2 = grads["dW2"]
    db2 = grads["db2"]

    # Update rule for each parameter
    W1 = W1 - learning_rate * dW1
    b1 = b1 - learning_rate * db1
    W2 = W2 - learning_rate * dW2
    b2 = b2 - learning_rate * db2

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

    return parameters

【測驗】

# 測驗update_parameters
print("=========================測驗update_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"]))

【結果】

=========================測驗update_parameters=========================
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 集成

??最后,通過按照正確的順序組合上述創建的函式就可以在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".
    parameters = initialize_parameters(n_x, n_h, n_y)
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]

    # Loop (gradient descent)
    for i in range(0, num_iterations):

        # 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)

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

    return parameters

【測驗】

# 測驗nn_model
print("=========================測驗nn_model=========================")
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"]))

【結果】

=========================測驗nn_model=========================
W1 = [[-4.18494714  5.33206444]
 [-7.53806726  1.20753857]
 [-4.19262445  5.32638718]
 [ 7.53804391 -1.20755126]]
b1 = [[ 2.3293681 ]
 [ 3.80995835]
 [ 2.33015051]
 [-3.80999435]]
W2 = [[-6033.82336187 -6008.1427588  -6033.08758194  6008.07912558]]
b2 = [[-52.67942084]]

4.5 預測

??為了驗證我們模型的準確性,我們可以根據nn_model()函式輸出的引數,利用正向傳播來預測結果(參考公式(5)),

【代碼】

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.
    A2, cache = forward_propagation(X, parameters)
    predictions = np.round(A2)

    return predictions

【測驗】

# 測驗predict
print("=========================測驗predict=========================")
parameters, X_assess = predict_test_case()
predictions = predict(parameters, X_assess)
print("預測的平均值 = " + str(np.mean(predictions)))

【結果】

=========================測驗predict=========================
預測的平均值 = 0.6666666666666666

??至此,所有的作業都完成了,現在我們可以正式利用我們搭建的神經網路模型來訓練flower 二分類資料集,

【代碼】

# 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.219449
Cost after iteration 9000: 0.218605

在這里插入圖片描述

??還可以利用以下代碼來查看該訓練好的神經網路模型的預測準確性,

【代碼】

# 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%

??與Logistic回歸相比,準確性確實更高, 該模型學習了flower的葉子圖案!與邏輯回歸不同,神經網路甚至能夠學習非線性的決策邊界,

4.6 調整隱藏層大小

??我們上面的實驗把隱藏層定為4個節點,現在我們更改隱藏層里面的節點數量,看一看節點數量是否會對結果造成影響,

【代碼】

plt.figure(figsize=(16, 32))
hidden_layer_sizes = [1, 2, 3, 4, 5, 10, 20]
for i, n_h in enumerate(hidden_layer_sizes):
    plt.subplot(4, 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))

在這里插入圖片描述

【說明】:根據上述結果可以看出:

?? ? \bullet ? 較大的模型(具有更多隱藏的單元)能夠更好地擬合訓練集,直到最終最大的模型過擬合資料為止,
?? ? \bullet ? 隱藏層的最佳大小似乎在n_h = 5左右,的確,此值似乎很好地擬合了資料,而又不會引起明顯的過度擬合,
?? ? \bullet ? 之后的教程還將學習正則化,幫助構建更大的模型(例如n_h = 50)而不會過度擬合,
?? ? \bullet ? 在上述代碼中,plt.figure(figsize=(16, 32)) 此行代碼需要根據自己的電腦解析度進行設定,否則畫出來的圖不好看,

5 模型在其他資料集上的性能

??如果需要,可以為以下每個資料集重新運行構建的神經網路模型(除去資料集部分),

??首先,來看一下該模型在noisy_circles資料集的運行效果(只需要把原來處理資料集的部分修改成以下代碼就可以,不需要修改其他部分):

【代碼】

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}

dataset = "noisy_circles"		# 修改不同的資料集

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

# make blobs binary
if dataset == "blobs":
    Y = Y%2

【結果】

X的維度為: (2, 200)
Y的維度為: (1, 200)
資料集里面的資料有:200 個
Cost after iteration 0: 0.693150
Cost after iteration 1000: 0.371229
Cost after iteration 2000: 0.360047
Cost after iteration 3000: 0.355231
Cost after iteration 4000: 0.352771
Cost after iteration 5000: 0.351263
Cost after iteration 6000: 0.351428
Cost after iteration 7000: 0.354861
Cost after iteration 8000: 0.354747
Cost after iteration 9000: 0.354317
Accuracy: 81%

在這里插入圖片描述
在這里插入圖片描述

??接著,來看一下該模型在noisy_moons資料集的運行效果:

【結果】

X的維度為: (2, 200)
Y的維度為: (1, 200)
資料集里面的資料有:200 個
Cost after iteration 0: 0.693001
Cost after iteration 1000: 0.316565
Cost after iteration 2000: 0.317008
Cost after iteration 3000: 0.316195
Cost after iteration 4000: 0.099350
Cost after iteration 5000: 0.094745
Cost after iteration 6000: 0.093920
Cost after iteration 7000: 0.093484
Cost after iteration 8000: 0.093183
Cost after iteration 9000: 0.093618
Accuracy: 96%

在這里插入圖片描述
在這里插入圖片描述

??然后,來看一下該模型在blobs資料集的運行效果:

【結果】

X的維度為: (2, 200)
Y的維度為: (1, 200)
資料集里面的資料有:200 個
Cost after iteration 0: 0.693527
Cost after iteration 1000: 0.324217
Cost after iteration 2000: 0.323287
Cost after iteration 3000: 0.323032
Cost after iteration 4000: 0.322912
Cost after iteration 5000: 0.322842
Cost after iteration 6000: 0.322796
Cost after iteration 7000: 0.322764
Cost after iteration 8000: 0.322739
Cost after iteration 9000: 0.322721
Accuracy: 83%

在這里插入圖片描述
在這里插入圖片描述

??最后,來看一下該模型在gaussian_quantiles資料集的運行效果:

【結果】

X的維度為: (2, 200)
Y的維度為: (1, 200)
資料集里面的資料有:200 個
Cost after iteration 0: 0.693149
Cost after iteration 1000: 0.100718
Cost after iteration 2000: 0.077908
Cost after iteration 3000: 0.067646
Cost after iteration 4000: 0.062900
Cost after iteration 5000: 0.059589
Cost after iteration 6000: 0.057225
Cost after iteration 7000: 0.055425
Cost after iteration 8000: 0.054002
Cost after iteration 9000: 0.052850
Accuracy: 98%

在這里插入圖片描述
在這里插入圖片描述

??綜合上述可以看出,我們構建的單隱層神經網路模型對該四個資料集都能夠訓練出較好的結果,準確率相對較高,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/356710.html

標籤:AI

上一篇:元學習深度決議

下一篇:雙目立體視覺(9)PyTorch & ZED 3D人體識別與追蹤 (下)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more