吴恩达深度学习课程-Course 1 神经网络与深度学习 第四周 深层神经网络编程作业(第二部分)

第二部分

用于图像分类的深度神经网络:应用

完成此操作后,您将完成第 4 周的最后一个编程作业,以及本课程的最后一个编程作业!

您将使用在上一个作业中实现的函数来构建深度网络,并将其应用于猫与非猫分类。 希望您会看到相对于您之前的逻辑回归实现的准确性有所提高。

完成此任务后,您将能够:

  • 构建深度神经网络并将其应用于监督学习

让我们开始吧!

1 - 导入相关包

让我们首先导入您在此任务中需要的所有包。

  • numpy 是使用 Python 进行科学计算的基本包。
  • matplotlib 是一个用 Python 绘制图形的库。
  • h5py 是一个通用包,用于与存储在 H5 文件中的数据集进行交互。
  • 这里使用了 PILscipy,最后用你自己的图片来测试你的模型。
  • 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_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 - 数据集

您将使用与“作为神经网络的逻辑回归”(作业 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 = 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.")

在这里插入图片描述

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

在这里插入图片描述
像往常一样,您在将图像输入网络之前对其进行整形标准化。 代码在下面的单元格中给出。
在这里插入图片描述

# Reshape the training and test examples 
train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T   # “-1”使重塑展平剩余尺寸
test_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T

# 标准化数据以具有介于 0 和 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,这是一个重构图像向量的大小。

3 - 模型的架构

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

  • 一个 2 层神经网络
  • L层深度神经网络

然后,您将比较这些模型的性能,并尝试不同的 𝐿值
让我们来看看这两种架构。

3.1 - 2层神经网络

在这里插入图片描述
该模型可以概括为:INPUT -> LINEAR -> RELU -> LINEAR -> SIGMOID -> OUTPUT

图 2 的详细架构:

  • 输入是一个 (64,64,3) 图像,它被展平为大小为(12288,1)的向量。
  • 对应的向量: [ x 0 , x 1 , . . . , x 12287 ] T [x_0,x_1,...,x_{12287}]^T [x0,x1,...,x12287]T然后乘以大小为 ( n [ 1 ] , 12288 ) (n^{[1]}, 12288) (n[1],12288)的权重矩阵 W [ 1 ] W^{[1]} W[1]
  • 然后添加一个偏置项并取其 RELU 得到以下向量: [ a 0 [ 1 ] , a 1 [ 1 ] , . . . , a n [ 1 ] − 1 [ 1 ] ] T [a_0^{[1]}, a_1^{[1]},..., a_{n^{[1]}-1}^{[1]}]^T [a0[1],a1[1],...,an[1]1[1]]T
  • 然后重复相同的过程。
  • 您将结果向量乘以 𝑊[2]并加上您的截距(偏差)
  • 最后,您取结果的 sigmoid。 如果大于 0.5,则将其归类为猫。

3.2 - L层深度神经网络

用上述表示很难表示 L 层深度神经网络。 但是,这是一个简化的网络表示:
在这里插入图片描述
图 3 的详细架构:

  • 输入是一个 (64,64,3) 图像,它被展平为大小为 (12288,1) 的向量。
  • 相应的向量: [ x 0 , x 1 , . . . , x 12287 ] T [x_0,x_1,...,x_{12287}]^T [x0,x1,...,x12287]T 然后乘以权重矩阵 W [ 1 ] W^{[1]} W[1] 然后你加上截距 b [ 1 ] b^{[1 ]} b[1]。 结果称为线性单位
  • 接下来,您获取线性单元的 relu。 根据模型架构,此过程可以针对每个 ( W [ l ] , b [ l ] ) (W^{[l]}, b^{[l]}) (W[l],b[l]) 重复多次。
  • 最后,您取最终线性单元的 sigmoid。 如果大于 0.5,则将其归类为猫。

3.3 - 一般方法

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

  • 1.初始化参数/定义超参数
  • 2.num_iterations 循环
    a.前向传播
    b.计算成本函数
    c.反向传播
    d. 更新参数(使用parameters和来自 backprop 的 grads
  • 3.使用训练好的参数来预测标签

现在让我们实现这两个模型!

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):
    """
    实现了两层神经网络:LINEAR->RELU->LINEAR->SIGMOID。
    
    参数:
    X -- 输入数据, 形状为 (n_x, number of examples)
    Y -- 真实的 "标签" 向量 (包含 0 表示猫,1 表示非猫), of shape (1, number of examples)
    layers_dims -- 层的维度 (n_x, n_h, n_y)
    num_iterations -- 优化循环的迭代次数
    learning_rate -- 梯度下降更新规则的学习率
    print_cost -- 如果设置为 True,这将每 100 次迭代打印成本
    
    Returns:
    parameters -- 包括 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

在这里插入图片描述
在这里插入图片描述
好在你构建了一个矢量化的实现! 否则,训练它可能需要 10 倍的时间。
现在,您可以使用经过训练的参数对数据集中的图像进行分类。 要查看您对训练集和测试集的预测,请运行下面的单元格。

predictions_train = predict(train_x, train_y, parameters)

输出结果为
在这里插入图片描述

pred_test = predict(test_x, test_y, parameters)

在这里插入图片描述
注意】:您可能会注意到,以较少的迭代(比如 1500 次)运行模型可以在测试集上提供更好的准确性。 这称为“早停”,我们将在下一课程中讨论。 提前停止是一种防止过度拟合的方法

恭喜! 您的 2 层神经网络似乎比逻辑回归实现(70%,作业第 2 周)具有更好的性能(72%)。 让我们看看你是否可以用 𝐿 层模型做得更好。

5 - 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

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

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

# 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
    """
    实现一个 L 层神经网络: [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
parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True)

在这里插入图片描述
在这里插入图片描述

pred_train = predict(train_x, train_y, parameters)

在这里插入图片描述

pred_test = predict(test_x, test_y, parameters)

在这里插入图片描述
恭喜! 在相同的测试集上,您的 5 层神经网络似乎比您的 2 层神经网络 (72%) 具有更好的性能 (80%)。

这是此任务的良好性能。 不错的工作!

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

6 - 结果分析

首先我们来看看L层模型标注错误的一些图片。 这将显示一些错误标记的图像。

print_mislabeled_images(classes, test_x, test_y, pred_test)

在这里插入图片描述
模型往往表现不佳的几种类型的图像包括:

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

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

恭喜你完成了这个任务。 您可以使用自己的图像并查看模型的输出。 要做到这一点:

  1. 单击本笔记本上方栏中的“文件”,然后单击“打开”进入您的 Coursera Hub
  2. 将您的图像添加到此 Jupyter Notebook 目录的“images”文件夹中
  3. 在以下代码中更改您的图像名称
  4. 运行代码并检查算法是否正确(1 = 猫,0 = 非猫)!
"""
这是老师的代码
"""
## 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.")

来自链接评论区的大神的代码

"""
这里网上其它大神的代码
"""
#自己找图片来识别
from PIL import Image
my_label_y = [1] # the true class of your image (1 -> cat, 0 -> non-cat)
 
num_px = 64
image = Image.open('images/my_image.jpg')
 
my_image = np.array(image.resize((num_px,num_px),Image.ANTIALIAS))
 
my_image = my_image.reshape(num_px*num_px*3 , -1)
 
predict_my_image = predict(my_image , my_label_y ,parameters)
 
plt.imshow(image)
 
print("y = " + str(np.squeeze(predict_my_image)) + ", your L-layer model predicts a \"" + classes[int(np.squeeze(predict_my_image))].decode("utf-8") + "\"picture.")
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值