NG深度学习第一门课作业3-2 构建深度神经网络做图像处理

图像分类的深层神经网络及其应用

当你完成这个,你将完成第四周的最后一个编程作业,也是这门课的最后一个编程作业! 您将使用在上一个作业中实现的功能来构建一个深层网络,并将其应用于卡特彼勒和非卡特彼勒分类。希望您会看到相对于之前的逻辑回归实现,准确性有所提高。 完成这项任务后,您将能够: 建立并应用深层神经网络进行监督学习。 让我们开始吧!

1-准备软件包

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

  • 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_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)中相同的“猫vs非猫”数据集。你建立的模型对猫和非猫图像的分类有70%的测试准确率。希望你的新模型会表现得更好!

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

  • 标记为cat (1)或非cat (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()
print(train_x_orig.shape)
print(train_y.shape)
print(test_x_orig.shape)
print(test_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 = 50
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.

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

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

 

3 -模型的架构

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

  • 一个两层的神经网络
  • 一个L层的深层神经网络

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

3.1 -两层的神经网络

该模型可以概括为: INPUT -> LINEAR -> RELU -> LINEAR -> SIGMOID -> OUTPUT

3.2 - L层深层神经网络

有一个简化的网络表示:

 

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

  • 1.初始化参数/定义超参数
  • 2.迭代次数循环:
  • a.正向传播

  • b.计算成本函数

  • c.反向传播

  • d.更新参数(使用参数和来自背板的梯度)

  • 4.使用训练有素的参数来预测标签 现在让我们实现这两个模型!

 

4 -两层神经网络

问题:使用您在前面的作业中实现的辅助函数,构建一个具有以下结构的两层神经网络: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,例子数)
        Y - 标签,向量,0为非猫,1为猫,维度为(1,数量)
        layers_dims - 层数的向量,维度为(n_y,n_h,n_y)
        learning_rate - 学习率
        num_iterations - 迭代的次数
        print_cost - 是否打印成本值,每100次打印一次
        isPlot - 是否绘制出误差值的图谱
    返回:
        parameters - 一个包含W1,b1,W2,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)
#     print(parameters.keys())
#     print(parameters)
    ### 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):

        # 前向传播: 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, "relu")
        A2, cache2 = linear_activation_forward(A1, W2, b2, "sigmoid")
        ### END CODE HERE ###
        
        # 计算代价
        ### START CODE HERE ### (≈ 1 line of code)
        cost = compute_cost(A2,Y)
        ### END CODE HERE ###
        
        # 初始化反向传播
        dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))
        
        # 反向传播. 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, "sigmoid")
        dA0, dW1, db1 = linear_activation_backward(dA1, cache1, "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
        
        # 更新参数
        ### 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)
       
    # 绘制代价

    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 = 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.693049735659989
Cost after iteration 100: 0.6464320953428849
Cost after iteration 200: 0.6325140647912678
Cost after iteration 300: 0.6015024920354665
Cost after iteration 400: 0.5601966311605748
Cost after iteration 500: 0.515830477276473
Cost after iteration 600: 0.4754901313943325
Cost after iteration 700: 0.43391631512257495
Cost after iteration 800: 0.40079775362038866
Cost after iteration 900: 0.3580705011323798
Cost after iteration 1000: 0.3394281538366413
Cost after iteration 1100: 0.3052753636196264
Cost after iteration 1200: 0.27491377282130164
Cost after iteration 1300: 0.24681768210614857
Cost after iteration 1400: 0.19850735037466094
Cost after iteration 1500: 0.17448318112556632
Cost after iteration 1600: 0.17080762978096875
Cost after iteration 1700: 0.11306524562164708
Cost after iteration 1800: 0.09629426845937152
Cost after iteration 1900: 0.08342617959726867
Cost after iteration 2000: 0.07439078704319087
Cost after iteration 2100: 0.06630748132267936
Cost after iteration 2200: 0.05919329501038175
Cost after iteration 2300: 0.053361403485605606
Cost after iteration 2400: 0.04855478562877021

 

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

训练集的预测:

predictions_train = predict(train_x, train_y, parameters)

结果:

Accuracy: 1.0

测试集的预测:

predictions_test = predict(test_x, test_y, parameters)

结果:

Accuracy: 0.72

注意:您可能会注意到,在更少的迭代上运行模型(比如1500次)可以在测试集上提供更好的准确性。这被称为“提前停止”,我们将在下一课中讨论它。提前停止是防止过度拟合的一种方法。 恭喜!看来你的两层神经网络比逻辑回归实现(70%,作业第2周)有更好的性能(72%)。让我们看看你是否可以用一个L层模型做得更好。

 

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: 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。

    参数:
        X - 输入的数据,维度为(n_x,例子数)
        Y - 标签,向量,0为非猫,1为猫,维度为(1,数量)
        layers_dims - 层数的向量,维度为(n_y,n_h,···,n_h,n_y)
        learning_rate - 学习率
        num_iterations - 迭代的次数
        print_cost - 是否打印成本值,每100次打印一次
        isPlot - 是否绘制出误差值的图谱

    返回:
     parameters - 模型学习的参数。 然后他们可以用来预测。
    """

    np.random.seed(1)
    costs = []                         # keep track of cost
    
    # 初始化参数
    ### START CODE HERE ###
    parameters = initialize_parameters_deep(layers_dims)
    ### END CODE HERE ###
    
    # 循环 (梯度下降)
    for i in range(0, num_iterations):

        # 前向传播: [LINEAR -> RELU]*(L-1) -> LINEAR -> SIGMOID.
        ### START CODE HERE ### (≈ 1 line of code)
        AL, caches = L_model_forward(X,parameters)
        ### END CODE HERE ###
        
        # 计算代价
        ### START CODE HERE ### (≈ 1 line of code)
        cost = compute_cost(AL, Y)
        ### END CODE HERE ###
    
        # 后向传播
        ### START CODE HERE ### (≈ 1 line of code)
        grads = L_model_backward(AL,Y,caches)
        ### END CODE HERE ###
 
        # 更新参数
        ### 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)
            
    # 绘制代价
    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)

结果:

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

训练集的预测:

predictions_train = predict(train_x, train_y, parameters)

结果:

Accuracy: 0.9856459330143541

测试集的预测:

predictions_test = predict(test_x, test_y, parameters)

结果:

Accuracy: 0.8

恭喜!在同一测试集中,您的5层神经网络的性能(80%)似乎优于您的2层神经网络(72%)。 这是这项任务的良好表现。干得好! 尽管在下一堂关于“改进深层神经网络”的课程中,您将学习如何通过系统地搜索更好的超参数(学习速率、层亮度、迭代次数以及其他您在下一堂课中也将学习的参数)来获得更高的精度。

 

6- 结果分析

首先,让我们来看看一些图像,在L层模型中被错误地标记了,导致准确率没有提高。

print_mislabeled_images(classes, test_x, test_y, pred_test)

分析一下我们就可以得知原因了: 
模型往往表现欠佳的几种类型的图像包括:

  • 猫身体在一个不同的位置
  • 猫出现在相似颜色的背景下
  • 不同的猫的颜色和品种
  • 相机角度
  • 图片的亮度
  • 比例变化(猫的图像非常大或很小)

 

7-用自己的形象测试(可选/未分级练习)

祝贺你完成这项任务。您可以使用自己的图像并查看模型的输出。为此:

  • 1.单击本笔记本上方栏中的“文件”,然后单击“打开”进入您的Coursera集线器。
  • 2.将您的图像添加到“图像”文件夹中的这个笔记本目录中
  • 3.在下面的代码中更改图像的名称
  • 4.运行代码并检查算法是否正确(1 = cat,0 = non-cat)!
%matplotlib inline
## 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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值