概述
如何利用Python的來實(shí)現(xiàn)具有一個(gè)隱藏層的平面數(shù)據(jù)分類問題邪码。前文谢揪,創(chuàng)建的神經(jīng)網(wǎng)絡(luò)只有一個(gè)輸出層扭弧,沒有隱藏層阎姥。本文將創(chuàng)建單隱藏層的神經(jīng)網(wǎng)絡(luò)模型。
- 二分類單隱藏層的神經(jīng)網(wǎng)絡(luò)
- 神經(jīng)元節(jié)點(diǎn)采用非線性的激活函數(shù)鸽捻,如tanh
- 計(jì)算交叉損失函數(shù)
- 運(yùn)用前向和后向傳播
準(zhǔn)備
numpy:Python科學(xué)計(jì)算中最重要的庫
sklearn:提供了一些簡(jiǎn)單而有效的工具用于數(shù)據(jù)挖掘和數(shù)據(jù)分析呼巴。
mathplotlib:Python畫圖的庫
testCases:自定義文件,封裝了一些用于測(cè)試樣本御蒲,用于評(píng)估算法的有效性伊磺。
planar_utils:自定義文件,封裝了一些作用用到的相關(guān)函數(shù)删咱。
# Package imports
import numpy as np
import matplotlib.pyplot as plt
from testCases_v2 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
np.random.seed(1) # set a seed so that the results are consistent
數(shù)據(jù)集
下述代碼將加載一個(gè)二分類的數(shù)據(jù)集并進(jìn)行可視化:
X, Y = load_planar_dataset()
# Visualize the data:
plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);
繪制出的圖像像是一朵花屑埋,對(duì)于y=0時(shí),顯示為紅色的點(diǎn)痰滋;而當(dāng)y=1時(shí)摘能,顯示的是藍(lán)色的點(diǎn)。我們的目的是希望建立一個(gè)模型可以將兩種顏色的點(diǎn)區(qū)分開敲街。
其中X是一個(gè)矩陣团搞,包含著數(shù)據(jù)的特征信息(x1,x2)
Y是一個(gè)向量多艇,包含這數(shù)據(jù)對(duì)應(yīng)的標(biāo)記結(jié)果逻恐,其中(red:0,blue:1)
尺寸信息:
### START CODE HERE ### (≈ 3 lines of code)
shape_X = X.shape
shape_Y = Y.shape
m = shape_X[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))
運(yùn)行結(jié)果可以得到X的維度為2400,Y的維度為1400,訓(xùn)練樣本的數(shù)量為400复隆。
簡(jiǎn)單的邏輯回歸
在建立一個(gè)神經(jīng)網(wǎng)絡(luò)之前拨匆,先用邏輯回歸算法來解決一下該問題⊥旆鳎可以直接使用sklearn的內(nèi)置函數(shù)來完成惭每。
# 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)")
結(jié)果為:
Accuracy of logistic regression: 47 % (percentage of correctly labelled datapoints)
得到的模型分割圖:[圖片上傳失敗...(image-6aab6c-1516700004743)]
顯然亏栈,數(shù)據(jù)集是非線性的台腥,因此邏輯回歸結(jié)果不好。
神經(jīng)網(wǎng)絡(luò)模型
神經(jīng)網(wǎng)絡(luò)的模型如下:[圖片上傳失敗...(image-16cc4c-1516700004743)]
數(shù)學(xué)角度上绒北,對(duì)于每個(gè)訓(xùn)練樣本x(i)黎侈,有:[圖片上傳失敗...(image-a6132b-1516700004743)][圖片上傳失敗...(image-9cfd50-1516700004743)]
注意: 建立神經(jīng)網(wǎng)絡(luò)的一般方法如下:
- 定義神經(jīng)網(wǎng)絡(luò)的結(jié)構(gòu) ( 輸入單元數(shù)量, 隱藏層單元數(shù)量等等).
- 初始化模型的參數(shù)
- 迭代循環(huán):
- 前向傳播
- 計(jì)算損失函數(shù)
- 后向傳播,計(jì)算梯度
- 更新參數(shù) (梯度下降)
一般習(xí)慣將上述1-3步分別定義成一個(gè)獨(dú)立的函數(shù)闷游,再通過模型函數(shù)將三者融合一起蜓竹。在建立模型之后,迭代獲取到參數(shù)之后储藐,即可對(duì)新數(shù)據(jù)進(jìn)行預(yù)測(cè)。
定義神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu)
給定如下變量:n_x:輸入層神經(jīng)元的數(shù)目
n_h:隱藏層神經(jīng)元的數(shù)目
n_y:輸出層神經(jīng)元的數(shù)目
此處嘶是,我們需要根據(jù)X和Y來確定n_x和n_y钙勃,另外n_h設(shè)置為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)
模型參數(shù)初始化
在定義參數(shù)的時(shí)候聂喇,對(duì)于權(quán)重矩陣我們進(jìn)行隨機(jī)初始化:np.random.randn(a,b) * 0.01 以獲取一個(gè)尺寸為(a辖源,b)的隨機(jī)矩陣。 對(duì)于參數(shù)b希太,我們直接初始化為0克饶,np.zeros((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((n_h,1))*0.01
W2 = np.random.randn(n_y,n_h)*0.01
b2 = np.zeros((n_y,1))*0.01
### 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
循環(huán)
首先是前向傳播。
為前向傳播定義一個(gè)函數(shù)誊辉,在隱藏層的激活函數(shù)是tanh矾湃,在輸出層的激活函數(shù)是sigmoid。利用初始化的參數(shù)計(jì)算Z[1],A[1],Z[2] 和 A[2]堕澄,同時(shí)注意保留值到cache邀跃,因?yàn)樵诤罄m(xù)的后向傳播需要用到。
前向傳播代碼:
# 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)
### 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
代價(jià)函數(shù)
# 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
# Compute the cross-entropy cost
### START CODE HERE ### (≈ 2 lines of code)
logprobs = np.multiply(np.log(A2),Y) + np.multiply(np.log(1-A2),(1-Y))
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
反向傳播
公式如下:[圖片上傳失敗...(image-aa5101-1516700004743)]
- 注意 ? 表示元素之間的乘積蛙紫。
- 在計(jì)算dZ1時(shí)候拍屑,我們需要先計(jì)算 g[1]′(Z[1])。這是由于 g[1](.) is的激活函數(shù)是tanh坑傅,當(dāng)a=g1則g[1]′(z)=1?a2僵驰。為此,我們可以用(1 - np.power(A1, 2))來計(jì)算g[1]′(Z[1])
# 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
"""
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
參數(shù)更新
上述的結(jié)果我們已經(jīng)可以計(jì)算出反向傳播的梯度了,那么我們就可以通過梯度下降法對(duì)參數(shù)進(jìn)行更新: [圖片上傳失敗...(image-ff7944-1516700004743)]其中 α 是學(xué)習(xí)率 θ 則是代表待更新的參數(shù)蒜茴。
選擇好的學(xué)習(xí)率星爪,迭代才會(huì)收斂,否則迭代過程不斷振蕩矮男,呈發(fā)散狀態(tài)移必。
[圖片上傳失敗...(image-b2a3c1-1516700004743)]
# 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
"""
# 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
模型融合
# 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
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
測(cè)試代碼
def nn_model_test_case():
np.random.seed(1)
X_assess = np.random.randn(2, 3)
Y_assess = np.random.randn(1, 3)
return X_assess, Y_assess
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"]))
結(jié)果
W1 = [[-4.18496401 5.33207212]
[-7.53803949 1.20755725]
[-4.19297213 5.32618291]
[ 7.53798193 -1.20759019]]
b1 = [[ 2.32932824]
[ 3.81001626]
[ 2.33008802]
[-3.81011657]]
W2 = [[-6033.82356872 -6008.14295996 -6033.08780035 6008.07953767]]
b2 = [[-52.67923024]]
預(yù)測(cè)
除了訓(xùn)練模型外,我們還需要使用我們的模型來進(jìn)行預(yù)測(cè)毡鉴。
通常崔泵,我們會(huì)設(shè)置一個(gè)閾值,當(dāng)預(yù)測(cè)結(jié)果大于該閾值時(shí)猪瞬,我們認(rèn)為其為1憎瘸,否則為0。0.5是一個(gè)很常用的閾值陈瘦。
# GRADED FUNCTION: predict
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
目前為止幌甘,已經(jīng)實(shí)現(xiàn)了完整的神經(jīng)網(wǎng)絡(luò)模型和預(yù)測(cè)函數(shù),接下來用數(shù)據(jù)集來訓(xùn)練痊项。
# 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))
運(yùn)行結(jié)果:
分類曲線如上圖所示锅风,接下來,使用預(yù)測(cè)函數(shù)計(jì)算一下我們模型的預(yù)測(cè)準(zhǔn)確度:
# 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) + '%')
相比47%的邏輯回歸預(yù)測(cè)率鞍泉,使用含有一個(gè)隱藏層的神經(jīng)網(wǎng)絡(luò)預(yù)測(cè)的準(zhǔn)確度可以達(dá)到90%皱埠。
調(diào)整隱藏層神經(jīng)元數(shù)目觀察結(jié)果
接下來,使用包含不同隱藏層神經(jīng)元的模型來進(jìn)行訓(xùn)練咖驮,以此來觀察神經(jīng)元數(shù)量度模型的影響边器。分別適用包含1,2,3,4,5,20,50個(gè)神經(jīng)元的模型來進(jìn)行訓(xùn)練:
# 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))
輸出結(jié)果:
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 10 hidden units: 90.25 %
Accuracy for 20 hidden units: 90.5 %
對(duì)比上述圖像,可以發(fā)現(xiàn):
1.隱藏層的神經(jīng)元數(shù)量越多托修,則對(duì)訓(xùn)練數(shù)據(jù)集的擬合效果越好忘巧,直到最后出現(xiàn)過擬合。
2.本文中最好的神經(jīng)元數(shù)目是n_h=5睦刃,此時(shí)砚嘴,能夠較好地?cái)M合訓(xùn)練數(shù)據(jù)集,也不會(huì)出現(xiàn)過擬合現(xiàn)象涩拙。
3.對(duì)于n_h過大而產(chǎn)生的過擬合是可以通過正則化來消除的枣宫。