01.神经网络和深度学习 W3.浅层神经网络(作业:带一个隐藏层的神经网络)
文章目錄
- 1. 導入包
- 2. 預覽數據
- 3. 邏輯回歸
- 4. 神經網絡
- 4.1 定義神經網絡結構
- 4.2 初始化模型參數
- 4.3 循環
- 4.3.1 前向傳播
- 4.3.2 計算損失
- 4.3.3 后向傳播
- 4.3.4 梯度下降
- 4.4 組建Model
- 4.5 預測
- 4.6 調節隱藏層單元個數
- 4.7 更改激活函數
- 4.8 更改學習率
- 4.9 其他數據集下的表現
選擇題測試:
參考博文1
參考博文2
建立你的第一個神經網絡!其有1個隱藏層。
1. 導入包
# 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 inlinenp.random.seed(1) # set a seed so that the results are consistent2. 預覽數據
- 可視化數據
紅色的標簽為 0, 藍色的標簽為 1,我們的目標是建模將它們分開
- 數據維度
3. 邏輯回歸
# Train the logistic regression classifier clf = sklearn.linear_model.LogisticRegressionCV(); clf.fit(X.T, Y.T); # 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)") Accuracy of logistic regression: 47 % (percentage of correctly labelled datapoints)
數據集是線性不可分的,邏輯回歸變現的不好,下面看看神經網絡怎么樣。
4. 神經網絡
模型如下:
對于一個樣本 x(i)x^{(i)}x(i) 而言:
z[1](i)=W[1]x(i)+b[1](i)z^{[1] (i)} = W^{[1]} 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)})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)}z[2](i)=W[2]a[1](i)+b[2](i)
y^(i)=a[2](i)=σ(z[2](i))\hat{y}^{(i)} = a^{[2] (i)} = \sigma(z^{ [2] (i)})y^?(i)=a[2](i)=σ(z[2](i))
yprediction(i)={1if?a[2](i)>0.50otherwise?y_{\text {prediction}}^{(i)}=\left\{\begin{array}{ll}1 & \text { if } a^{[2](i)}>0.5 \\ 0 & \text { otherwise }\end{array}\right.yprediction(i)?={10??if?a[2](i)>0.5?otherwise??
得到所有的樣本的預測值后,計算損失:
J=?1m∑i=0m(y(i)log?(a[2](i))+(1?y(i))log?(1?a[2](i)))J = - \frac{1}{m} \sum\limits_{i = 0}^{m} \large\left(\small y^{(i)}\log\left(a^{[2] (i)}\right) + (1-y^{(i)})\log\left(1- a^{[2] (i)}\right) \large \right) \smallJ=?m1?i=0∑m?(y(i)log(a[2](i))+(1?y(i))log(1?a[2](i)))
建立神經網絡的一般方法:
- 1、定義神經網絡結構(輸入,隱藏單元等)
- 2、初始化模型的參數
- 3、循環:
—— a、實現正向傳播
—— b、計算損失
—— c、實現反向傳播,計算梯度
—— d、更新參數(梯度下降)
編寫輔助函數,計算步驟1-3
將它們合并到 nn_model()的函數中
學習正確的參數,對新數據進行預測
4.1 定義神經網絡結構
- 定義每層的節點個數
4.2 初始化模型參數
- 隨機初始化權重 w,偏置 b 初始化為 0
4.3 循環
4.3.1 前向傳播
- 根據上面的公式,編寫代碼
4.3.2 計算損失
- 計算了 A2,也就是每個樣本的預測值,計算損失
J=?1m∑i=0m(y(i)log?(a[2](i))+(1?y(i))log?(1?a[2](i)))J = - \frac{1}{m} \sum\limits_{i = 0}^{m} \large\left(\small y^{(i)}\log\left(a^{[2] (i)}\right) + (1-y^{(i)})\log\left(1- a^{[2] (i)}\right) \large \right) \smallJ=?m1?i=0∑m?(y(i)log(a[2](i))+(1?y(i))log(1?a[2](i)))
4.3.3 后向傳播
一些公式如下:
激活函數的導數,請查閱
- sigmoid
a=g(z);g′(z)=ddzg(z)=a(1?a)a=g(z) ;\quad g^{\prime}(z)=\fracze8trgl8bvbq{d z} g(z)=a(1-a)a=g(z);g′(z)=dzd?g(z)=a(1?a) - tanh
a=g(z);g′(z)=ddzg(z)=1?a2a=g(z) ; \quad g^{\prime}(z)=\fracze8trgl8bvbq{d z} g(z)=1-a^2a=g(z);g′(z)=dzd?g(z)=1?a2
sigmoid 下損失函數求導
# GRADED FUNCTION: backward_propagationdef 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-YdW2 = np.dot(dZ2, A1.T)/mdb2 = np.sum(dZ2, axis=1, keepdims=True)/mdZ1 = np.dot(W2.T, dZ2)*(1-np.power(A1, 2))dW1 = np.dot(dZ1, X.T)/mdb1 = np.sum(dZ1, axis=1, keepdims=True)/m### END CODE HERE ###grads = {"dW1": dW1,"db1": db1,"dW2": dW2,"db2": db2}return grads4.3.4 梯度下降
- 選取合適的學習率,學習率太大,會產生震蕩,收斂慢,甚至不收斂
4.4 組建Model
- 將上面的函數以正確順序放在 model 里
4.5 預測
predictions={1if?activation>0.50otherwisepredictions = \begin{cases} 1 & \text{if}\ activation > 0.5 \\ 0 & \text{otherwise} \end{cases}predictions={10?if?activation>0.5otherwise?
# GRADED FUNCTION: predictdef predict(parameters, X):"""Using the learned parameters, predicts a class for each example in XArguments:parameters -- python dictionary containing your parameters X -- input data of size (n_x, m)Returnspredictions -- 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- 建立一個含有1個隱藏層(4個單元)的神經網絡模型
可以看出模型較好地將兩類點分開了!準確率 90%,比邏輯回歸 47%高不少。
4.6 調節隱藏層單元個數
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)) 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.5 % Accuracy for 50 hidden units: 90.75 %
可以看出:
- 較大的模型(具有更多隱藏單元)能夠更好地適應訓練集,直到最大的模型過擬合了
- 最好的隱藏層大小似乎是n_h=5左右。這個值似乎很適合數據,而不會引起明顯的過擬合
- 稍后還將了解正則化,它允許你使用非常大的模型(如n_h=50),而不會出現太多過擬合
4.7 更改激活函數
- 將隱藏層的激活函數更改為 sigmoid 函數,準確率沒有使用tanh的高,tanh在任何場合幾乎都優于sigmoid
- 將隱藏層的激活函數更改為 ReLu 函數,似乎沒有用,感覺是需要更多的隱藏層,才能達到效果
報了些警告
C:\Users\mingm\AppData\Roaming\Python\Python37\site-packages\ ipykernel_launcher.py:20: RuntimeWarning: divide by zero encountered in log C:\Users\mingm\AppData\Roaming\Python\Python37\site-packages\ ipykernel_launcher.py:20: RuntimeWarning: invalid value encountered in multiply C:\Users\mingm\AppData\Roaming\Python\Python37\site-packages\ ipykernel_launcher.py:35: RuntimeWarning: overflow encountered in power C:\Users\mingm\AppData\Roaming\Python\Python37\site-packages\ ipykernel_launcher.py:35: RuntimeWarning: invalid value encountered in multiply C:\Users\mingm\AppData\Roaming\Python\Python37\site-packages \ipykernel_launcher.py:35: RuntimeWarning: overflow encountered in multiply4.8 更改學習率
- 采用 tanh 激活函數,調整學習率檢查效果
學習率 2.0
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.75 % Accuracy for 5 hidden units: 90.25 % Accuracy for 20 hidden units: 91.0 % Accuracy for 50 hidden units: 91.25 % best學習率 1.5
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: 89.75 % Accuracy for 5 hidden units: 90.5 % Accuracy for 20 hidden units: 91.0 % best Accuracy for 50 hidden units: 90.75 %學習率 1.2
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 % best Accuracy for 20 hidden units: 90.5 % Accuracy for 50 hidden units: 90.75 %學習率 1.0
Accuracy for 1 hidden units: 67.25 % Accuracy for 2 hidden units: 67.0 % Accuracy for 3 hidden units: 90.75 % Accuracy for 4 hidden units: 90.5 % Accuracy for 5 hidden units: 91.0 % best Accuracy for 20 hidden units: 91.0 % best Accuracy for 50 hidden units: 90.75 %學習率 0.5
Accuracy for 1 hidden units: 67.25 % Accuracy for 2 hidden units: 66.5 % Accuracy for 3 hidden units: 89.25 % Accuracy for 4 hidden units: 90.0 % Accuracy for 5 hidden units: 89.75 % Accuracy for 20 hidden units: 90.0 % best Accuracy for 50 hidden units: 89.75 %學習率 0.1
Accuracy for 1 hidden units: 67.0 % Accuracy for 2 hidden units: 64.75 % Accuracy for 3 hidden units: 88.25 % Accuracy for 4 hidden units: 88.0 % Accuracy for 5 hidden units: 88.5 % Accuracy for 20 hidden units: 88.75 % best Accuracy for 50 hidden units: 88.75 % best大致規律:
- 學習率太小,造成學習不充分,準確率較低
- 學習率越大,需要越多的隱藏單元來提高準確率?(請大佬指點)
4.9 其他數據集下的表現
均為tanh激活函數,學習率1.2
- dataset = "noisy_circles"
- dataset = "noisy_moons"
- dataset = "blobs"
- dataset = "gaussian_quantiles"
不同的數據集下,表現的效果也不太一樣。
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的01.神经网络和深度学习 W3.浅层神经网络(作业:带一个隐藏层的神经网络)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TensorFlow 2.0 - TFR
- 下一篇: LeetCode MySQL 178.