吳恩達老師的公開課,簡單神經網路的作業總結
定義四個變數
train_set_x shape: (209, 64, 64, 3)
train_set_y shape: (1, 209)
test_set_x shape: (50, 64, 64, 3)
test_set_y shape: (1, 50)
分別為訓練集的X,Y,測試集的X,Y。
這裡有一點需要注意,作業中直接匯入的檔案train_catvnoncat.h5和test_catvnoncat.h5兩個檔案,如果後面需要訓練自己的資料,需要建立資料集
//////////////////////////////////////////
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0],-1).T
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0],-1).T
建立了兩個為(64×63×3,209)和(64×64×3,50)這樣的形式,作為兩個新的變數
為什麼上面的語句可以實現這一點,需要繼續學習
////////////////////////////////////////
初始化定義w,b,其中w為(m,1)的形式,其中m為輸入的列向量的維度
函式命名為initialize_with_zeros(dim)
////////////////////////////////////////
進行正向傳播和損失函式的計算
m = X.shape[1]
A = sigmoid(np.dot(w.T,X)+b)
cost = -np.sum((np.dot(Y,np.log(A).T)+np.dot((1-Y),np.log(1-A).T)))/m
dw = np.dot(X,(A-Y).T)/m
db = np.sum(A-Y)/m
上面為計算公式,下面的為宣告和一個計算,不是很懂
assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)
assert(cost.shape == ())
在寫程式時出現了一個問題:dw = 1/m×np.dot(X,(A-Y).T)執行一直為0,不是很懂,但是需要注意
函式命名為propagate(w, b, X, Y)
///////////////////////////////////////
反響傳播計算,利用學習率計算w,b的下次迭代的值
costs = []
for i in range(num_iterations):
grads, cost = propagate(w, b, X, Y)
dw = grads["dw"]//這裡用來做什麼,不是很懂
db = grads["db"]
w = w - learning_rate*dw
b = b - learning_rate*db
if i % 100 == 0:
costs.append(cost)
if print_cost and i % 100 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
函式命名為optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False)
////////////////////////////////////
對結果進行預測
m = X.shape[1]
Y_prediction = np.zeros((1,m))
w = w.reshape(X.shape[0], 1)
A = sigmoid(np.dot(w.T,X)+b)
for i in range(A.shape[1]):
if A[0,i]>=0.5:
Y_prediction[0,i] = 1
else:
Y_prediction[0,i] = 0
assert(Y_prediction.shape == (1, m))
函式命名為predict(w, b, X)
///////////////////////////////
函式命名完成,需要進行訓練,先建立model,然後訓練資料集
w, b = initialize_with_zeros(X_train.shape[0])
parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
w = parameters["w"]
b = parameters["b"]
Y_prediction_test = predict(w, b, X_test)
Y_prediction_train = predict(w, b, X_train)
print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))
d = {"costs": costs,
"Y_prediction_test": Y_prediction_test,
"Y_prediction_train" : Y_prediction_train,
"w" : w,
"b" : b,
"learning_rate" : learning_rate,
"num_iterations": num_iterations}
上面的語句顯示最終的正確率,如何計算得到的,還不是很懂,python接觸時間太短,需要了解
函式命名為model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False)
/////////////////////////////
如果要訓練深度學習,網路深度,模型設計,還有資料集的製作,這些都需要仔細學習一下