DeepLearing-Deep Neural Network for Image Classification: Application(编程作业1.4.2)


上节课的作业中,我们完成了2层神经网络以及L层神经网络模型的搭建,现在,我们便可以以此模型来实现图片分类。

1 - 前期准备

为了后续的操作,首先我们需要导入一些库,如time,h5py,scipy等。另外dnn_app_utils_v2文件中存储了我们建立的网络中的函数,现在我们也能够直接调用。

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

%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

%load_ext autoreload
%autoreload 2

np.random.seed(1)   #使得能够生成固定的随机数

2 - 数据集

这次采用的仍然是之间课程中所提到过的猫分类的数据集(“data.h5”):

  • 训练集中有 m _ t r a i n m\_train m_train个训练样本,并且进行了标注:cat(1), non-cat(0)
  • 测试集中有 m _ t e s t m\_test m_test个测试样本,同样标注为cat 和 non-cat
  • 每张照片的尺寸为 ( n u m _ p x , n u m _ p x , 3 ) (num\_px, num\_px, 3) (num_px,num_px,3),其中3表示RGB三通道

加载数据:

train_x_orig, train_y, test_x_orig, test_y, classes = load_data()

查看数据:

# Example of a picture
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.")

其输出的结果为:

y = 1. It's a cat picture.

在这里插入图片描述
(这图片真的就是这么糊。)我们可以通过更改索引index的值来显示不同的图片以及其相对应的分类结果。
获取数据的尺寸信息:

# Explore your dataset 
m_train = train_x_orig.shape[0]
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))

输出结果为:

Number of training examples: 209
Number of testing examples: 50
Each image is of size: (64, 64, 3)
train_x_orig shape: (209, 64, 64, 3)
train_y shape: (1, 209)
test_x_orig shape: (50, 64, 64, 3)
test_y shape: (1, 50)

reshape:
与往常一样,在将图像输入到网络之前,需要对图像进行整形和标准化。
在这里插入图片描述
其代码如下:

# Reshape the training and test examples 
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

# Standardize data to have feature values between 0 and 1.
train_x = train_x_flatten/255.
test_x = test_x_flatten/255.

print ("train_x's shape: " + str(train_x.shape))
print ("test_x's shape: " + str(test_x.shape))

输出结果为:

train_x's shape: (12288, 209)
test_x's shape: (12288, 50)

3 - 模型框架

与上次的作业类似,我们将创建两种神经网络,一种是双层神经网络,另一种是L层神经网络。在此基础上,我们还会对不同L值得网络模型进行比较分析。

3.1 - 双层神经网络

在这里插入图描述
这个模型可以被简化为INPUT -> LINEAR -> RELU -> LINEAR -> SIGMOID -> OUTPUT,其架构为

  1. 输入的图片的尺寸为 ( 64 , 64 , 3 ) (64,64,3) (64,64,3),我们通过reshape操作将其扁平化为尺寸大小为 ( 12288 , 1 ) (12288,1) (12288,1)的向量。
  2. 形式为向量 [ x 0 , x 1 , . . . , x 12287 ] T [x0,x1,...,x12287]^T [x0,x1,...,x12287]T的样本与大小为 ( n [ 1 ] , 12288 ) (n^{[1]},12288) (n[1],12288)的权重矩阵 W [ 1 ] W^{[1]} W[1]相乘。
  3. 加上偏移项并使用relu激活函数将其变成 [ a 0 [ 1 ] , a 1 [ 1 ] , . . . , a n [ 1 ] − 1 [ 1 ] ] T [a^{[1]}_0,a^{[1]}_1,...,a^{[1]}_{n^{[1]}-1}]^T [a0[1],a1[1],...,an[1]1[1]]T
  4. 重复以上过程,将之前的结果与尺寸为 ( 1 , n [ 1 ] ) (1,n^{[1]}) (1,n[1])的权重矩阵 W [ 2 ] W^{[2]} W[2]相乘并加上偏移量。
  5. 将结果带入sigmoid激活函数中,如果得到的值大于0.5,则认为图片的内容为cat。

3.2 - L层神经网络

L层的神经网络模型可以表示为如下形式:
在这里插入图片描述
该模型的可以被简化为 [LINEAR -> RELU] × (L-1) -> LINEAR -> SIGMOID ,其架构为:
6. 输入的图片的尺寸为 ( 64 , 64 , 3 ) (64,64,3) (64,64,3),我们通过reshape操作将其扁平化为尺寸大小为 ( 12288 , 1 ) (12288,1) (12288,1)的向量。
7. 将形为向量 [ x 0 , x 1 , . . . , x 12287 ] T [x0,x1,...,x12287]^T [x0,x1,...,x12287]T的样本与大小为 ( n [ 1 ] , 12288 ) (n^{[1]},12288) (n[1],12288)的权重矩阵 W [ 1 ] W^{[1]} W[1]相乘并加上偏移量 b [ 1 ] b^{[1]} b[1]。这个过程被称为线性单元。
8. 将线性单元的结果输入relu激活函数中,由于该层神经网络存在多个神经元,所以该步骤会对位于该层的神经元都进行处理。
9. 最后将输出的线性单元输入到sigmoid激活函数中,若输出结果大于0.5,则将其判别为cat。

3.3 - 通用方法

我们一般按照以下方式来建立模型:

  1. 参数初始化 / 定义超参数
  2. 多次循环迭代
    a. 前向传播
    b. 计算损失函数
    c. 反向传播
    d. 更新参数(根据梯度)
  3. 用训练完的参数进行预测

4 - 双层神经网络

在之前的课程中,我们已经明白双层神经网络的模型结构为LINEAR -> RELU -> LINEAR -> SIGMOID,因此我们可以通过调用之前已经实现的函数来完成代码:

# GRADED FUNCTION: two_layer_model

def two_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):
    """
    Implements a two-layer neural network: LINEAR->RELU->LINEAR->SIGMOID.
    
    Arguments:
    X -- input data, of shape (n_x, number of examples)
    Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
    layers_dims -- dimensions of the layers (n_x, n_h, n_y)
    num_iterations -- number of iterations of the optimization loop
    learning_rate -- learning rate of the gradient descent update rule
    print_cost -- If set to True, this will print the cost every 100 iterations 
    
    Returns:
    parameters -- a dictionary containing W1, W2, b1, and b2
    """
    
    np.random.seed(1)
    grads = {}
    costs = []                              # to keep track of the cost
    m = X.shape[1]                           # number of examples
    (n_x, n_h, n_y) = layers_dims
    
    # Initialize parameters dictionary, by calling one of the functions you'd previously implemented
    ### START CODE HERE ### (≈ 1 line of code)
    parameters = initialize_parameters(n_x,n_h,n_y)
    ### END CODE HERE ###
    
    # Get W1, b1, W2 and b2 from the dictionary parameters.
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    
    # Loop (gradient descent)

    for i in range(0, num_iterations):

        # Forward propagation: LINEAR -> RELU -> LINEAR -> SIGMOID. Inputs: "X, W1, b1". Output: "A1, cache1, A2, cache2".
        ### START CODE HERE ### (≈ 2 lines of code)
        A1, cache1 = linear_activation_forward(X, W1, b1, activation = "relu")
        A2, cache2 = linear_activation_forward(A1, W2, b2, activation = "sigmoid")
        ### END CODE HERE ###
        
        # Compute cost
        ### START CODE HERE ### (≈ 1 line of code)
        cost = compute_cost(A2, Y)
        ### END CODE HERE ###
        
        # Initializing backward propagation
        dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))
        
        # Backward propagation. Inputs: "dA2, cache2, cache1". Outputs: "dA1, dW2, db2; also dA0 (not used), dW1, db1".
        ### START CODE HERE ### (≈ 2 lines of code)
        dA1, dW2, db2 = linear_activation_backward(dA2, cache2, activation = "sigmoid")
        dA0, dW1, db1 = linear_activation_backward(dA1, cache1, activation = "relu")
        ### END CODE HERE ###
        
        # Set grads['dWl'] to dW1, grads['db1'] to db1, grads['dW2'] to dW2, grads['db2'] to db2
        grads['dW1'] = dW1
        grads['db1'] = db1
        grads['dW2'] = dW2
        grads['db2'] = db2
        
        # Update parameters.
        ### START CODE HERE ### (approx. 1 line of code)
        parameters = update_parameters(parameters, grads, learning_rate)
        ### END CODE HERE ###

        # Retrieve W1, b1, W2, b2 from parameters
        W1 = parameters["W1"]
        b1 = parameters["b1"]
        W2 = parameters["W2"]
        b2 = parameters["b2"]
        
        # Print the cost every 100 training example
        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)
       
    # plot the cost

    plt.plot(np.squeeze(costs))
    plt.ylabel('cost')
    plt.xlabel('iterations (per tens)')
    plt.title("Learning rate =" + str(learning_rate))
    plt.show()
    
    return parameters

测试代码如下:

### CONSTANTS DEFINING THE MODEL ####
n_x = 12288     # num_px * num_px * 3
n_h = 7
n_y = 1
layers_dims = (n_x, n_h, n_y)

parameters = two_layer_model(train_x, train_y, layers_dims = (n_x, n_h, n_y), num_iterations = 2500, print_cost=True)

运行的结果如下:

Cost after iteration 0: 0.6930497356599888
Cost after iteration 100: 0.6464320953428849
Cost after iteration 200: 0.6325140647912677
Cost after iteration 300: 0.6015024920354665
Cost after iteration 400: 0.5601966311605747
Cost after iteration 500: 0.5158304772764729
Cost after iteration 600: 0.47549013139433255
Cost after iteration 700: 0.43391631512257495
Cost after iteration 800: 0.4007977536203886
Cost after iteration 900: 0.3580705011323798
Cost after iteration 1000: 0.3394281538366412
Cost after iteration 1100: 0.3052753636196264
Cost after iteration 1200: 0.2749137728213015
Cost after iteration 1300: 0.24681768210614846
Cost after iteration 1400: 0.19850735037466108
Cost after iteration 1500: 0.17448318112556654
Cost after iteration 1600: 0.17080762978096023
Cost after iteration 1700: 0.11306524562164728
Cost after iteration 1800: 0.09629426845937154
Cost after iteration 1900: 0.08342617959726861
Cost after iteration 2000: 0.07439078704319084
Cost after iteration 2100: 0.06630748132267932
Cost after iteration 2200: 0.05919329501038171
Cost after iteration 2300: 0.053361403485605564
Cost after iteration 2400: 0.04855478562877018

在这里插入图片描述
接着,我们便可以使用以上训练好的参数进行预测。首先我们先在训练集上进行预测,并求得结果的准确率,使用代码为:predictions_train = predict(train_x, train_y, parameters)。运行结果为Accuracy: 1.0。接着,我们对测试集得图片同样进行预测,计算准确率,代码为:predictions_test = predict(test_x, test_y, parameters),测试结果为Accuracy: 0.72。准确率高于之前逻辑回归得准确率(70%)。
另外,通过多次实验分析可以得到,在训练的过程中略微减小迭代的代数(例如减小到1500),可以增加模型在测试集上的准确率,这就是“early stopping”,能够一定程度上防止过拟合。
接下来,我们进一步来完成L层神经网络的搭建

5 - L层神经网络

L层神经网络的模型可以简化为**[LINEAR -> RELU] × (L-1) -> LINEAR -> SIGMOID**,我们用已经实现的代码来完成该模型:

# GRADED FUNCTION: L_layer_model

def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009
    """
    Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID.
    
    Arguments:
    X -- data, numpy array of shape (number of examples, num_px * num_px * 3)
    Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)
    layers_dims -- list containing the input size and each layer size, of length (number of layers + 1).
    learning_rate -- learning rate of the gradient descent update rule
    num_iterations -- number of iterations of the optimization loop
    print_cost -- if True, it prints the cost every 100 steps
    
    Returns:
    parameters -- parameters learnt by the model. They can then be used to predict.
    """

    np.random.seed(1)
    costs = []                         # keep track of cost
    
    # Parameters initialization.
    ### START CODE HERE ###
    parameters = initialize_parameters_deep(layers_dims)
    ### END CODE HERE ###
    
    # Loop (gradient descent)
    for i in range(0, num_iterations):

        # Forward propagation: [LINEAR -> RELU]*(L-1) -> LINEAR -> SIGMOID.
        ### START CODE HERE ### (≈ 1 line of code)
        AL, caches = L_model_forward(X, parameters)
        ### END CODE HERE ###
        
        # Compute cost.
        ### START CODE HERE ### (≈ 1 line of code)
        cost = compute_cost(AL, Y)
        ### END CODE HERE ###
    
        # Backward propagation.
        ### START CODE HERE ### (≈ 1 line of code)
        grads = L_model_backward(AL, Y, caches)
        ### END CODE HERE ###
 
        # Update parameters.
        ### START CODE HERE ### (≈ 1 line of code)
        parameters = update_parameters(parameters, grads, learning_rate)
        ### END CODE HERE ###
                
        # Print the cost every 100 training example
        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)
            
    # plot the cost
    plt.plot(np.squeeze(costs))
    plt.ylabel('cost')
    plt.xlabel('iterations (per tens)')
    plt.title("Learning rate =" + str(learning_rate))
    plt.show()
    
    return parameters

测试的代码为:

### CONSTANTS ###
layers_dims = [12288, 20, 7, 5, 1] #  5-layer model

parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True)

运行的结果为:

Cost after iteration 0: 0.771749
Cost after iteration 100: 0.672053
Cost after iteration 200: 0.648263
Cost after iteration 300: 0.611507
Cost after iteration 400: 0.567047
Cost after iteration 500: 0.540138
Cost after iteration 600: 0.527930
Cost after iteration 700: 0.465477
Cost after iteration 800: 0.369126
Cost after iteration 900: 0.391747
Cost after iteration 1000: 0.315187
Cost after iteration 1100: 0.272700
Cost after iteration 1200: 0.237419
Cost after iteration 1300: 0.199601
Cost after iteration 1400: 0.189263
Cost after iteration 1500: 0.161189
Cost after iteration 1600: 0.148214
Cost after iteration 1700: 0.137775
Cost after iteration 1800: 0.129740
Cost after iteration 1900: 0.121225
Cost after iteration 2000: 0.113821
Cost after iteration 2100: 0.107839
Cost after iteration 2200: 0.102855
Cost after iteration 2300: 0.100897
Cost after iteration 2400: 0.092878

在这里插入图片描述
同样先对训练集进行预测:pred_train = predict(train_x, train_y, parameters),得到的准确率为Accuracy: 0.986;接着对测试集进行预测:pred_test = predict(test_x, test_y, parameters),得到的准确率为:Accuracy: 0.8
至此,我们已经完成了5层神经网络模型的训练以及预测,从最后预测的救国可以看出它比前面的两层神经网络更好。当然,我们也可以通过改变超参数以及迭代的代数等数据来进一步提升预测的准确性。

6 - 结果分析

我们先来观察一下模型预测错误的几个样本:

def print_mislabeled_images(classes, X, y, p):
    """
    Plots images where predictions and truth were different.
    X -- dataset
    y -- true labels
    p -- predictions
    """
    a = p + y
    mislabeled_indices = np.asarray(np.where(a == 1))
    plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots
    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)

在这里插入图片描述
由此可见,在以下条件下模型的预测可能会出现问题:

  • 猫出现的位置不常见
  • 猫的颜色和背景相似
  • 猫的颜色和种类不常见
  • 相机的角度不合适
  • 图片的亮度不合适
  • 比例误差(猫在图像中过大或过小)

7 - 在自己的数据集

现在,我们以及可以使用这个模型来对自己的图片进行预测。把图片放在“images”文件夹下,使用以下代码:

## START CODE HERE ##
my_image = XXX
my_label_y = XXX
## END CODE HERE ##

fname = "images/" + my_image
image = np.array(plt.imread(fname))
my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((num_px*num_px*3,1))
my_predicted_image = predict(my_image, my_label_y, parameters)

plt.imshow(image)
print ("y = " + str(np.squeeze(my_predicted_image)) + ", your L-layer model predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") +  "\" picture.")

其中,my_images的取值为图片的名称,my_label_y的值为图片的分类(0表示non-cat, 1表示cat)。
我选取了一只比较“丑”的猫的照片,并令my_label_y = [1],照片如下:
在这里插入图片描述
输出结果为:

Accuracy: 1.0
y = 1.0, your L-layer model predicts a "cat" picture.

预测成功了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值