前言:
文章以Andrew Ng 的 deeplearning.ai 視頻課程為主線,記錄Programming Assignments 的實(shí)現(xiàn)過(guò)程。相對(duì)于斯坦福的CS231n課程,Andrew的視頻課程更加簡(jiǎn)單易懂,適合深度學(xué)習(xí)的入門(mén)者系統(tǒng)學(xué)習(xí)!
這次作業(yè)的主題是使用一個(gè)隱藏層區(qū)分平面數(shù)據(jù),涉及到兩種類(lèi)型的激活函數(shù)分別為tanh和sigmoid,使用gradient descent算法對(duì)參數(shù)進(jìn)行更新,個(gè)人覺(jué)得這次作業(yè)的最大亮點(diǎn)是劃分平面數(shù)據(jù),讓我們認(rèn)識(shí)到神經(jīng)網(wǎng)絡(luò)不僅僅對(duì)圖片有很好的performance,對(duì)其他類(lèi)型的數(shù)據(jù)也是可以嘗試這種方法進(jìn)行classification
1.1 Dataset
let's get the dataset,the code will load a "flower" 2-class dataset into variables X and Y:
X, Y = load_planar_dataset()
plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);
shape_X = X.shape
shape_Y = Y.shape
m = X.shape[1]? # training set size
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))
1.2 Simple Logistic Regression
Before building a full neural network, lets first see how logistic regression performs on this problem. You can use sklearn's built-in functions to do that. Run the code below to train a logistic regression classifier on the dataset.
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, Y.T)
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")
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
1.3 Neural Network model
Logistic Regression 在 flower dataset 上的表現(xiàn)不是很好,所以我們嘗試使用帶有一個(gè)隱藏層的神經(jīng)網(wǎng)絡(luò)來(lái)訓(xùn)練我們的數(shù)據(jù)集
這里是我們的模型和一些數(shù)學(xué)推到:
下面是實(shí)現(xiàn)代碼:
def layer_sizes(X, Y):
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)
def initialize_parameters(n_x, n_h, n_y):
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
def forward_propagation(X, parameters):
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
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
def compute_cost(A2, Y, parameters):
m = Y.shape[1] # number of example
logprobs = Y*np.log(A2)+(1-Y)*np.log(1-A2)
cost = -1/m*np.sum(logprobs)
cost = np.squeeze(cost)
assert(isinstance(cost, float))
return cost
這是梯度下降的數(shù)學(xué)推導(dǎo):
def backward_propagation(parameters, cache, X, Y):
m = X.shape[1]
W1 = parameters["W1"]
W2 = parameters["W2"]
A1 = cache["A1"]
A2 = cache["A2"]
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-A1*A1)
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
def update_parameters(parameters, grads, learning_rate = 1.2):
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
dW1 = grads["dW1"]
db1 = grads["db1"]
dW2 = grads["dW2"]
db2 = grads["db2"]
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
def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):
np.random.seed(3)
n_x = layer_sizes(X, Y)[0]
n_y = layer_sizes(X, Y)[2]
parameters = initialize_parameters(n_x, n_h, n_y)
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
for i in range(0, num_iterations):
A2, cache = forward_propagation(X, parameters)
cost = compute_cost(A2, Y, parameters)
grads = backward_propagation(parameters, cache, X, Y)
parameters = update_parameters(parameters, grads)
if print_cost and i % 1000 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
return parameters
def predict(parameters, X):
A2, cache = forward_propagation(X, parameters)
predictions = A2>0.5
return predictions
我們調(diào)用定義好的模型進(jìn)行訓(xùn)練:
parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
plt.title("Decision Boundary for hidden layer size " + str(4))
訓(xùn)練結(jié)果如下:
對(duì)X的數(shù)據(jù)進(jìn)行預(yù)測(cè):
predictions = predict(parameters, X)
print ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%')
現(xiàn)在我們對(duì)隱藏層的神經(jīng)元數(shù)量進(jìn)行tune,神經(jīng)元數(shù)量分別為1,2,3,4,5,20,50,代碼如下:
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é)果為:
從實(shí)驗(yàn)結(jié)果可以看出當(dāng)神經(jīng)元的數(shù)量達(dá)到3個(gè)以上的時(shí)候,神經(jīng)網(wǎng)絡(luò)對(duì)flower的數(shù)據(jù)集擬合程度較好。最后附上我作業(yè)的得分,表示我的程序沒(méi)有問(wèn)題,如果覺(jué)得我的文章對(duì)您有用,請(qǐng)隨意打賞,我將持續(xù)更新Deeplearning.ai的作業(yè)!