python邏輯迴歸識別貓(持續更新中)

邏輯迴歸

簡單來說, 邏輯迴歸(Logistic Regression)是一種用於解決二分類(0 or 1)問題的機器學習方法,用於估計某種事物的可能性。比如某用戶購買某商品的可能性,某病人患有某種疾病的可能性,以及某廣告被用戶點擊的可能性等。 注意,這裏用的是“可能性”,而非數學上的“概率”,logisitc迴歸的結果並非數學定義中的概率值,不可以直接當做概率值來用。該結果往往用於和其他特徵值加權求和,而非直接相乘。
這次我們採用邏輯迴歸的方法來設計一張圖片判斷是否爲貓的分類問題。
這次邏輯迴歸模型我們採用的是Python進行程序編寫。

邏輯迴歸實現貓的辨別

下面的案列我參照吳恩達的深度學習作業做對應的編寫,可能模型準確度不是很高,希望大家多多指點。

Python環境的配置

在對邏輯迴歸進行貓的辨別時,我們最好建一個jupyter notebook 將每一步都規劃好。
第一步導入相對應的包和數據,對應的數據和文件我待會文後附上鍊接。

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 ##調用自己的一個python腳本中的函數,在當前工作目錄下面
%matplotlib inline #圖片顯示在jupyter notebook 上面

第二步就是開始導入數據,劃分訓練集和測試集,查看數據的規模,以及我們定義一些變量。

# Loading the data (cat/non-cat)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
print(train_set_x_orig.shape)# 查看訓練集測試圖片的規模,64*64*3,三個通道
print(train_set_y.shape)#查看訓練集y的的標籤
print(test_set_x_orig.shape)
print(test_set_y.shape)
print(classes)#查看類別
(209, 64, 64, 3)
(1, 209)
(50, 64, 64, 3)
(1, 50)
[b'non-cat' b'cat']

如果有興趣的話,大家可以自己在自己的電腦上試着查看一下你導入的圖片。

# Example of a picture
index = 0 # 查看圖片,每張圖片對應一個索引,但不要超出範圍(這個取決與我們的訓練集和測試集大小)
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.")#打印圖片的編號以及打印它的標籤(是不是一隻貓)

這個是我運行完後的一個結果,有興趣大家可以在自己電腦上面進行測試。也可以改變index值,查看別的圖片。
在這裏插入圖片描述
如果想具體瞭解和了解數據屬性,可以看下面的操作。

m_train = train_set_x_orig.shape[0]#訓練集圖片的數量
m_test = test_set_x_orig.shape[0]#測試集圖片數量
num_px = train_set_x_orig.shape[2]#圖片像素大小矩陣

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)")#每一張圖片三個通道對應RGB三種顏色,圖片的矩陣表示,對應三個顏色強度矩陣
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)

接下來就是我們需要重點關注的一步,如何將圖片數據轉爲向量表示,這裏和大家普及一下圖片一般是RGB色彩和其他色彩,不過我們這裏的圖片數據是RBG格式,rgb通俗點就是三原色每個顏色對應一個矩陣,矩陣中的每一個元素都是像素點,三個顏色矩陣的像素點組合就成爲一張圖片。然後我們將三個矩陣的元素合併到一個向量來表示。

# Reshape the training and test examples
#將圖片轉成向量
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0],-1).T#64*64*3,一共209張圖片
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0],-1).T#209個訓練圖片標籤
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]

單純這樣的處理還不夠,因爲像素點是0-255,數字比較大,不便於後面處理我麼對數據進行一定的縮放比例,將像素點範圍調控到0-1之間。

train_set_x = train_set_x_flatten/255.#像素的值在0-255之間,縮放像素0-1之間
test_set_x = test_set_x_flatten/255.

接下來就是構建神經網絡模型,下面這個我截取吳恩達的課程給出的模型以及涉及到的公式。

Mathematical expression of the algorithm:

For one example x(i)x^{(i)}:
(1)z(i)=wTx(i)+bz^{(i)} = w^T x^{(i)} + b \tag{1}
(2)y^(i)=a(i)=sigmoid(z(i))\hat{y}^{(i)} = a^{(i)} = sigmoid(z^{(i)})\tag{2}
(3)L(a(i),y(i))=y(i)log(a(i))(1y(i))log(1a(i)) \mathcal{L}(a^{(i)}, y^{(i)}) = - y^{(i)} \log(a^{(i)}) - (1-y^{(i)} ) \log(1-a^{(i)})\tag{3}

The cost is then computed by summing over all training examples:
(6)J=1mi=1mL(a(i),y(i)) J = \frac{1}{m} \sum_{i=1}^m \mathcal{L}(a^{(i)}, y^{(i)})\tag{6}

但模型大致思路如下:

定義模型結構(例如輸入特性的數量)

初始化模型的參數

計算當前損失(正向傳播)

計算當前梯度(向後傳播)

更新參數(梯度下降)

關於邏輯迴歸模型的算法講解我會在下一篇博客中詳解講解。下面我們開始用python構建邏輯迴歸模型。
1.下面我們構建模型中的一個重要函數激活函數。

# GRADED FUNCTION: sigmoid
def sigmoid(x):
    """
    計算sigmoid函數
    :param x: 任意大小的標量或者numpy數組
    :return: sigmoid(x)
    """
    s = 1 / (1 + np.exp(-x))
    return s

如果你想看看你的激活函數是否達到你的要求,可以調用函數
在這裏插入圖片描述

初始化模型的參數

# 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)#標量
    """
    w = np.zeros((dim,1))#初始化權重值
    b = 0
    assert(w.shape == (dim, 1))#判斷權重矩陣是否爲你想要的形式
    assert(isinstance(b, float) or isinstance(b, int))
    
    return w, b

定義計算損失值函數

通過“正向”和“反向”傳播,計算損失值。
正向傳播:
獲取 X
計算
計算損失函數:
計算dw和db使用到的兩條公式

# 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) 權重,一個numpy數組大小(num_px * num_px * 3,1)
    b -- bias, a scalar                              偏差,一個標量
    X -- data of size (num_px * num_px * 3, number of examples)   數據大小(num_px * num_px * 3,例子數量)
    Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples) 真正的“標籤”向量(包含0如果非貓,1如果貓)的大小(1,例子數量)
    
    Return:
    cost -- negative log-likelihood cost for logistic regression      Logistic迴歸的負對數似然成本。
    dw -- gradient of the loss with respect to w, thus same shape as w  關於w的損失梯度,與w相同。

    db -- gradient of the loss with respect to b, thus same shape as b  關於b的損失梯度,與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)
#前向傳播
    A = sigmoid(np.dot(w.T,X)+b)          
    cost = -1/m*np.sum(Y*np.log(A)+(1-Y)*np.log(1-A))   
    ### END CODE HERE ###
    
    # BACKWARD PROPAGATION (TO FIND GRAD)
#反向傳播
    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#返回梯度和代價

大家可以測試一下上面的函數,看看是否達到你的要求:
在這裏插入圖片描述
當我們進行到這裏時候,大致的邏輯迴歸的模型大致搭建好了,接下來也就是我們要考慮優化函數的問題了。

# 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

下面是我測試的優化函數結果
在這裏插入圖片描述
當我們進行到這裏的時候,邏輯迴歸的主體函數基本搭建好了,但是我們訓練的最終目的是爲了預測結果,而不是單純爲了在訓練集上面達到想要的結果。所以接下來我們要開始編寫我們自己的預測函數。這個是借用吳恩達老師的預測函數。

# 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

這個是一個測試樣例
在這裏插入圖片描述
上述將整個邏輯迴歸的模型拆成了一個個的函數,便於大家理解和學習,後面我們需要將所有的函數整合在一起,這樣纔是完整的模型。

# 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.
    """

    
    # initialize parameters with zeros 
    w, b = initialize_with_zeros(X_train.shape[0])

    # Gradient descent
    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 
    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

到這裏,整個模型也就成型了,但是我們想知道我們的模型對辨別貓有多高的準確率,我們就可以利用上面的數據開始跑我們的模型了。
在這裏插入圖片描述
可能直接看這個覺得不是很直觀,我們可以直接索引圖片一個個的進行看

# Example of a picture that was wrongly classified.
index = 7#通過改變索引,查看圖片測試結果
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.")

這是的測試結果
在這裏插入圖片描述
當我們進性索引時發現有一些圖片被模型判別錯誤了,這個一個是我們數據量不是很大的原因,還有我們的參數調節問題。這個我後面會和大家講解,代碼和文件我會後期附在這個博客後面,可以給大家參考,這個代碼我也是在吳恩達老師的作業代碼進行補充的。
代碼參考鏈接鏈接:https://pan.baidu.com/s/1ZqXWD5rDSl-Y52W4dA0k9A
提取碼:xmxl

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章