深度神經(jīng)網(wǎng)絡(luò)的圖像分類應(yīng)用

前言

作業(yè)一中一步步構(gòu)建了一個神經(jīng)網(wǎng)絡(luò),本部分作業(yè)將會利用作業(yè)一中的知識構(gòu)建一個神經(jīng)網(wǎng)絡(luò)圖片分類器。這個圖片分類器通過訓(xùn)練可以識別出圖片中的具體內(nèi)容是否是貓。

1. 導(dǎo)入相關(guān)包

首先,還是導(dǎo)入搭建神經(jīng)網(wǎng)絡(luò)分類器所需要的python包,并對整個程序做一些基本的設(shè)置,具體代碼如下所示:


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


%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # 設(shè)置圖片默認(rèn)顯示大小
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

%load_ext autoreload
%autoreload 2
# 設(shè)置隨機(jī)種子
np.random.seed(1)

2. 數(shù)據(jù)集

神經(jīng)網(wǎng)絡(luò)所用到的數(shù)據(jù)集主要分為訓(xùn)練集和測試集,都是以.h5文件存儲的,處理此類文件用到的python庫是h5py庫。對于訓(xùn)練集和測試集而言,輸出數(shù)據(jù)都有一個標(biāo)簽,要么是0(表示該圖片內(nèi)容不是貓),要么是1(表示該圖片內(nèi)容內(nèi)容是貓),數(shù)據(jù)集的特征都是(num_px,num_px,3)形式的矩陣,其中,3代表的是RGB3通道。加載數(shù)據(jù)集的代碼如下所示:


def load_data():
    train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
    train_set_x_orig = np.array(train_dataset["train_set_x"][:]) #訓(xùn)練集的特征
    train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # 訓(xùn)練集輸出的標(biāo)簽

    test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r")
    test_set_x_orig = np.array(test_dataset["test_set_x"][:]) #測試集的輸入特征
    test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # 測試集的輸出標(biāo)簽

    classes = np.array(test_dataset["list_classes"][:]) # 類別列表
    
    train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
    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_x_orig, train_y, test_x_orig, test_y, classes = load_data()

隨便找一張數(shù)據(jù)集中的數(shù)據(jù),顯示結(jié)果如下所示:


index = 7
plt.imshow(train_x_orig[index])
print ("y = " + str(train_y[0,index]) + ". It's a " + classes[train_y[0,index]].decode("utf-8") +  " picture.")

為了確認(rèn)數(shù)據(jù)集的形狀并且為了方便神經(jīng)網(wǎng)絡(luò)的搭建和后續(xù)的運(yùn)算,需要對數(shù)據(jù)集的形狀和大小進(jìn)行顯示,具體代碼如下所示;

 m_train = train_x_orig.shape[0]  # 訓(xùn)練集的樣本大小
num_px = train_x_orig.shape[1]  #樣本的像素
m_test = test_x_orig.shape[0] #測試集的樣本大小

print ("Number of training examples: " + str(m_train))
print ("Number of testing examples: " + str(m_test))
print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")
print ("train_x_orig shape: " + str(train_x_orig.shape))
print ("train_y shape: " + str(train_y.shape))
print ("test_x_orig shape: " + str(test_x_orig.shape))
print ("test_y shape: " + str(test_y.shape))

最后,輸出結(jié)果如下所示:


單個樣本的數(shù)據(jù)集的形狀為(64,64,3),表示一個寬和高都是64像素且為3通道的圖像,在神經(jīng)網(wǎng)絡(luò)訓(xùn)練之前,需要對上述數(shù)據(jù)集做出一些改變,即單個樣本的矩陣轉(zhuǎn)化為一個列向量,具體過程可以由下圖表示:


除了將其轉(zhuǎn)化一個向量之外,還需要將其標(biāo)準(zhǔn)化,確保每一個值都是在之間,標(biāo)準(zhǔn)化的過程可以通過將每一個像素除以255得到,具體的實(shí)現(xiàn)代碼如下所示:

# 重新改變訓(xùn)練集和測試集的大小
train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T   # The "-1" makes reshape flatten the remaining dimensions
test_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T

# 標(biāo)準(zhǔn)化數(shù)據(jù)集
train_x = train_x_flatten/255.
test_x = test_x_flatten/255.

print ("train_x's shape: " + str(train_x.shape))  #輸出:(12288,209)
print ("test_x's shape: " + str(test_x.shape))  #輸出: (12288,50)

神經(jīng)網(wǎng)絡(luò)模型的結(jié)構(gòu)

數(shù)據(jù)預(yù)處理之后,就可以搭建神經(jīng)網(wǎng)絡(luò)的模型了,對于神經(jīng)網(wǎng)絡(luò)模型的搭建,有以下的選擇:

  • 搭建一個2層的神經(jīng)網(wǎng)絡(luò)模型
  • 搭建一個L層的神經(jīng)網(wǎng)絡(luò)模型

可以通過搭建不同結(jié)構(gòu)的神經(jīng)網(wǎng)絡(luò)模型來比較哪種結(jié)構(gòu)的神經(jīng)網(wǎng)絡(luò)模型擁有更好的性能。

3.1 兩層的神經(jīng)網(wǎng)絡(luò)模型

對于兩層的神經(jīng)網(wǎng)絡(luò)模型的結(jié)構(gòu)可以由下圖所示:

整個神經(jīng)網(wǎng)絡(luò)的結(jié)構(gòu)可以總結(jié)為INPUT->LINEAR->RELU->LINEAR->SIGMOID->OUTPUT
輸入特征是(12288,1)的矩陣,對應(yīng)的權(quán)重參數(shù)W^{[1]}(12288,12288)的矩陣,而權(quán)重參數(shù)W^{[2]}(1,12288)的矩陣。

3.2 L層的神經(jīng)網(wǎng)絡(luò)模型

L層的神經(jīng)網(wǎng)絡(luò)模型的結(jié)構(gòu)可以由以下圖形表示:

L層神經(jīng)網(wǎng)絡(luò)的結(jié)構(gòu)可以總結(jié)為INPUT->[LINEAR->RELU]×(L-1)->LINEAE->SGMOID

L層神經(jīng)網(wǎng)絡(luò)的更詳細(xì)的解釋可以參考一步步構(gòu)建了一個神經(jīng)網(wǎng)絡(luò).

3.3 總體實(shí)現(xiàn)方法

以上結(jié)構(gòu)的神經(jīng)網(wǎng)絡(luò)的總體實(shí)現(xiàn)方法可以總結(jié)為以下幾個步驟,具體如下:

  • 初始化權(quán)重參數(shù)/定義超參數(shù)
  • 經(jīng)過多次迭代:
    • 前向傳播
    • 利用損失函數(shù)計(jì)算損失
    • 反向傳播
    • 利用反向傳播和梯度下降更新參數(shù)
  • 用訓(xùn)練后得到的參數(shù)預(yù)測輸出

4. 兩層神經(jīng)網(wǎng)絡(luò)模型的實(shí)現(xiàn)

兩層神經(jīng)網(wǎng)絡(luò)的具體實(shí)現(xiàn)細(xì)節(jié)已經(jīng)有過介紹,故以下直接給出實(shí)現(xiàn)代碼。

4.1 定義神經(jīng)網(wǎng)絡(luò)的結(jié)構(gòu)

首先,定義神經(jīng)網(wǎng)絡(luò)模型的結(jié)構(gòu),具體代碼如下所示:


n_x = 12288     # num_px * num_px * 3
n_h = 7
n_y = 1
layers_dims = (n_x, n_h, n_y)
4.2 兩層神經(jīng)網(wǎng)絡(luò)模型的參數(shù)初始化
#初始化權(quán)重參數(shù)
def initialize_parameters(n_x, n_h, n_y):
     np.random.seed(1)
    
    W1 = np.random.randn(n_h, n_x)*0.01
    b1 = np.zeros((n_h, 1))
    W2 = np.random.randn(n_y, n_h)*0.01
    b2 = np.zeros((n_y, 1))
    
    assert(W1.shape == (n_h, n_x))
    assert(b1.shape == (n_h, 1))
    assert(W2.shape == (n_y, n_h))
    assert(b2.shape == (n_y, 1))
    
    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}
    
    return parameters     

4.3 前向激活函數(shù)的計(jì)算

def linear_activation_forward(A_prev, W, b, activation):

    if activation == "sigmoid":
    
        Z, linear_cache = linear_forward(A_prev, W, b)
        A, activation_cache = sigmoid(Z)
    
    elif activation == "relu":
       
        Z, linear_cache = linear_forward(A_prev, W, b)
        A, activation_cache = relu(Z)
    
    assert (A.shape == (W.shape[0], A_prev.shape[1]))
    cache = (linear_cache, activation_cache)

    return A, cache
4.4 損失函數(shù)的計(jì)算

def compute_cost(AL, Y):
  
    m = Y.shape[1]
   cost = (1./m) * (-np.dot(Y,np.log(AL).T) - np.dot(1-Y, np.log(1-AL).T))
    
    cost = np.squeeze(cost) 
    assert(cost.shape == ())
    
    return cost
4.5 反向傳播函數(shù)的計(jì)算

def linear_activation_backward(dA, cache, activation):
 
    linear_cache, activation_cache = cache
    
    if activation == "relu":
        dZ = relu_backward(dA, activation_cache)
        dA_prev, dW, db = linear_backward(dZ, linear_cache)
        
    elif activation == "sigmoid":
        dZ = sigmoid_backward(dA, activation_cache)
        dA_prev, dW, db = linear_backward(dZ, linear_cache)
    
    return dA_prev, dW, db

4.6 參數(shù)的更新
def update_parameters(parameters, grads, learning_rate):

    L = len(parameters) // 2 # 神經(jīng)網(wǎng)絡(luò)的層數(shù)
    
    for l in range(L):
        parameters["W" + str(l+1)] = parameters["W" + str(l+1)] - learning_rate * grads["dW" + str(l+1)]
        parameters["b" + str(l+1)] = parameters["b" + str(l+1)] - learning_rate * grads["db" + str(l+1)]
        
    return parameters
4.7 兩層神經(jīng)網(wǎng)絡(luò)模型的總體實(shí)現(xiàn)

根據(jù)以上代碼,神經(jīng)網(wǎng)絡(luò)模型的總體實(shí)現(xiàn)代碼,如下所示;

def two_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):

    np.random.seed(1)
    grads = {}
    costs = []                             
    m = X.shape[1]                      
    (n_x, n_h, n_y) = layers_dims
# 初始化權(quán)重參數(shù)
    parameters = initialize_parameters(n_x,n_h,n_y)
  
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    

多次迭代
    for i in range(0, num_iterations):

  前向傳播的實(shí)現(xiàn)
        
        A1, cache1 = linear_activation_forward(X,W1,b1,'relu')
        A2, cache2 = linear_activation_forward(A1,W2,b2,'sigmoid')
   # 損失函數(shù)計(jì)算
        cost = compute_cost(A2,Y)
  
 # 反向傳播的第一步計(jì)算公式
        dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))
        #反向傳播的計(jì)算
        dA1, dW2, db2 = linear_activation_backward(dA2,cache2,'sigmoid')
        dA0, dW1, db1 = linear_activation_backward(dA1,cache1,'relu')
      
        grads['dW1'] = dW1
        grads['db1'] = db1
        grads['dW2'] = dW2
        grads['db2'] = db2
        
#參數(shù)更新
        parameters = update_parameters(parameters,grads,learning_rate)
  
        W1 = parameters["W1"]
        b1 = parameters["b1"]
        W2 = parameters["W2"]
        b2 = parameters["b2"]
        

        if print_cost and i % 100 == 0:
            print("Cost after iteration {}: {}".format(i, np.squeeze(cost)))
        if print_cost and i % 100 == 0:
            costs.append(cost)
       
# 繪制損失函數(shù)圖形
    plt.plot(np.squeeze(costs))
    plt.ylabel('cost')
    plt.xlabel('iterations (per tens)')
    plt.title("Learning rate =" + str(learning_rate))
    plt.show()
    
    return parameters

經(jīng)過多次迭代之后,可以看到損失已經(jīng)下降到一個非常小的值。


4.8 做出預(yù)測

有了以上實(shí)現(xiàn),得到了能夠使損失函數(shù)最小化的參數(shù),利用此參數(shù)和神經(jīng)網(wǎng)絡(luò)的前向傳播函數(shù)做出預(yù)測如下所示;

def predict(X, y, parameters):
   
    m = X.shape[1]
    n = len(parameters) // 2 # number of layers in the neural network
    p = np.zeros((1,m))
    

    probas, caches = L_model_forward(X, parameters)
    for i in range(0, probas.shape[1]):
        if probas[0,i] > 0.5:
            p[0,i] = 1
        else:
            p[0,i] = 0
    
    print("Accuracy: "  + str(np.sum((p == y)/m)))
        
    return p

分別對訓(xùn)練集和測試集做出預(yù)測,精確度結(jié)果如下所示:
訓(xùn)練集預(yù)測精度



測試集預(yù)測精度


5 L層神經(jīng)網(wǎng)絡(luò)模型的實(shí)現(xiàn)

L層神經(jīng)網(wǎng)絡(luò)模型的實(shí)現(xiàn)已經(jīng)在一步步實(shí)現(xiàn)一個神經(jīng)網(wǎng)絡(luò)中有過詳細(xì)介紹了,一些多層神經(jīng)網(wǎng)絡(luò)分類器的主要的代碼實(shí)現(xiàn)如下所示:

5.1 多層神經(jīng)網(wǎng)絡(luò)模型的參數(shù)初始化
def initialize_parameters_deep(layer_dims):
   
    np.random.seed(1)
    parameters = {}
    L = len(layer_dims)          #網(wǎng)絡(luò)的層數(shù)

    for l in range(1, L):
        parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) / np.sqrt(layer_dims[l-1]) *0.01
        parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
        
        assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))
        assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))

        
    return parameters
5.2 多層神經(jīng)網(wǎng)絡(luò)前向傳播函數(shù)的實(shí)現(xiàn)

def L_model_forward(X, parameters):

caches = []
    A = X
    L = len(parameters) // 2              
    for l in range(1, L):
        A_prev = A 
        A, cache = linear_activation_forward(A_prev, parameters['W' + str(l)], parameters['b' + str(l)], activation = "relu")
        caches.append(cache)
   
    AL, cache = linear_activation_forward(A, parameters['W' + str(L)], parameters['b' + str(L)], activation = "sigmoid")
    caches.append(cache)
    
    assert(AL.shape == (1,X.shape[1]))
            
    return AL, caches

5.3 多層神經(jīng)網(wǎng)絡(luò)模型的反向傳播實(shí)現(xiàn)

def L_model_backward(AL, Y, caches):
    
    grads = {}

    m = AL.shape[1]
    Y = Y.reshape(AL.shape) 
  
    dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))
    current_cache = caches[L-1]
    grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, activation = "sigmoid")
    
    for l in reversed(range(L-1)):
 
        current_cache = caches[l]
        dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 2)], current_cache, activation = "relu")
        grads["dA" + str(l + 1)] = dA_prev_temp
        grads["dW" + str(l + 1)] = dW_temp
        grads["db" + str(l + 1)] = db_temp

    return grads

5.4 參數(shù)更新

def update_parameters(parameters, grads, learning_rate):

    L = len(parameters) // 2 # number of layers in the neural network
    for l in range(L):
        parameters["W" + str(l+1)] = parameters["W" + str(l+1)] - learning_rate * grads["dW" + str(l+1)]
        parameters["b" + str(l+1)] = parameters["b" + str(l+1)] - learning_rate * grads["db" + str(l+1)]
        
    return parameters

5.5 多層神經(jīng)網(wǎng)絡(luò)的整體實(shí)現(xiàn)代碼

將以上所有的代碼按照神經(jīng)網(wǎng)絡(luò)的計(jì)算方式組合在一起,如下所示:


def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009
     np.random.seed(1)
    costs = []                         # keep track of cost

    parameters = initialize_parameters_deep(layers_dims)

    for i in range(0, num_iterations):

        AL, caches = L_model_forward(X,parameters)
      
        cost = compute_cost(AL, Y)
     
        grads = L_model_backward(AL,Y,caches)
       
        parameters = update_parameters(parameters,grads,learning_rate)
     
        if print_cost and i % 100 == 0:
            print ("Cost after iteration %i: %f" %(i, cost))
        if print_cost and i % 100 == 0:
            costs.append(cost)
            
  
    plt.plot(np.squeeze(costs))
    plt.ylabel('cost')
    plt.xlabel('iterations (per tens)')
    plt.title("Learning rate =" + str(learning_rate))
    plt.show()

在運(yùn)行以上代碼之前,需要定義一個網(wǎng)絡(luò)的結(jié)構(gòu),包括輸入層,隱藏層和輸出層的基本信息,具體實(shí)現(xiàn)代碼如下所示:


layers_dims = [12288, 20, 7, 5, 1] #  5-層的神經(jīng)網(wǎng)絡(luò)

最后,以上代碼運(yùn)行結(jié)果和損失的下降過程如下所示:

5.6 做出預(yù)測

根據(jù)4.7的預(yù)測代碼,分別對訓(xùn)練集和測試集做出預(yù)測,其結(jié)果分別如下所示:

可以看出,與淺層神經(jīng)網(wǎng)絡(luò)相比,多層神經(jīng)網(wǎng)絡(luò)的性能有所上升。

6 分類結(jié)果分析

利用以下代碼對神經(jīng)網(wǎng)絡(luò)分類不正確的圖像進(jìn)行輸出


def print_mislabeled_images(classes, X, y, p):
    """
    
    X -- 數(shù)據(jù)集
    y --真實(shí)標(biāo)簽
    p -- 預(yù)測標(biāo)簽
    """
    a = p + y  # 相加同為2或者同為0表示預(yù)測結(jié)果正確
    mislabeled_indices = np.asarray(np.where(a == 1))
    plt.rcParams['figure.figsize'] = (40.0, 40.0) 
    num_images = len(mislabeled_indices[0])
    for i in range(num_images):
        index = mislabeled_indices[1][i]
        
        plt.subplot(2, num_images, i + 1)
        plt.imshow(X[:,index].reshape(64,64,3), interpolation='nearest')
        plt.axis('off')
        plt.title("Prediction: " + classes[int(p[0,index])].decode("utf-8") + " \n Class: " + classes[y[0,index]].decode("utf-8"))
print_mislabeled_images(classes, test_x, test_y, pred_test)

最后,造成這種異常結(jié)果的原因可能如下:

  • 貓的身體處在照片中不合適的位置
  • 貓的顏色與圖片背景色太過接近
  • 貓的顏色較為罕見
  • 拍照角度
  • 圖片的亮度
  • 貓的身體在圖片中過大或者過小
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容