赞
踩
你将使用在上一个作业中实现的函数来构建深层网络,并将其应用于分类cat图像和非cat图像。 希望你会看到相对于先前的逻辑回归实现的分类,准确性有所提高。
完成此任务后,你将能够:
让我们首先导入在作业过程中需要的所有软件包。
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)
你将使用与“用神经网络思想实现Logistic回归”(作业2)中相同的“cats vs non-cats”数据集。此前你建立的模型在对猫和非猫图像进行分类时只有70%的准确率。希望你的新模型会更好!
问题说明:你将获得一个包含以下内容的数据集(“data.h5”):
让我们熟悉一下数据集吧, 首先通过运行以下代码来加载数据。
train_x_orig, train_y, test_x_orig, test_y, classes = load_data()
运行以下代码以展示数据集中的图像。 通过更改索引,然后重新运行单元以查看其他图像。
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.
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)
与往常一样,在将图像输入到网络之前,需要对图像进行重塑和标准化。 下面单元格给出了相关代码。
图1:图像转换为向量。
# 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 12,288 = 64 \times 64 \times 3 12,288=64×64×3,这是图像重塑为向量的大小。
现在你已经熟悉了数据集,是时候建立一个深度神经网络来区分猫图像和非猫图像了。
你将建立两个不同的模型:
让我们看一下两种架构。
图2:2层神经网络。
该模型可以总结为:Input -> Linear -> ReLu -> Linear -> Sigmoid -> Output
图2的详细架构:
用上面的方式很难表示一个L层的深度神经网络。这是一个简化的网络表示形式:
图3:L层神经网络。
该模型可以总结为:**[Linear -> ReLu] × \times × (L - 1) ->Linear -> Sigmoid **
图3的详细结构:
与往常一样,你将遵循深度学习步骤来构建模型:
初始化参数/定义超参数
循环num_iterations次:
a.正向传播
b.计算损失函数
c.反向传播
d.更新参数(使用参数和反向传播的梯度)
使用训练好的参数来预测标签
现在让我们实现这两个模型!
问题:使用你在上一个作业中实现的辅助函数来构建具有以下结构的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
n_x = 12288 # num_px * num_px * 3
n_h = 7
n_y = 1
layers_dims = (n_x, n_h, n_y)
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 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(2, num_iterations): # 正向传播(Linear -> Relu -> Linear -> Sigmoid) A1, cache1 = linear_activation_forward(X, W1, b1, activation = "relu") A2, cache2 = linear_activation_forward(A1, W2, b2, activation = "sigmoid") # 计算代价 cost = compute_cost(A2, Y) # 初始化反向传播 dA2 = -(np.divide(Y, A2) - np.divide(1 - Y, 1 - A2)) # 反向传播 dA1, dW2, db2 = linear_activation_backward(dA2, cache2, activation = "sigmoid") dA0, dW1, db1 = linear_activation_backward(dA1, cache1, activation = "relu") # 设置grads['dW1']=dW1,... grads['dW1'] = dW1 grads['db1'] = db1 grads['dW2'] = dW2 grads['db2'] = db2 # 更新参数 parameters = update_parameters(parameters, grads, learning_rate) # 从参数中检索W1, b1, W2, b2 W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] # 打印每100个训练示例的成本 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
运行下面的单元格以训练模型参数。观察损失下降以查看模型是否运行。运行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)
Cost after iteration 100: 0.6466225250643386 Cost after iteration 200: 0.6329267017700396 Cost after iteration 300: 0.6022777927398311 Cost after iteration 400: 0.5610680026124479 Cost after iteration 500: 0.5168132026755782 Cost after iteration 600: 0.4766873092878978 Cost after iteration 700: 0.4347884767113523 Cost after iteration 800: 0.3912816235692091 Cost after iteration 900: 0.3597856592125624 Cost after iteration 1000: 0.3430198684370303 Cost after iteration 1100: 0.30641363903267166 Cost after iteration 1200: 0.27109865743778777 Cost after iteration 1300: 0.24031971112012065 Cost after iteration 1400: 0.200247848772056 Cost after iteration 1500: 0.18000394885786078 Cost after iteration 1600: 0.17473791105839445 Cost after iteration 1700: 0.11323537732604003 Cost after iteration 1800: 0.09709104443552838 Cost after iteration 1900: 0.08353123747222893 Cost after iteration 2000: 0.07455470245436674 Cost after iteration 2100: 0.06647310649472173 Cost after iteration 2200: 0.05928183178382505 Cost after iteration 2300: 0.05345000603677248 Cost after iteration 2400: 0.04865082074708337
你构建了向量化的实现! 否则,可能需要花费10倍的时间来训练它。
你可以使用训练好的参数对数据集中的图像进行分类。 要查看训练和测试集的预测结果,请运行以下单元格。
predictions_train = predict(train_x, train_y, parameters)
Accuracy: 0.9999999999999998
predictions_test = predict(test_x, test_y, parameters)
Accuracy: 0.72
注意:你可能会注意到,以较少的迭代次数(例如1500)运行模型可以使测试集具有更高的准确性。 这称为“尽早停止”,我们将在下一课程中讨论。 提前停止是防止过拟合的一种方法。
恭喜你!看来你的2层神经网络的性能(72%)比逻辑回归实现(70%,第2周的作业)更好。 让我们看看使用 L L L层模型是否可以做得更好。
问题:使用之前实现的辅助函数来构建具有以下结构的 L L L层神经网络:[Linear -> ReLu] × \times × (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
layers_dims = [12288, 20, 7, 5, 1] # 5-layer model
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost = False): np.random.seed(1) costs = [] # 初始化参数 parameters = initialize_parameters_deep(layers_dims) for i in range(0, num_iterations): # 前向传播:[Linear -> ReLu] * (L-1) -> Linear -> Sigmoid。 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() 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
pred_train = predict(train_x, train_y, parameters)
Accuracy: 0.9856459330143539
pred_test = predict(test_x, test_y, parameters)
Accuracy: 0.8
Good!在相同的测试集上,你的5层的神经网络似乎比2层神经网络具有更好的性能(80%)。做的好!
在下一作业教程“改善深度神经网络”中,你将学习如何通过系统地匹配更好的超参数(学习率,层数,迭代次数以及下一门课程中还将学习到的其他参数)来获得更高的准确性。
首先,让我们看一下L层模型标记错误的一些图像。 这将显示一些分类错误的图像。
print_mislabeled_images(classes, test_x, test_y, pred_test)
该模型在表现效果较差的的图像包括:
你可以使用自己的图像测试并查看模型的输出。要做到这一点:
## 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 = my_image
image = np.array(plt.imread(fname))
my_image = np.array(Image.fromarray(image).resize(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.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。