1.导入package
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_v3 import *
from public_tests 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”),其中包含:
-标记为cat(1)或非cat(0)的“m_train”图像的训练集
-标记为cat和非cat的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.")
编译:
# 浏览数据集
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))
编译:
解释:
train_x_orig
和 test_x_orig
存储了图像数据,其形状为 (数量, 图像高度, 图像宽度, 通道数)
,其中 数量
表示样本数量,图像高度
和 图像宽度
表示图像的尺寸,通道数
表示图像的颜色通道数(例如,RGB 图像的通道数为 3)。
train_y
和 test_y
存储了对应于每个图像的标签,其形状为 (1, 数量)
。这里的 数量
与图像的数量相同。
像往常一样,在将图像输入网络之前,您可以对图像进行整形和标准化。代码在下面的单元格中给出。
# 重塑培训和测试示例
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))
编译:
注:12288等于64×64×3,这是一个reshape图像向量的大小。(“3”=red+green+blue)
3.模型架构
3.1二层神经网络
图2的详细架构:
输入是一个(64,64,3)图像,它被展平为大小为(12288,1)的矢量。相应的矢量:[𝑥0,𝑥1.𝑥12287]𝑇
然后乘以权重矩阵𝑊[1] 的大小(𝑛[1] ,12288)
然后,添加一个偏置项并取其relu,得到以下向量:[𝑎[1] 0,𝑎[1] 1,。。。,𝑎[1]𝑛[1] −1]𝑇
将结果向量乘以𝑊[2] 并加上截距(偏置)。
最后,记下经过sigmoid的结果。如果大于0.5,则将其归类为猫。
3.2L层神经网络
使用上述表示法来表示L层深度神经网络是相当困难的。然而,这里是一个简化的网络表示:
图3的详细架构:
输入是一个(64,64,3)图像,它被展平为大小为(12288,1)的矢量。相应的矢量:[𝑥0,𝑥1.𝑥12287]𝑇然后乘以权重矩阵𝑊[1] 然后加上截距𝑏[1] 。结果称为线性单位。
接下来,取线性单位的relu。这个过程可以对每个重复几次(𝑊[𝑙],𝑏[𝑙])取决于模型架构。
最后,记下经过sigmoid的结果。如果大于0.5,则将其归类为猫。
3.3一般方法
- 初始化参数/定义超参数
- 重复loop:a. 前向传播 b. 计算损失函数 c. 后向传播 d. 更新参数 (使用参数和反向投影的梯度)
- 使用经过训练的参数预测标签
4.两层神经网络
Exercise 1 - two_layer_model
###定义模型的常量####
n_x = 12288 # num_px * num_px * 3,输入层的神经元数
n_h = 7 #隐藏层的神经元数,这是一个超参数
n_y = 1 #输出层的神经元数。在二分类问题中,n_y 通常设置为 1,因为你只需要一个输出节点来表示分类结果(例如,猫或非猫)。在多类别分类问题中,n_y 等于类别的数量。
layers_dims = (n_x, n_h, n_y) #一个元组,包含了神经网络各层的维度。具体来说,layers_dims 的定义为 (n_x, n_h, n_y),表示神经网络的结构包括输入层、隐藏层和输出层。
learning_rate = 0.0075 #学习率,是梯度下降算法中的一个超参数,用于控制参数更新的步幅。这是一个需要手动调整的参数,影响着模型的收敛速度和性能。通常需要在训练过程中不断尝试不同的学习速率值,以找到合适的值。
def two_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):
"""
参数:
X——输入数据,形状(n_X,示例数)
Y——真正的“标签”矢量(如果是猫,则包含1,如果不是猫,则为0),形状(1,示例数)
layers_dims——层的尺寸(n_x,n_h,n_y)
num_iterrations—优化循环的迭代次数
learning_rate——梯度下降更新规则的学习率
print_cost——如果设置为True,则将每100次迭代打印一次成本
返回:
parameters——包含W1、W2、b1和b2的字典
"""
np.random.seed(1)
grads = {}
costs = [] # 跟踪cost
m = X.shape[1] # 例子数量
(n_x, n_h, n_y) = layers_dims
def two_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):
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
parameters = initialize_parameters(n_x, n_h, n_y)
# 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, W2, b2". Output: "A1, cache1, A2, cache2".
A1, cache1 = linear_activation_forward(X, W1, b1, "relu")
A2, cache2 = linear_activation_forward(A1, W2, b2, "sigmoid")
# Compute cost
cost = compute_cost(A2, Y)
# 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".
dA1, dW2, db2 = linear_activation_backward(dA2, cache2, "sigmoid")
dA0, dW1, db1 = linear_activation_backward(dA1, cache1, "relu")
# 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.
parameters = update_parameters(parameters, grads, learning_rate)
# Retrieve W1, b1, W2, b2 from parameters
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
# Print the cost every 100 iterations
if print_cost and i % 100 == 0 or i == num_iterations - 1:
print("Cost after iteration {}: {}".format(i, np.squeeze(cost)))
if i % 100 == 0 or i == num_iterations:
costs.append(cost)
return parameters, costs
def plot_costs(costs, learning_rate=0.0075):
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
测试:
parameters, costs = two_layer_model(train_x, train_y, layers_dims = (n_x, n_h, n_y), num_iterations = 2, print_cost=False)
print("Cost after first iteration: " + str(costs[0]))
two_layer_model_test(two_layer_model)
结果
4.1 训练模型
如果您的代码通过了上一个单元格,请运行下面的代码来训练您的参数。每次迭代的成本都应该降低。运行2500次迭代可能需要长达5分钟的时间。
parameters, costs = two_layer_model(train_x, train_y, layers_dims = (n_x, n_h, n_y), num_iterations = 2500, print_cost=True)
plot_costs(costs, learning_rate)
您成功地训练了模型。幸好您构建了一个vectorized implementation!否则,训练这个可能需要10倍的时间。现在,您可以使用经过训练的参数对数据集中的图像进行分类。要查看您对训练集和测试集的预测,请运行下面的代码:
predictions_train = predict(train_x, train_y, parameters)
predictions_test = predict(test_x, test_y, parameters)
您可能会注意到,在较少的迭代次数(比如1500次)上运行模型可以在测试集上获得更好的准确性。这被称为“early stopping”,您将在下一课程中了解更多信息。early stopping是防止过度拟合的一种方法。
5.L-layer Neural Network
Exercise 2 - L_layer_model
layers_dims = [12288, 20, 7, 5, 1] # 4-layer model
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):
"""
实现L层神经网络:[LINEAR->RELU]*(L-1)->LINAR->SIGMOID。
参数:
X——输入数据,形状(n_X,示例数)
Y——真正的“标签”矢量(如果是猫,则包含1,如果不是猫,则为0),形状(1,示例数)
layers_dims——包含输入大小和每个层大小的列表,长度为(层数+1)。
learning_rate——梯度下降更新规则的学习率
num_iterrations—优化循环的迭代次数
print_cost——如果为True,则每100步打印一次成本
返回:
parameters——模型学习的参数。然后可以使用它们进行预测。
"""
np.random.seed(1)
costs = [] # 追踪cost
np.random.seed(1)
costs = [] # keep track of cost
# Parameters initialization.
parameters = initialize_parameters_deep(layers_dims)
# Loop (gradient descent)
for i in range(0, num_iterations):
# Forward propagation: [LINEAR -> RELU]*(L-1) -> LINEAR -> SIGMOID.
AL, caches = L_model_forward(X, parameters)
# Compute cost.
cost = compute_cost(AL, Y)
# Backward propagation.
grads = L_model_backward(AL, Y, caches)
# Update parameters.
parameters = update_parameters(parameters, grads, learning_rate)
# Print the cost every 100 iterations
if print_cost and i % 100 == 0 or i == num_iterations - 1:
print("Cost after iteration {}: {}".format(i, np.squeeze(cost)))
if i % 100 == 0 or i == num_iterations:
costs.append(cost)
return parameters, costs
测试:
parameters, costs = L_layer_model(train_x, train_y, layers_dims, num_iterations = 1, print_cost = False)
print("Cost after first iteration: " + str(costs[0]))
L_layer_model_test(L_layer_model)
结果
5.1 Train the model
parameters, costs = 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)
6.结果分析
首先,看看L层模型标记错误的一些图像。这将显示一些标签错误的图像。
print_mislabeled_images(classes, test_x, test_y, pred_test)
模型在某些类型的图像上往往表现不佳,包括:
猫身体处于异常位置
猫出现在类似颜色的背景下
不同寻常的猫的颜色和种类
相机角度
图片的亮度
比例变化(图片中猫很大或很小)
7.测试自己的照片
您可以使用自己的图像来测试模型的输出。要执行此操作,请执行以下步骤:
点击本笔记本上栏的“文件”,然后点击“打开”进入Coursera Hub。
将您的图像添加到此Jupyter笔记本的目录中的“images”文件夹中
在以下代码中更改图像的名称
运行代码并检查算法是否正确(1=猫,0=非猫)
my_image = "my_image.jpg" # 将引号内的内容改为自己照片的名字
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(Image.open(fname).resize((num_px, num_px)))
plt.imshow(image)
image = image / 255.
image = image.reshape((1, num_px * num_px * 3)).T
my_predicted_image = predict(image, my_label_y, parameters)
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.")