前言:
文章以Andrew Ng 的 deeplearning.ai 視頻課程為主線,記錄Programming Assignments 的實(shí)現(xiàn)過程。相對(duì)于斯坦福的CS231n課程,Andrew的視頻課程更加簡(jiǎn)單易懂,適合深度學(xué)習(xí)的入門者系統(tǒng)學(xué)習(xí)!
這一部分的作業(yè)主要涉及到Logistic Regression,Logistic Regression 用于Binary Classification二分類的問題(0,1),基于多分類的Softmax也是在Logistic Regression的基礎(chǔ)上改進(jìn)而來,這次Assignment的數(shù)據(jù)集為data.h5,包含train_data和test_data,label分別為cat和non_cat,,首先我們看一下數(shù)據(jù)集,對(duì)數(shù)據(jù)集有一個(gè)直觀的認(rèn)識(shí):
1 Overview of the Problem set
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
index = 25
plt.imshow(train_set_x_orig[index])
print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") +? "' picture.")
程序輸出:y = [1], it's a 'cat' picture.
我們需要對(duì)圖片進(jìn)行預(yù)處理,從而轉(zhuǎn)化為我們需要的shape類型,并且需要normalization從而加速收斂
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[1]
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
print ("train_set_x_flatten shape: " + str(train_set_x_flatten.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x_flatten shape: " + str(test_set_x_flatten.shape))
print ("test_set_y shape: " + str(test_set_y.shape))
print ("sanity check after reshaping: " + str(train_set_x_flatten[0:5,0]))
train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.
2 General Architecture of the learning algorithm
The following figure explains the architecture of the learning algorithm,this algorithm can distinguish cat images from non-cat images:
3 Building the parts of our algorithm
def sigmoid(z):
s = 1./(1+np.exp(-z))
return s
def initialize_with_zeros(dim):
w =np.zeros((dim,1))
b = 0
return w, b
def propagate(w, b, X, Y):
A = sigmoid(np.dot(w.T,X)+b)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
cost =-1/m*(np.sum(Y*np.log(A)+(1-Y)*np.log(1-A)))? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
dw =1/m*np.dot(X,(A-Y).T)
db = 1/m*np.sum(A-Y)
cost = np.squeeze(cost)
grads = {"dw": dw,
"db": db}
return grads, cost
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
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))
params = {"w": w,
"b": b}
grads = {"dw": dw,
"db": db}
return params, grads, costs
def predict(w, b, X):
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
return Y_prediction
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
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}
return d
現(xiàn)在我們可以用model函數(shù)來進(jìn)行訓(xùn)練:
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)
訓(xùn)練結(jié)果如圖所示:
index = 1
plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))
print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[d["Y_prediction_test"][0,index]].decode("utf-8") +? "\" picture.")
我們可以看一下隨著迭代次數(shù)的增加,cost的變化情況
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(d["learning_rate"]))
plt.show()
對(duì)于不同的learning_rate,cost曲線變化明顯:
4 Test with your own image
我們可以用模型訓(xùn)練出來的參數(shù)對(duì)圖片進(jìn)行預(yù)測(cè),判斷是否為貓的圖片
my_image = "my_image.jpg"
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T
my_predicted_image = predict(d["w"], d["b"], my_image)
plt.imshow(image)
print("y = " + str(np.squeeze(my_predicted_image)) + ", your algorithm predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") +? "\" picture.")
預(yù)測(cè)結(jié)果為:
y = 0.0, your algorithm predicts a "non-cat" picture.
最后附上我作業(yè)的得分,表示我的程序沒有問題,如果覺得我的文章對(duì)您有用,請(qǐng)隨意打賞,我將持續(xù)更新Deeplearning.ai的作業(yè)!