吳恩達深度學習課程第一課第二週課程作業

1、作業前環境安裝和工具準備

win系統在cmd命令列輸入pip install jupyter notebook

2、安裝包，前面說過了,這幾個包主要是科學計算和圖片處理用的，具體可以上網搜一下。

``````import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage

3、資料集處理

``train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()``

``````m_train=train_set_x_orig.shape[0]
m_test=test_set_x_orig.shape[0]
num_px=train_set_x_orig[0].shape[0]``````

print (“Number of training examples: m_train = ”
str(m_train))
print (“Number of testing examples: m_test = ” str(m_test))
print (“Height/Width of each image: num_px = ” str(num_px))
print (“Each image is of size: (” str(num_px) “, ” str(num_px) “, 3)”)
print (“train_set_x shape: ” str(train_set_x_orig.shape))
print (“train_set_y shape: ” str(train_set_y.shape))
print (“test_set_x shape: ” str(test_set_x_orig.shape))
print (“test_set_y shape: ” str(test_set_y.shape))

``````Number of training examples: m_train = 209
Number of testing examples: m_test = 50
Height/Width of each image: num_px = 64
Each image is of size: (64, 64, 3)
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)``````

``````train_set_x_flatten=train_set_x_orig.reshape(m_train,num_px**2*3).T
test_set_x_flatten=test_set_x_orig.reshape(m_test,-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_flatten shape: (12288, 209)
train_set_y shape: (1, 209)
test_set_x_flatten shape: (12288, 50)
test_set_y shape: (1, 50)
sanity check after reshaping: [17 31 56 22 33]``````

``````train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.``````

4、函式定義

``````def sigmoid(z):
s=1/(1 np.exp(-z))
return s``````

``````def initialize_with_zeros(dim):
w=np.zeros((dim,1))
b=0
assert(w.shape==(dim,1))
assert(isinstance(b,float) or isinstance(b,int))
return w,b``````

``````def propagate(w,b,X,Y):
m=X.shape[1]
A=sigmoid(np.dot(w.T,X) b)
cost=-np.sum(np.multiply(Y,np.log(A)) np.multiply(1-Y,np.log(1-A)))/m
dw=1/m*np.dot(X,(A-Y).T)
db=1/m*np.sum(A-Y)
assert(dw.shape==w.shape)
assert(db.dtype==float)
cost = np.squeeze(cost)#刪除陣列中為1的那個維度
assert(cost.shape == ())#cost為實數
'db':db}
``````

``````def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
costs=[]
for i in range(num_iterations):
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}
"db": db}

``````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
assert(Y_prediction.shape == (1, m))
return Y_prediction``````

``print ("predictions = "   str(predict(w, b, X)))``

``````def model(X_train,Y_train,X_test,Y_test,num_iterations=2000,learning_rate=0.005, print_cost = False):
w,b=np.zeros((X_train.shape[0],1)),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``````

5、執行模型

``d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)``

``````Cost after iteration 0: 0.693147
Cost after iteration 100: 0.584508
Cost after iteration 200: 0.466949
Cost after iteration 300: 0.376007
Cost after iteration 400: 0.331463
Cost after iteration 500: 0.303273
Cost after iteration 600: 0.279880
Cost after iteration 700: 0.260042
Cost after iteration 800: 0.242941
Cost after iteration 900: 0.228004
Cost after iteration 1000: 0.214820
Cost after iteration 1100: 0.203078
Cost after iteration 1200: 0.192544
Cost after iteration 1300: 0.183033
Cost after iteration 1400: 0.174399
Cost after iteration 1500: 0.166521
Cost after iteration 1600: 0.159305
Cost after iteration 1700: 0.152667
Cost after iteration 1800: 0.146542
Cost after iteration 1900: 0.140872
train accuracy: 99.04306220095694 %
test accuracy: 70.0 %``````

``````index=1
plt.imshow(test_set_x[:,index].reshape((num_px,num_px,3))) #使用imshow必須是RGB影象格式，3通道
print('y= ' str(test_set_y[0,index])  ", you predicted that it is a \"" classes[int(d['Y_prediction_test'][0,index])].decode('utf-8') "\"picture.")``````

``y= 1, you predicted that it is a "cat"picture.``

6、學習率的影響

``````learning_rates=[0.01,0.001,0.0001]
models={}
for i in learning_rates:
print ("learning_rate is: " str(i))
models[str(i)]=model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)
print ('\n'   "-------------------------------------------------------"   '\n')
for i in learning_rates:
plt.plot(np.squeeze(models[str(i)]['costs']),label=str(models[str(i)]["learning_rate"]))
plt.ylabel('cost')
plt.xlabel('iterations')
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.show()``````

7、試一下自己的圖片

``````my_image = "image1219.jpg"
fname = "images/"   my_image