實現邏輯迴歸-神經網路
1、邏輯迴歸與線性迴歸的區別?
線性迴歸
預測得到的是一個數值,而 邏輯迴歸
預測到的數值只有0、1兩個值。 邏輯迴歸
是線上性迴歸的基礎上,加上一個 sigmoid函式
,讓其值位於 0-1
之間,最後獲得的值大於 0.5
判斷為 1
,小於等於 0.5
判斷為 0
二、邏輯迴歸的推導
1、一般公式
y
為標籤值,另一個 y hat
為預測值。
2、向量化
3、啟用函式
引入sigmoid函式(用
表示),使值位於0-1
4、損失函式
損失函式用
表示
因 梯度下降
效果不好,換用 交叉熵損失函式
5、代價函式
代價函式用
表示
展開
6、正向傳播
7、反向傳播
求出
= 3,表示 對 的偏導數
求出
= 6
求出
= 6
對 Sigmod函式
求導
8、反向傳播的意義
修正引數,使 代價函式值
減少, 預測值
接近 實際值
。
舉個例子:
(1) 玩一個猜數遊戲,目標數字為150。
(2) 輸入訓練樣本值: 你第一次猜出一個數字為x = 10
(3) 設定初始權重: 設定一個權重值,比如權重w設為0.5
(4) 正向計算: 進行計算,獲得值wx
(5) 求出代價函式: 出題人說差了多少(說的不是具體數字,而是用0-10表示,10表示差的離譜,1表示非常接近,0表示正確)
(6) 反向傳播或求導: 你通過出題人的結論,去一點點修正權重(增加w或減少w)。
(7) 重複(4)操作,直到無限接近或等於目標數字。
機器學習,就是在訓練中改進、優化,找到最有泛化能力的規則。
三、神經網路實現
1、實現啟用函式Sigmoid
def sigmoid(z): s = 1.0 / (1.0 + np.exp(-z)) return s
2、引數初始化
def initialize_with_zeros(dim): w = np.zeros([dim,1]) b = 0 return w, b
3、前後向傳播
def propagate(w, b, X, Y): m = X.shape[1] A = sigmoid(np.dot(w.T,X) + b) cost = (- 1.0 / m ) * np.sum(Y*np.log(A) + (1-Y)*np.log(1-A)) dw = (1.0 / m) * np.dot(X,(A - Y).T) db = (1.0 / m) * np.sum(A - Y) cost = np.squeeze(cost) grads = {"dw": dw,"db": db} return grads, cost
4、優化器實現
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): costs = [] for i in range(num_iterations): # Cost and gradient calculation grads, cost = propagate(w,b,X,Y) # Retrieve derivatives from grads dw = grads["dw"] db = grads["db"] # update rule w = w - learning_rate * dw b = b - learning_rate * db # Record the costs if i % 100 == 0: costs.append(cost) # Print the cost every 100 training iterations 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
5、預測函式
def predict(w, b, X): m = X.shape[1] Y_prediction = np.zeros((1,m)) w = w.reshape(X.shape[0], 1) # Compute vector "A" predicting the probabilities of a cat being present in the picture A = sigmoid(np.dot(w.T,X)+b) for i in range(A.shape[1]): # Convert probabilities A[0,i] to actual predictions p[0,i] if A[0][i] <= 0.5: Y_prediction[0][i] = 0 else: Y_prediction[0][i] = 1 return Y_prediction
6、程式碼模組整合
def model(X_train, Y_train, X_test, Y_test, num_iterations =2000, learning_rate =0.5, print_cost = False): # initialize parameters with zeros (≈ 1 line of code) w, b = initialize_with_zeros(train_set_x.shape[0]) # Gradient descent (≈ 1 line of code) parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost) # Retrieve parameters w and b from dictionary "parameters" w = parameters["w"] b = parameters["b"] Y_prediction_test = predict(w, b, X_test) Y_prediction_train = predict(w, b, X_train) # Print train/test Errors 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
7、執行程式
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 %
8、更多的分析
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 (hundreds)') legend = plt.legend(loc='upper center', shadow=True) frame = legend.get_frame() frame.set_facecolor('0.90') plt.show()
9、測試圖片
## START CODE HERE ## (PUT YOUR IMAGE NAME) my_image = "my_image.jpg"# change this to the name of your image file ## END CODE HERE ## # We preprocess the image to fit your algorithm. 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 = 0.0, your algorithm predicts a "non-cat" picture.