deeplearning.ai深度学习——构建一个LR分类器来识别猫

Logistic Regression with a Neural Network mindset

目录

1 - Packages

2 - Overview of the Problem set

3 - General Architecture of the learning algorithm

4 - Building the parts of our algorithm

4.1 - Helper functions

4.2 - Initializing parameters

4.3 - Forward and Backward propagation

5 - Merge all functions into a model

6 - Further analysis (optional/ungraded exercise)

7 - Test with your own image (optional/ungraded exercise)


这节作业会学到:

  • 构建学习算法的通用架构,包括:初始化参数、计算损失函数及其梯度、使用优化算法(梯度下降)
  • 按正确的顺序将上述所有三个函数组合在主模型函数中

 

1 - Packages

首先,运行下面的单元来导入在这个作业中需要的所有包:

  • numpy是使用python进行科学计算的基础包。
  • h5py是一个与存储在h5文件中的与数据集交互的通用包。
  • Matplotlib是一个著名的用Python绘制图形的库。
  • 这里使用pil和scipy并用你自己的图片测试你的模型。
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset

%matplotlib inline

 

2 - Overview of the Problem set

你的数据集(“data.h5”)包含:

  • 训练集,m_train个图片,标记了猫(y=1)或非猫(y=0)。
  • 测试集,m_test个图片的标记,标记为猫或非猫。
  • 每张图片的shape都为(num_px, num_px, 3),其中3表示3通道(RGB)。因此,每张图都是方形的,即长宽都为num_px。

构建一个简单的图像识别算法,可以正确地将图片分类为猫或非猫。

运行以下代码加载数据:

# Loading the data (cat/non-cat)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
(209, 64, 64, 3)
(1, 209)
(50, 64, 64, 3)
(1, 50)
[b'non-cat' b'cat']

我们在图像数据集(训练和测试)的末尾添加了“_orig”,因为我们要对它们进行预处理。在预处理之后,我们将以train_set_x和test_set_x结束(标签train_set_y和test_set_y不需要任何预处理)。

来看一个图片的例子:

# Example of a picture
index = 99
plt.imshow(train_set_x_orig[index])
print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") +  "' picture.")
y = [0], it's a 'non-cat' picture.

deeplearning.ai深度学习——构建一个LR分类器来识别猫

练习:得到下列值:

  • m_train(训练样本的数量)
  • m_test(测试样本的数量)
  • num_px(训练图片的长宽)

train_set_x_orig是一个形状为(m_train, num_px, num_px, 3)的numpy数组,例如,你可以通过train_set_x_orig.shape[0]得到m_train的值。

### START CODE HERE ### (≈ 3 lines of code)
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[2]
### END CODE HERE ###

print ("Number of training examples: m_train = " + str(m_train))
print ("Number of testing examples: m_test = " + str(m_test))
print ("Height/Width of each image: num_px = " + str(num_px))
print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")
print ("train_set_x shape: " + str(train_set_x_orig.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x shape: " + str(test_set_x_orig.shape))
print ("test_set_y shape: " + str(test_set_y.shape))
Number of training examples: m_train = 209
Number of testing examples: m_test = 50
Height/Width of each image: num_px = 64
Each image is of size: (64, 64, 3)
train_set_x shape: (209, 64, 64, 3)
train_set_y shape: (1, 209)
test_set_x shape: (50, 64, 64, 3)
test_set_y shape: (1, 50)

为了方便,可以reshape图片的形状(num_px, num_px, 3)变为(num_px*num_px*3, 1),之后,训练集和测试集就是一个每个列向量都是一个扁平图像的numpy数组了,且有m_train(训练集是m_test)个列向量。

练习:对训练集和测试集数据进行reshape,使其形状(num_px, num_px, 3)扁平化为一个向量(num_px*num_px*3, 1)。

# Reshape the training and test examples

### START CODE HERE ### (≈ 2 lines of code)
train_set_x_flatten = train_set_x_orig.reshape(m_train, num_px*num_px*3).T
test_set_x_flatten = test_set_x_orig.reshape(m_test, num_px*num_px*3).T
### END CODE HERE ###

print ("train_set_x_flatten shape: " + str(train_set_x_flatten.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x_flatten shape: " + str(test_set_x_flatten.shape))
print ("test_set_y shape: " + str(test_set_y.shape))
print ("sanity check after reshaping: " + str(train_set_x_flatten[0:5,0]))
train_set_x_flatten shape: (12288, 209)
train_set_y shape: (1, 209)
test_set_x_flatten shape: (12288, 50)
test_set_y shape: (1, 50)
sanity check after reshaping: [17 31 56 22 33]

为了表示彩色图像,必须为每个像素指定红色、绿色和蓝色通道(RGB),因此像素值实际上是一个从0到255的三个数字的矢量。

机器学习中一个常见的预处理步骤是将数据集居中并标准化,这意味着从每个样本中减去整个numpy数组的平均值,然后将每个样本除以整个numpy数组的标准差。但是对于图片数据集来说,它更简单、更方便,仅仅将数据集的每一行除以255(像素通道的最大值)就可以有比较好的效果:

train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.

需要记住的是:

对于一个新的数据集,常用的预处理步骤为:

  • 得到问题的尺寸和形状(m_train, m_test, num_px, ...)
  • reshape数据集使得每个样本数据变为一个向量(num_px*num_px*3, 1)
  • 标准化数据

 

3 - General Architecture of the learning algorithm

使用神经网络的思维方式建立一个逻辑回归。下图解释了为什么逻辑回归实际上是一个非常简单的神经网络:

deeplearning.ai深度学习——构建一个LR分类器来识别猫

算法的数学表示:

deeplearning.ai深度学习——构建一个LR分类器来识别猫

关键步骤:在练习中,执行以下步骤:

  • 初始化模型的参数
  • 通过最小化损失函数来学习模型参数
  • 使用学习到的参数在测试集上预测
  • 分析结果并总结

 

4 - Building the parts of our algorithm

构造一个神经网络的主要步骤:

  1. 定义模型结构,例如输入特征的数量
  2. 初始化模型的参数
  3. 循环:
  • 计算当前损失(前向传播)
  • 计算当前梯度(反向传播)
  • 更新参数(梯度下降)

通常的做法是单独构建1-3,并将它们集成到model()函数中。

4.1 - Helper functions

练习:实现sigmoid()函数,因为需要计算deeplearning.ai深度学习——构建一个LR分类器来识别猫

s = 1 / (1 + np.exp(-z))
sigmoid([0, 2]) = [0.5        0.88079708]

4.2 - Initializing parameters

练习:在下面的单元中实现参数初始化,需要将w初始化为一个全零向量。

w = np.zeros(shape=(dim, 1))
b = 0
w = [[0.]
 [0.]]
b = 0

对于图片输入,w的形状是(num_px*num_px*3, 1)。

4.3 - Forward and Backward propagation

练习:实现propagate()函数,用于计算损失函数及其梯度。

提示:

deeplearning.ai深度学习——构建一个LR分类器来识别猫

# FORWARD PROPAGATION (FROM X TO COST)
A = sigmoid(np.dot(w.T, X) + b)
cost = -np.mean(Y * np.log(A) + (1 - Y) * np.log(1 - A))
    
# BACKWARD PROPAGATION (TO FIND GRAD)
dw = np.dot(X, (A - Y).T) / m
db = np.mean(A - Y)
dw = [[0.99993216]
 [1.99980262]]
db = 0.49993523062470574
cost = 6.000064773192205

优化:使用梯度下降更新参数

练习:写出优化函数,目标是通过最小化损失函数J来学习w和b。对于参数deeplearning.ai深度学习——构建一个LR分类器来识别猫,更新规则是deeplearning.ai深度学习——构建一个LR分类器来识别猫,其中deeplearning.ai深度学习——构建一个LR分类器来识别猫是学习率。

costs = []
    
for i in range(num_iterations):
        
    # Cost and gradient calculation (≈ 1-4 lines of code)
    grads, cost = propagate(w, b, X, Y)
        
    # Retrieve derivatives from grads
    dw = grads["dw"]
    db = grads["db"]
        
    # update rule (≈ 2 lines of code)
    w = w - learning_rate * dw
    b = b - learning_rate * db
w = [[0.1124579 ]
 [0.23106775]]
b = 1.5593049248448891
dw = [[0.90158428]
 [1.76250842]]
db = 0.4304620716786828

练习:之前的函数会输出学习到的参数w和b,我们已经能够使用w和b来预测数据X的标签了,实现predict()函数,两个步骤:

  1. 计算deeplearning.ai深度学习——构建一个LR分类器来识别猫
  2. 将A转换为0(如果**值小于0.5)或1(如果**值大于0.5),将预测值存储在向量Y_prediction中,可以在for循环中使用if/else。
# Compute vector "A" predicting the probabilities of a cat being present in the picture
A = sigmoid(np.dot(w.T, X) + b)

for i in range(A.shape[1]):
        
    # Convert probabilities A[0,i] to actual predictions p[0,i]
    if A[0][i] <= 0.5:
        Y_prediction[0][i] = 0
    else:
        Y_prediction[0][i] = 1
predictions = [[1. 1.]]

需要记住的是:

已经实现了如下函数:

  • 初始化(w, b)
  • 迭代优化损失来学习参数(w, b),包括计算损失及其梯度和利用梯度下降更新参数
  • 对于给定的一组样本,使用学习到的参数(w, b)来预测标签

 

5 - Merge all functions into a model

练习:实现model函数,使用下列记号:

  • Y_prediction:在测试集上的预测值
  • Y_prediction_train:在训练集上的预测值
  • w,costs,grads:optimize()函数的输出
# initialize parameters with zeros (≈ 1 line of code)
w, b = initialize_with_zeros(X_train.shape[0])

# Gradient descent (≈ 1 line of code)
parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
    
# Retrieve parameters w and b from dictionary "parameters"
w = parameters["w"]
b = parameters["b"]
    
# Predict test/train set examples (≈ 2 lines of code)
Y_prediction_test = predict(w, b, X_test)
Y_prediction_train = predict(w, b, X_train)
Cost after iteration 0: 0.693147
Cost after iteration 100: 0.584508
Cost after iteration 200: 0.466949
Cost after iteration 300: 0.376007
Cost after iteration 400: 0.331463
Cost after iteration 500: 0.303273
Cost after iteration 600: 0.279880
Cost after iteration 700: 0.260042
Cost after iteration 800: 0.242941
Cost after iteration 900: 0.228004
Cost after iteration 1000: 0.214820
Cost after iteration 1100: 0.203078
Cost after iteration 1200: 0.192544
Cost after iteration 1300: 0.183033
Cost after iteration 1400: 0.174399
Cost after iteration 1500: 0.166521
Cost after iteration 1600: 0.159305
Cost after iteration 1700: 0.152667
Cost after iteration 1800: 0.146542
Cost after iteration 1900: 0.140872
train accuracy: 99.04306220095694 %
test accuracy: 70.0 %

可以看出该模型明显过拟合了训练数据。之后将学习如何减少过度拟合,例如使用正则化。使用下面的代码(并更改索引),您可以查看测试集图片上的预测。

# Example of a picture that was wrongly classified.
index = 6
plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))
print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[int(d["Y_prediction_test"][0,index])].decode("utf-8") +  "\" picture.")
y = 1, you predicted that it is a "non-cat" picture.

deeplearning.ai深度学习——构建一个LR分类器来识别猫

画出损失函数及其梯度:

# Plot learning curve (with costs)
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(d["learning_rate"]))
plt.show()

deeplearning.ai深度学习——构建一个LR分类器来识别猫

可以看到损失在下降,它表明参数正在被学习。然而,可以在训练集中对模型进行更多的训练。尝试增加上面的迭代次数,然后重新运行。你可能会看到训练集的精度上升,但测试集的精度下降。这被称为过拟合。

 

6 - Further analysis (optional/ungraded exercise)

学习率的选择

提醒:为了使梯度下降正常工作,你必须明智地选择学习率。学习率α决定了我们更新参数的速度。如果学习率太大,我们可能会“过冲”最优值。同样,如果它太小,我们将需要太多的迭代来收敛到最佳值。这就是为什么使用调整好的学习速度是至关重要的。

将模型的学习曲线与几种学习速率选择进行比较:

learning_rates = [0.01, 0.005, 0.001, 0.0005, 0.0001]
models = {}
for i in learning_rates:
    print ("learning rate is: " + str(i))
    models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)
    print ('\n' + "-------------------------------------------------------" + '\n')

for i in learning_rates:
    plt.plot(np.squeeze(models[str(i)]["costs"]), label= str(models[str(i)]["learning_rate"]))

plt.ylabel('cost')
plt.xlabel('iterations')

legend = plt.legend(loc='upper center', shadow=True)
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.show()
learning rate is: 0.01
train accuracy: 99.52153110047847 %
test accuracy: 68.0 %

-------------------------------------------------------

learning rate is: 0.005
train accuracy: 97.60765550239235 %
test accuracy: 70.0 %

-------------------------------------------------------

learning rate is: 0.001
train accuracy: 88.99521531100478 %
test accuracy: 64.0 %

-------------------------------------------------------

learning rate is: 0.0005
train accuracy: 82.77511961722487 %
test accuracy: 56.0 %

-------------------------------------------------------

learning rate is: 0.0001
train accuracy: 68.42105263157895 %
test accuracy: 36.0 %

-------------------------------------------------------

deeplearning.ai深度学习——构建一个LR分类器来识别猫

解释:

  • 不同的学习率产生不同的损失,从而产生不同的预测结果
  • 如果学习率太大(0.01),损失可能会上下波动。它甚至可能会出现diverge(尽管在本例中,使用0.01最终仍然会获得很好的损失值)。
  • 低损失并不意味着更好的模型。你得检查一下是否有可能过拟合。当训练精度远远高于测试精度时,就会发生这种情况。
  • 在深度学习中,通常建议:
  1. 选择更好地最小化损失函数的学习率。
  2. 如果模型过拟合,使用其他技术来减少过拟合。

 

7 - Test with your own image (optional/ungraded exercise)

可以使用自己的图像并查看模型的输出:

## START CODE HERE ## (PUT YOUR IMAGE NAME) 
my_image = "my_image.jpg"   # change this to the name of your image file 
## END CODE HERE ##

# We preprocess the image to fit your algorithm.
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T
my_predicted_image = predict(d["w"], d["b"], my_image)

plt.imshow(image)
print("y = " + str(np.squeeze(my_predicted_image)) + ", your algorithm predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") +  "\" picture.")
y = 0.0, your algorithm predicts a "non-cat" picture.

deeplearning.ai深度学习——构建一个LR分类器来识别猫

y = 1.0, your algorithm predicts a "cat" picture.

deeplearning.ai深度学习——构建一个LR分类器来识别猫

 

这节作业中应该记住的:

  1. 对数据集进行预处理很重要
  2. 分别实现每个函数:initialize(), propagate(), optimize(),然后构造一个model()函数
  3. 调整学习率(这是一个“超参数”的例子)可以对算法产生很大的影响。