概述
本文主要內(nèi)容:如何利用Python的來實(shí)現(xiàn)Logistic函數(shù)。包括:初始化、計(jì)算代價(jià)函數(shù)和梯度、使用梯度下降算法進(jìn)行優(yōu)化等并把他們整合成為一個函數(shù)。本文將通過訓(xùn)練來判斷一副圖像是否為貓。
準(zhǔn)備
在這個過程中,我們將會用到如下庫:
numpy:Python科學(xué)計(jì)算中最重要的庫
h5py:Python與H5文件交互的庫
mathplotlib:Python畫圖的庫
PIL:Python圖像相關(guān)的庫
scipy:Python科學(xué)計(jì)算相關(guān)的庫
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset
%matplotlib inline
數(shù)據(jù)集
在訓(xùn)練之前,首先需要讀取數(shù)據(jù),讀取數(shù)據(jù)的代碼如下:
def load_dataset():
"""
# 加載數(shù)據(jù)集
"""
train_dataset = h5py.File('E:/python/week2/train_catvnoncat.h5', "r") #讀取H5文件
train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features
train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels
test_dataset = h5py.File('E:/python/week2/test_catvnoncat.h5', "r")
test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features
test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels
classes = np.array(test_dataset["list_classes"][:]) # the list of classes
train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0])) #對訓(xùn)練集和測試集標(biāo)簽進(jìn)行reshape
test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
數(shù)據(jù)說明:
對于訓(xùn)練集的標(biāo)簽而言,對于貓,標(biāo)記為1,否則標(biāo)記為0。每一個圖像的維度都是(num_px, num_px, 3),其中,長寬相同,3表示是RGB圖像。train_set_x_orig和test_set_x_orig中,包含_orig是由于我們稍候需要對圖像進(jìn)行預(yù)處理,預(yù)處理后的變量將會命名為train_set_x和train_set_y。train_set_x_orig中的每一個元素對于這一副圖像,我們可以用如下代碼將圖像顯示出來:
# Example of a picture
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.")

接下來,根據(jù)圖像集來計(jì)算出訓(xùn)練集的大小、測試集的大小以及圖片的大?。?/p>
### START CODE HERE ### (≈ 3 lines of code)
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[1]
### END CODE HERE ###
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))
Ps:其中X_flatten = X.reshape(X.shape[0], -1).T可以將一個維度為(a,b,c,d)的矩陣轉(zhuǎn)換為一個維度為(b??c??d, a)的矩陣。
接下來,對圖像值進(jìn)行歸一化。
由于圖像的原始值在0到255之間,最簡單的方式是直接除以255即可。
train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.
logistics介紹

對于每個訓(xùn)練樣本x,其誤差函數(shù)的計(jì)算方式如下:

而整體的代價(jià)函數(shù)計(jì)算如下:

實(shí)現(xiàn)
接下來,我們將按照如下步驟來實(shí)現(xiàn)Logistic:
1. 定義模型結(jié)構(gòu)
2. 初始化模型參數(shù)
3. 循環(huán)
3.1 前向傳播
3.2 反向傳遞
3.3 更新參數(shù)
4. 整合成為一個完整的模型
Step1:實(shí)現(xiàn)sigmod函數(shù)
# GRADED FUNCTION: sigmoid
def sigmoid(z):
"""
Compute the sigmoid of z
Arguments:
z -- A scalar or numpy array of any size.
Return:
s -- sigmoid(z)
"""
### START CODE HERE ### (≈ 1 line of code)
s = 1/(1+np.exp(-(z)))
### END CODE HERE ###
return s
Step2:初始化參數(shù)
# GRADED FUNCTION: initialize_with_zeros
def initialize_with_zeros(dim):
"""
This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.
Argument:
dim -- size of the w vector we want (or number of parameters in this case)
Returns:
w -- initialized vector of shape (dim, 1)
b -- initialized scalar (corresponds to the bias)
"""
### START CODE HERE ### (≈ 1 line of code)
w = np.zeros((dim,1))
b = 0
### END CODE HERE ###
assert(w.shape == (dim, 1))
assert(isinstance(b, float) or isinstance(b, int))
return w, b
Step3:前向傳播與反向傳播
計(jì)算公式如下:


# GRADED FUNCTION: propagate
def propagate(w, b, X, Y):
"""
Implement the cost function and its gradient for the propagation explained above
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (num_px * num_px * 3, number of examples)
Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)
Return:
cost -- negative log-likelihood cost for logistic regression
dw -- gradient of the loss with respect to w, thus same shape as w
db -- gradient of the loss with respect to b, thus same shape as b
Tips:
- Write your code step by step for the propagation. np.log(), np.dot()
"""
m = X.shape[1]
# FORWARD PROPAGATION (FROM X TO COST)
### START CODE HERE ### (≈ 2 lines of code)
A = sigmoid(np.dot(w.T,X)+b) # compute activation
cost = -1.0/m*(np.sum(Y*np.log(A)+(1-Y)*np.log(1-A))) # compute cost
### END CODE HERE ###
# BACKWARD PROPAGATION (TO FIND GRAD)
### START CODE HERE ### (≈ 2 lines of code)
dw = 1/m*(np.dot(X,(A-Y).T))
db = 1/m*(np.sum(A-Y))
### END CODE HERE ###
assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)
assert(cost.shape == ())
grads = {"dw": dw,
"db": db}
return grads, cost
Step4:更新參數(shù)
更新參數(shù)的公式如下:

完整代碼如下:
# GRADED FUNCTION: optimize
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
"""
This function optimizes w and b by running a gradient descent algorithm
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of shape (num_px * num_px * 3, number of examples)
Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)
num_iterations -- number of iterations of the optimization loop
learning_rate -- learning rate of the gradient descent update rule
print_cost -- True to print the loss every 100 steps
Returns:
params -- dictionary containing the weights w and bias b
grads -- dictionary containing the gradients of the weights and bias with respect to the cost function
costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve.
Tips:
You basically need to write down two steps and iterate through them:
1) Calculate the cost and the gradient for the current parameters. Use propagate().
2) Update the parameters using gradient descent rule for w and b.
"""
costs = []
for i in range(num_iterations):
# Cost and gradient calculation (≈ 1-4 lines of code)
### START CODE HERE ###
grads, cost = propagate(w,b,X,Y)
### END CODE HERE ###
# Retrieve derivatives from grads
dw = grads["dw"]
db = grads["db"]
# update rule (≈ 2 lines of code)
### START CODE HERE ###
w = w - learning_rate*dw
b = b - learning_rate*db
### END CODE HERE ###
# Record the costs
if i % 100 == 0:
costs.append(cost)
# Print the cost every 100 training examples
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
Step5:利用訓(xùn)練好的模型對測試集進(jìn)行預(yù)測:
計(jì)算公式如下:

當(dāng)輸入大于0.5時,我們認(rèn)為其預(yù)測認(rèn)為結(jié)果是貓,否則不是貓。
# GRADED FUNCTION: predict
def predict(w, b, X):
'''
Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (num_px * num_px * 3, number of examples)
Returns:
Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in 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
### START CODE HERE ### (≈ 1 line of code)
A = sigmoid(np.dot(w.T,X)+b)
### END CODE HERE ###
for i in range(A.shape[1]):
# Convert probabilities A[0,i] to actual predictions p[0,i]
### START CODE HERE ### (≈ 4 lines of code)
if(A[0][i]<=0.5):
Y_prediction[0][i] = 0
else:
Y_prediction[0][i] = 1
### END CODE HERE ###
assert(Y_prediction.shape == (1, m))
return Y_prediction
Step5:將以上功能整合到一個模型中:
# GRADED FUNCTION: model
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
"""
Builds the logistic regression model by calling the function you've implemented previously
Arguments:
X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)
Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train)
X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test)
Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test)
num_iterations -- hyperparameter representing the number of iterations to optimize the parameters
learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize()
print_cost -- Set to true to print the cost every 100 iterations
Returns:
d -- dictionary containing information about the model.
"""
### START CODE HERE ###
# initialize parameters with zeros (≈ 1 line of code)
w, b = initialize_with_zeros(X_train.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"]
# Predict test/train set examples (≈ 2 lines of code)
Y_prediction_test = predict(w,b,X_test)
Y_prediction_train = predict(w,b,X_train)
### END CODE HERE ###
# 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
測試一下該模型吧:
# Example of a picture that was wrongly classified.
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[int(d["Y_prediction_test"][0,index])].decode("utf-8") + "\" picture.")

此時觀察打印結(jié)果,測試準(zhǔn)確率已經(jīng)可以達(dá)到70.0%。
而對于訓(xùn)練集,其準(zhǔn)確性達(dá)到了99%。這表明了模型有著一定的過擬合。