Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application

 

Deep Neural Network for Image Classification: Application

您将使用您在先前任务中实现的功能来构建深层网络,并将其应用于cat与非cat分类。希望您会看到相对于之前的逻辑回归实现的准确性有所提高。

完成此任务后,您将能够:构建并应用深度神经网络进行监督学习。

让我们首先导入在此分配期间您需要的所有包。

  • numpy是使用Python进行科学计算的基础包。
  • matplotlib是一个用Python绘制图形的库。
  • h5py是与存储在H5文件中的数据集进行交互的通用包。
  • 此处使用PIL和scipy来测试您的模型,最后使用您自己的图片。
  • dnn_app_utils提供在“构建您的深度神经网络:逐步”中为此笔记本分配的功能。
  • np.random.seed(1)用于保持所有随机函数调用一致。它将帮助我们评估您的工作。
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 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 - 数据集

您将使用与“Logistic回归为神经网络”(作业2)相同的“Cat vs non-Cat”数据集。 您构建的模型在对猫和非猫图像进行分类时具有70%的测试准确度。 希望您的新模型表现更好!

问题陈述:您将获得一个数据集(“data.h5”),其中包含:

  • 标记为猫(1)或非猫(0)的m_train图像训练集
  • 标记为猫和非猫的m_test图像的测试集
  • 每个图像的形状(num_px,num_px,3),其中3表示3个通道(RGB)。

让我们更熟悉数据集。 通过运行下面的单元格加载数据。

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

 

以下代码将显示数据集中的图像。 随意更改索引并重复运行单元格以查看其他图像。

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

Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application_第1张图片

# 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))

Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application_第2张图片

像往常一样,您在将图像送入网络之前对图像进行整形和标准化。 代码在下面的单元格中给出。

Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application_第3张图片

# 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))

12,288等于64×64×3,这是一个重新成形的图像矢量的大小。

现在您已经熟悉了数据集,现在是时候构建一个深度神经网络来区分猫图像和非猫图像。

您将构建两个不同的模型:

  • 2层神经网络。
  • L层深度神经网络。

然后,您将比较这些模型的性能,并为L尝试不同的值。

3.1 - 2层神经网络

 

Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application_第4张图片

图2的详细架构:

  • 输入是(64,64,3)图像,其被展平为大小为(12288,1)的向量。
  • 相应的矢量:然后乘以大小的权重矩阵W [1]。
  • 然后你添加一个偏置项并使其得到以下向量:
  • 然后重复相同的过程。
  • 将得到的向量乘以并添加截距(偏差)。
  • 最后,你取结果的sigmoid。 如果它大于0.5,则将其归类为猫。

3.2 - L层深度神经网络

用上述表示很难表示L层深度神经网络。 但是,这是一个简化的网络表示:

Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application_第5张图片

图3的详细架构:
输入是(64,64,3)图像,其被展平为大小为(12288,1)的向量。
相应的向量:然后乘以权重矩阵,然后加上截距。结果称为线性单位。
接下来,你拿线性单元的relu。根据模型架构,每个可以重复此过程若干次。
最后,你取最终线性单位的sigmoid。如果它大于0.5,则将其归类为猫。

3.3 - 一般方法

像往常一样,您将遵循深度学习方法来构建模型:

  1. 初始化参数/定义超参数
  2. 循环num_iterations:
  • 前向传播
  • 计算成本函数
  • 向后传播
  • 更新参数(使用参数和backprop的grads)
  1. 使用经过训练的参数来预测标签

4 - 双层神经网络

问题:使用您在先前任务中实现的辅助函数来构建具有以下结构的2层神经网络:LINEAR - > RELU - > LINEAR - > SIGMOID。您可能需要的功能及其输入是:

 

def initialize_parameters(n_x, n_h, n_y):
    ...
    return parameters 
def linear_activation_forward(A_prev, W, b, activation):
    ...
    return A, cache
def compute_cost(AL, Y):
    ...
    return cost
def linear_activation_backward(dA, cache, activation):
    ...
    return dA_prev, dW, db
def update_parameters(parameters, grads, learning_rate):
    ...
    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)
# 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

 

运行下面的单元格来训练您的参数。 看看你的模型是否运行。 成本应该在下降。 运行2500次迭代可能需要5分钟。 检查“迭代后的成本0”是否与下面的预期输出匹配,如果没有单击笔记本上方栏上的方块(⬛)来停止单元格并尝试查找错误。

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

Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application_第6张图片Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application_第7张图片

Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application_第8张图片

你构建了一个矢量化实现的好东西! 否则可能需要花费10倍的时间来训练它。

现在,您可以使用训练的参数对数据集中的图像进行分类。 要查看有关训练和测试集的预测,请运行下面的单元格。

predictions_train = predict(train_x, train_y, parameters)

注意:您可能会注意到,在较少的迭代(例如1500)上运行模型可以提高测试集的准确性。 这被称为“提前停止”,我们将在下一个课程中讨论它。 提前停车是防止过度装配的一种方法。

5 - L层神经网络

问题:使用先前实现的辅助函数构建具有以下结构的L层神经网络:[LINEAR - > RELU]×(L-1) - > LINEAR - > SIGMOID。 您可能需要的功能及其输入是:

def initialize_parameters_deep(layer_dims):
    ...
    return parameters 
def L_model_forward(X, parameters):
    ...
    return AL, caches
def compute_cost(AL, Y):
    ...
    return cost
def L_model_backward(AL, Y, caches):
    ...
    return grads
def update_parameters(parameters, grads, learning_rate):
    ...
    return parameters
### CONSTANTS ###
layers_dims = [12288, 20, 7, 5, 1] #  5-layer model
# GRADED FUNCTION: n_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

 

您现在将模型训练为5层神经网络。

运行下面的单元格来训练您的模型。 每次迭代都会降低成本。 运行2500次迭代可能需要5分钟。 检查“迭代后的成本0”是否与下面的预期输出匹配,如果没有单击笔记本上方栏上的方块(⬛)来停止单元格并尝试查找错误。

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


Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application_第9张图片Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application_第10张图片

 

 

pred_train = predict(train_x, train_y, parameters)

 

 

 

pred_test = predict(test_x, test_y, parameters)

恭喜! 在同一测试集中,您的5层神经网络似乎比2层神经网络(72%)具有更好的性能(84%)。

虽然在下一期“改进深度神经网络”课程中,您将学习如何通过系统地搜索更好的超参数(learning_rate,layers_dims,num_iterations以及其他您将在下一课程中学习的内容)来获得更高的准确性。

6)结果分析

首先,让我们看一下L层模型标记错误的一些图像。 这将显示一些贴错标签的图像。

print_mislabeled_images(classes, test_x, test_y, pred_test)

模型往往表现不佳的一些类型的图像包括:

  • 猫体处于不寻常的位置
  • 猫出现在相似颜色的背景下
  • 不寻常的猫的颜色和物种
  • 相机角度
  • 图片的亮度
  • 尺度变化(图像中的猫非常大或小)

7)用你自己的图像进行测试(可选/未分级练习)

 

  1. 恭喜你完成了这项任务。 您可以使用自己的图像并查看模型的输出。 要做到这一点:
  2. 单击此笔记本上方栏中的“file”,然后单击“open”以进入Coursera Hub。
  3. 将图像添加到此图像文件夹中的Jupyter Notebook目录中
  4. 在以下代码中更改图像的名称
  5. 运行代码并检查算法是否正确(1 = cat,0 =非cat)!

 

## START CODE HERE ##
my_image = "my_image.jpg" # change this to the name of your image file 
my_label_y = [1] # the true class of your image (1 -> cat, 0 -> non-cat)
## END CODE HERE ##

fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
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.")
Accuracy: 1.0
y = 1.0, your L-layer model predicts a "cat" picture.

Coursera吴恩达Deep Learning.ai第一课第四周Deep Neural Network for Image Classification: Application_第11张图片

 

 

你可能感兴趣的:(DeepLearning)