2020-6-6 吴恩达-NN&DL-w2 NN基础(课后编程-Logistic Regression with a Neural Network mindset)

原文链接

本练习将使用逻辑回归分类来识别猫。

这项作业将指导你如何用NN的思维方式来完成任务,也将培养你对DL的直觉。

请不要在代码中使用循环(for/while),除非作业明确要求你这样做。

通过作业你可以学习如何建立学习算法的总体架构,包含

  • 初始化参数
  • 计算成本函数和它的参数
  • 使用优化算法(梯度下降)

1.本文涉及的基本库

本作业涉及以下几个python库

  • numpy :是用Python进行科学计算的基本软件包。
  • h5py:是与H5文件中存储的数据集进行交互的常用软件包。
  • matplotlib:是一个著名的库,用于在Python中绘制图表。
  • PIL和scipy:处理图片。可以使用你自己的图片来测试你的模型。
  • lr_utils.py :本文包含的代码文件,包含一个load_dataset()函数,可以用来加载资料中提供的图像数据。具体如下

2. 训练集/测试集概况和预处理

import numpy as np
import h5py
    
    
def load_dataset():
    train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
    train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features
    train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels

    test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r")
    test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features
    test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels

    classes = np.array(test_dataset["list_classes"][:]) # the list of classes
    
    train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
    test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
    
    return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes

说明

  • train_catvnoncat.h5,包含训练图片集合,标签为cat (y=1) 或者 non-cat (y=0),209张
  • test_catvnoncat.h5,包含测试图片集合,50张
  • 图片都是64x64,正方形,3通道 (RGB),高和宽都是num_px
  • train_set_x_orig/test_set_x_orig :训练/测试集里面的图像数据。每一行都是一个表示图像的数组。
  • train_set_y_orig/test_set_y_orig :训练/测试集的图像对应的分类值,0和1
  • classes : bytes类型的两个字符串数据,数据为:[b’non-cat’ b’cat’]。

加载数据,调用方法

train_set_x_orig , train_set_y , test_set_x_orig , test_set_y , classes = load_dataset()

1-1.弄清数据集维度

你可以用以下方式查看一下某一张图像

# Example of a picture
index = 25
plt.imshow(train_set_x_orig[index])
plt.show() #我的代码必须加这一句才能把plt.imshow()处理后的内容显示出来
print ("y = " + str(train_set_y[:,index]) + ", it's a '" + classes[np.squeeze(train_set_y[:,index])].decode("utf-8") +  "' picture.")

np.squeeze()函数可以删除数组形状中的单维度条目,即把shape中为1的维度去掉,但是对非单维的维度不起作用。

运行后,图像显示如下
在这里插入图片描述

控制台输出分类,是猫

y = [1], it's a 'cat' picture.

如果是训练集,index=65
在这里插入图片描述

控制台显示,不是猫

y = [0], it's a 'non-cat' picture.

注意

DL的许多软件问题来自于矩阵/向量维度不匹配。如果你能保持你的矩阵/向量的维度是准确的,你将在很大程度上消除许多错误。

请尝试找到以下几个值,以便了解加载图像数据集具体情况

  • m_train :训练集图片的数量。希望输出209
  • m_test :测试集图片的数量。希望输出50
  • num_px : 训练/测试集中图片的高度和宽度。希望输出64

代码如下

m_train = train_set_y.shape[1] #训练集里图片的数量。
m_test = test_set_y.shape[1] #测试集里图片的数量。
num_px = train_set_x_orig.shape[1] #训练、测试集里面的图片的宽度和高度(均为64x64)。

print ("训练集的数量: m_train = " + str(m_train))
print ("测试集的数量 : m_test = " + str(m_test))
print ("图片的高和宽 : num_px = " + str(num_px))
print ("图片的大小 : (" + str(num_px) + ", " + str(num_px) + ", 3)")
print ("训练集_图片的维数 : " + str(train_set_x_orig.shape))
print ("训练集_标签的维数 : " + str(train_set_y.shape))
print ("测试集_图片的维数: " + str(test_set_x_orig.shape))
print ("测试集_标签的维数: " + str(test_set_y.shape))

运行结果

训练集的数量: m_train = 209
测试集的数量 : m_test = 50
图片的高和宽 : num_px = 64
图片的大小 : (64, 64, 3)
训练集_图片的维数 : (209, 64, 64, 3)
训练集_标签的维数 : (1, 209)
测试集_图片的维数: (50, 64, 64, 3)
测试集_标签的维数: (1, 50)

1-2.重构数据集

为了方便,你需要把维度为(64,64,3)的图像重新构造为(64 x 64 x 3,1)的numpy数组。(乘以3的原因是每张图片是由64x64像素构成的,而每个像素点由(R,G,B)三原色构成的)。reshape之后,训练和测试数据集是一个numpy数组,每列代表一个平坦的图像flattened image。numpy数组会有m_train(m_test)列。

小技巧

当你想将形状(a,b,c,d)的矩阵X平铺成形状(b * c * d,a)的矩阵X_flatten时,可以使用以下代码

X_flatten = X.reshape(X.shape[0], -1).T      # X.T is the 转置 of X

将训练集/测试集重构:降低维度,并转置。代码如下

# Reshape the training and test examples

### START CODE HERE ### (≈ 2 lines of code)
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).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))

控制台输出

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)

因为我们已经知道train_set_x_orig.shape=(209, 64, 64, 3),所以train_set_x_flatten.shape结果就是(64643,209)=(12288,209)。

1-3.数据预处理

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

DL中一个常见的预处理步骤是将数据集居中并标准化。
这意味着从每个示例中减去整个numpy数组的平均值,然后将每个示例除以整个numpy数组的标准差。但对于图片数据集来说,它更简单、更方便,并且几乎可以将数据集的每一行除以255(像素通道的最大值)。因为在RGB中不存在比255大的数据,我们可以通过除以255,让标准化的数据位于[0,1]之间。

标准化预处理图像代码如下

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

总结

数据集预处理步骤包含

  • 弄清训练集/测试集的维度,形状(例如:m_train, m_test, num_px)
  • 重构数据集,把每个示例变为一个向量,大小为(num_px * num_px * 3, 1)
  • 标准化数据

3.学习算法的一般结构

现在可以设计一个简单的算法来区分猫图片和非猫图片了。

你将利用NN思维来构筑逻辑回归。下图解释了为什么逻辑回归实际上是一个非常简单的神经网络!
在这里插入图片描述

算法的数学表达式如下:
对于一个样本 x(i)x^{(i)},逻辑回归算法前向传播,每个神经元分两步完成
步骤1,z(i)=wTx(i)+bz^{(i)}=w^Tx^{(i)}+b
步骤2,y(i)=a(i)=sigmoid(z(i))y^{​(i)}=a^{(i)}=sigmoid(z^{(i)}),激活函数输出预测值

得到损失函数,预测分类和实际类别偏差
L(a(i),y(i))=y(i)log(a(i))(1y(i))log(1a(i))L(a^{(i)},y^{(i)})=−y^{(i)}log(a^{(i)})−(1−y^{(i)})log(1−a^{(i)})

通过对所有训练样本损失求和来计算成本:
J=1mi=1mL(a(i),y(i))J=\frac 1m \sum_{i=1}^m​L(a^{(i)},y^{(i)})

本练习中,需要实现算法的以下关键步骤

  • 初始化模型参数
  • 通过最小化成本来学习模型的参数
  • 使用学习好的参数来进行预测(在测试集上)
  • 分析结果,得出结论

4.实现算法

建立NN的主要步骤包含

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

通常我们会分别建立上面3步,然后集成到一个函数中–model()。

4.1辅助函数-sigmoid()

实现函数sigmoid()。如上面的图中所示,最终你需要通过计算sigmoid(wTx+b)sigmoid( w^T x + b)来完成分类预测。

sigmoid()实现代码如下

# GRADED FUNCTION: sigmoid

def sigmoid(z):
    """
    Compute the sigmoid of z 计算sigmoid(z)

    Arguments:
    x -- A scalar or numpy array of any size. 任意大小的标量或者numpy数组

    Return:
    s -- sigmoid(z)
    """

    ### START CODE HERE ### (≈ 1 line of code)
    s = 1 / (1 + np.exp(-z))
    ### END CODE HERE ###
    
    return s

测试一下

print ("sigmoid(0) = " + str(sigmoid(0)))
print ("sigmoid(9.2) = " + str(sigmoid(9.2)))

运行结果

sigmoid(0) = 0.5
sigmoid(9.2) = 0.999898970806

sigmoid函数图像如下,结果与其相符合。
在这里插入图片描述

4.2初始化参数

你需要把ww初始化为0向量,可以通过np.zeros()函数来实现。

代码如下

# GRADED FUNCTION: initialize_with_zeros

def initialize_with_zeros(dim):
    """
    This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.
    此函数为w创建一个维度为(dim,1)的0向量,并将b初始化为0。
    
    Argument:
    dim -- size of the w vector we want (or number of parameters in this case)
    我们想要的向量w的大小(或者参数数量)
    
    Returns:
    w -- initialized vector of shape (dim, 1) 维度为(dim,1)的初始化向量
    b -- initialized scalar (corresponds to the bias) 初始化的标量(对应于偏差)
    """
    
    ### START CODE HERE ### (≈ 1 line of code)
    w = np.zeros(shape=(dim, 1))
    b = 0
    ### END CODE HERE ###

    #使用断言来确保数据是正确的
    assert(w.shape == (dim, 1))
    assert(isinstance(b, float) or isinstance(b, int))
    
    return w, b

调用方法如下

dim = 2
w, b = initialize_with_zeros(dim)
print ("w = " + str(w))
print ("b = " + str(b))

运行结果

w = [[ 0.]
 [ 0.]]
b = 0

在前面已经提醒过,为了减少错误,需要时时保持你的矩阵/向量的维度是准确的。
本次练习中,对于图像输入,ww的维度应该是 (num_px * num_px * 3, 1)。因为我们在step1-2时候,为了方便,已经把维度为(64,64,3)的图像重新构造为(64 x 64 x 3,1)的numpy数组。

4.3前向和反向传播

你已经完成了参数初始化。现在你可以进入前向和反向传播步骤来学习参数。

实现propagate() 函数来计算成本(前向)和梯度(反向)。

提示

前向传播

  • 获得输入X
  • 计算A=σ(wTX+b)=(a(0),a(1),...,a(m1),a(m))A = \sigma(w^T X + b) = (a^{(0)}, a^{(1)}, ..., a^{(m-1)}, a^{(m)})
  • 计算成本函数 J=1mi=1my(i)log(a(i))(1y(i))log(1a(i))J=-\frac 1m \sum_{i=1}^my^{(i)}log(a^{(i)})−(1−y^{(i)})log(1−a^{(i)})

反向传播,在这里有2个公式你会使用到
Jw=1mX(AY)T(7) \frac{\partial J}{\partial w} = \frac{1}{m}X(A-Y)^T\tag{7}Jb=1mi=1m(a(i)y(i))(8) \frac{\partial J}{\partial b} = \frac{1}{m} \sum_{i=1}^m (a^{(i)}-y^{(i)})\tag{8}

实现代码

# GRADED FUNCTION: propagate

def propagate(w, b, X, Y):
    """
    Implement the cost function and its gradient for the propagation explained above

    Arguments:
    w -- weights, a numpy array of size (num_px * num_px * 3, 1) 
           权重,numpy数组,维度(num_px * num_px * 3,1)
    b -- bias, a scalar 偏差,标量
    X -- data of size (num_px * num_px * 3, number of examples)  
           维度为(num_px * num_px * 3,训练数量)
    Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)“标签”
           矢量(如果非猫则为0,如果是猫则为1),维度为(1,训练数据数量)

    Return:
    cost -- negative log-likelihood cost for logistic regression 逻辑回归的负对数似然成本
    dw -- gradient of the loss with respect to w, thus same shape as w 关于w的损失梯度,与w相同的形状
    db -- gradient of the loss with respect to b, thus same shape as b 关于b的损失梯度,与b的形状相同
    
    Tips:
    - Write your code step by step for the propagation
    """
    
    m = X.shape[1]
    
    # FORWARD PROPAGATION (FROM X TO COST) 正向传播
    ### START CODE HERE ### (≈ 2 lines of code)
    A = sigmoid(np.dot(w.T, X) + b)  # compute activation
    cost = (- 1 / m) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A)))  # compute cost
    ### END CODE HERE ###
    
    # BACKWARD PROPAGATION (TO FIND GRAD) 反向传播
    ### START CODE HERE ### (≈ 2 lines of code)
    dw = (1 / m) * np.dot(X, (A - Y).T)
    db = (1 / m) * np.sum(A - Y)
    ### END CODE HERE ###

   #使用断言确保我的数据是正确的
    assert(dw.shape == w.shape)
    assert(db.dtype == float)
    cost = np.squeeze(cost)
    assert(cost.shape == ())
    
    #创建一个字典,把dw和db保存起来。
    grads = {"dw": dw,
             "db": db}
    
    return grads, cost

测试一下

w, b, X, Y = np.array([[1], [2]]), 2, np.array([[1,2], [3,4]]), np.array([[1, 0]])
grads, cost = propagate(w, b, X, Y)
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))
print ("cost = " + str(cost))

运行结果

dw = [[ 0.99993216]
 [ 1.99980262]]
db = 0.499935230625
cost = 6.00006477319

4.3.1优化

到目前为止,你已经完成了初始化参数,计算了成本和它的梯度。
现在你需要使用梯度来更新参数。

我们的目标是通过最小化成本函数 JJ 来学习 wwbb 。对于参数 θθ ,更新规则是 θ=θα dθ\theta = \theta - \alpha \text{ } d\theta,其中 αα 是学习率。

# GRADED FUNCTION: optimize

def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
    """
    This function optimizes w and b by running a gradient descent algorithm
    此函数通过运行梯度下降算法来优化w和b
    
    Arguments:
    w -- weights, a numpy array of size (num_px * num_px * 3, 1)
    b -- bias, a scalar
    X -- data of shape (num_px * num_px * 3, number of examples)
    Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)
    num_iterations -- number of iterations of the optimization loop 优化循环的迭代次数
    learning_rate -- learning rate of the gradient descent update rule 梯度下降更新规则的学习率
    print_cost -- True to print the loss every 100 steps 每100步打印一次损失值
    
    Returns:
    params -- dictionary containing the weights w and bias b 包含权重w和偏差b的字典
    grads -- dictionary containing the gradients of the weights and bias with respect to the cost function
                  包含权重和偏差相对于成本函数的梯度的字典
    costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve.
                 优化时计算的所有成本列表,将用于绘制学习曲线。

    Tips: 提示
    You basically need to write down two steps and iterate through them:
    你通常需要写下两个步骤并遍历它们:
        1) Calculate the cost and the gradient for the current parameters. Use propagate().
            使用propagate(),计算当前参数的成本和梯度。
        2) Update the parameters using gradient descent rule for w and b.
            使用w和b的梯度下降法则更新参数。
    """
    
    costs = []
    
    for i in range(num_iterations):
        
        
        # Cost and gradient calculation (≈ 1-4 lines of code)
        ### START CODE HERE ### 
        grads, cost = propagate(w, b, X, Y)
        ### END CODE HERE ###
        
        # Retrieve derivatives from grads
        dw = grads["dw"]
        db = grads["db"]
        
        # update rule (≈ 2 lines of code)
        ### START CODE HERE ###
        w = w - learning_rate * dw  # need to broadcast
        b = b - learning_rate * db
        ### END CODE HERE ###
        
        # Record the costs
        if i % 100 == 0:
            costs.append(cost)
        
        # Print the cost every 100 training examples
        if print_cost and i % 100 == 0:
            print ("Cost after iteration %i: %f" % (i, cost))
    
    params = {"w": w,
              "b": b}
    
    grads = {"dw": dw,
             "db": db}
    
    return params, grads, costs

测试一下优化函数

params, grads, costs = optimize(w, b, X, Y, num_iterations= 100, learning_rate = 0.009, print_cost = False)

print ("w = " + str(params["w"]))
print ("b = " + str(params["b"]))
print ("dw = " + str(grads["dw"]))
print ("db = " + str(grads["db"]))

运行结果

w = [[ 0.1124579 ]
 [ 0.23106775]]
b = 1.55930492484
dw = [[ 0.90158428]
 [ 1.76250842]]
db = 0.430462071679

函数迭代了100次,学习率0.009,不打印成本,最终输出学习好的wwbb

利用wwbb,我们就可以预测数据集X的分类标签了。

我们构建一个predict()函数来预测。计算预测有2个步骤

  • 计算Y^=A=σ(wTX+b)\hat{Y} = A = \sigma(w^T X + b)
  • 将a的值变为0(如果激活值<= 0.5)或者为1(如果激活值> 0.5)。把预测结果保存到向量Y_prediction。你可以通过for循环来实现(当然也有向量化方式可以实现,这里暂时不用)。

代码如下

# GRADED FUNCTION: predict

def predict(w, b, X):
    '''
    Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
    使用学习好的逻辑回归参数(w,b)预测标签是0还是1,
    
    Arguments:
    w -- weights, a numpy array of size (num_px * num_px * 3, 1)
    b -- bias, a scalar
    X -- data of size (num_px * num_px * 3, number of examples)
    
    Returns:
    Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X
                             包含X中所有图片的所有预测结果(0/1) 的一个numpy数组(向量)
    '''
    
    m = X.shape[1] #图片的数量
    Y_prediction = np.zeros((1, m))
    w = w.reshape(X.shape[0], 1)
    
    # Compute vector "A" predicting the probabilities of a cat being present in the picture
    # 计算预测猫在图片中出现的概率
    ### START CODE HERE ### (≈ 1 line of code)
    A = sigmoid(np.dot(w.T, X) + b)
    ### END CODE HERE ###
    
    for i in range(A.shape[1]):
        # Convert probabilities a[0,i] to actual predictions p[0,i]
        # #将概率a [0,i]转换为实际预测p [0,i]
        ### START CODE HERE ### (≈ 4 lines of code)
        Y_prediction[0, i] = 1 if A[0, i] > 0.5 else 0
        ### END CODE HERE ###
    
    #使用断言确保数据是正确的
    assert(Y_prediction.shape == (1, m))
    
    return Y_prediction

测试一下

print("predictions = " + str(predict(w, b, X)))

运行结果

predictions = [[ 1.  1.]]

注意,在前面我们已经赋值过了

w, b, X, Y = np.array([[1], [2]]), 2, np.array([[1,2], [3,4]]), np.array([[1, 0]])

输入矩阵X有2个样本,每个样本都有2个特征,2个样本的分类标签分别是1和0。只不过训练和测试用了同一个矩阵X,测试结果就有偏差了,输出的预测分类都是1。

5.把所有函数并入模型中

现在你可以按照正确的顺序将所有前面部分实现过的函数组合在一起,从而了解整个模型的结构。

5.1构建model函数

使用下面符号,构建model函数Implement the model function. Use the following notation:

  • Y_prediction:测试集的预测结果 for your predictions on the test set
  • Y_prediction_train:训练集的预测结果 for your predictions on the train set
  • w, costs, grads: optimize()函数输出

代码如下

# GRADED FUNCTION: model

def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False):
    """
    Builds the logistic regression model by calling the function you've implemented previously
    通过调用之前实现的函数来构建逻辑回归模型
    
    Arguments:
    X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)
	numpy的数组,维度为(num_px * num_px * 3,m_train)的训练集
    Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train)
	numpy的数组,维度为(1,m_train)(矢量)的训练标签集
    X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test)
	numpy的数组,维度为(num_px * num_px * 3,m_test)的测试集
    Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test)
	numpy的数组,维度为(1,m_test)的(向量)的测试标签集
    num_iterations -- hyperparameter representing the number of iterations to optimize the parameters
    	超参,表示用于优化参数的迭代次数
    learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize()
	超参,学习率
    print_cost -- Set to true to print the cost every 100 iterations 每100次迭代打印成本
    
    Returns:
    d -- dictionary containing information about the model. 包含有关模型信息的字典
    """
    
    ### START CODE HERE ###
    # 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和b
    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)

    ### END CODE HERE ###

    # Print train/test Errors
    # 打印训练后的准确率
    print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
    print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))

    
    d = {"costs": costs,
         "Y_prediction_test": Y_prediction_test, 
         "Y_prediction_train" : Y_prediction_train, 
         "w" : w, 
         "b" : b,
         "learning_rate" : learning_rate,
         "num_iterations": num_iterations}
    
    return d

基本步骤如下

  • 先初始化参数wwbb,initialize_with_zeros
  • 然后学习,获得学习好的wwbb,optimize
  • 预测训练和测试集,predict
  • 打印准确率,预测结果和实际标签的误差

测试一下

d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)

迭代2000次,学习率0.005
运行结果

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 %

迭代2000次后,成本下降并收敛。
最终训练集准确率99%,测试集正曲率70%。

训练集正确率接近100%。你的模型正在工作,并且具有足够高的容量来适应训练数据。
测试误差为70%。虑到我们使用的数据集很小,而且逻辑回归是一个线性分类器,所以对于这个简单的模型来说,这并不坏。

此外,你还可以看到,该模型显然过度拟合了训练数据。后面的课程会学习如何减少过度拟合,例如使用正则化。

5.2测试集图片预测

使用下面的代码(更改索引变量),你可以查看测试集图片上的预测。

index = 5
plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))
plt.show() #我的代码必须加这一句才能把plt.imshow()处理后的函数显示出来
print ("y = " + str(test_set_y[0, index]) + ", you predicted that it is a \"" + classes[d["Y_prediction_test"][0, index]].decode("utf-8") +  "\" picture.")

运行结果

y = 0, you predicted that it is a "cat" picture.

标签是0,但是预测结果是猫。显然,是错误的预测。你可以看一下图片,虽然有点模糊,不过看上去象是蝴蝶。

在这里插入图片描述

5.3绘制成本函数

optimize函数输出了学习过程中的成本,我们可以把它们绘制出来。

绘制成本,代码如下

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

运行后,成本曲线绘制图形如下

在这里插入图片描述

观察上图。
你可以看到成本在下降。这表明参数正在学习中。但是,你也明白,你可以在训练集上训练更多次的模型。尝试增迭代次数(例如:3000次)并运行,你可能会看到训练集的准确性上升,但测试集的准确性下降,这被称为过拟合

6.进阶分析

我们已经完成了第一个图像分类器模型。让我们进一步分析一下,并研究学习率α\alpha的可能选择。

为了让梯度下降起作用,我们必须聪明的选择学习速率。

学习率α\alpha 决定了我们更新参数的速度。如果学习率过高,我们可能会“超过”最优值。同样,如果它太小,我们将需要太多迭代才能收敛到最佳值。这就是为什么使用良好调整的学习率至关重要的原因。

让我们在模型中尝试3个不同的学习率,看看结果会怎么样。

代码如下

learning_rates = [0.01, 0.001, 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()

学习率分别是0.01, 0.001, 0.0001,运行结果如下

learning rate is: 0.01
train accuracy: 99.52153110047847 %
test accuracy: 68.0 %

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

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

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

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

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

在这里插入图片描述

说明:

  • 不同的学习率,成本和预测结果都不一样
  • 如果学习率太大(0.01),则成本可能上下波动。它甚至可能会发散(尽管在本例中,使用0.01最终还是会得到很好的成本值)。
  • 低成本并不意味着更好的模式。你得检查一下是否有过拟合可能。当训练准确率远高于测试准确率时就会发生这种情况。
  • DL中,通常推荐你
    • 选择能更好最小化成本的学习率
    • 如果模型过拟合了,请尝试用其他技术减少过拟合(后面课程介绍)

7.用你自己的图像测试预测效果

你可以尝试用你自己的图片来测试预测效果。

我在网上随便找了一张猫咪图片。
在这里插入图片描述

测试代码如下

# We preprocess the image to fit your algorithm.
fname = "images/" + my_image

#image = np.array(ndimage.imread(fname, flatten=False))
image = np.array(imageio.imread(fname))

#my_image = scipy.misc.imresize(image, size=(num_px, num_px)).reshape((1, num_px * num_px * 3)).T
my_image = np.array(Image.fromarray(image).resize((num_px, num_px),Image.ANTIALIAS)) #ANTIALIAS表示保留图片所有像素,不丢失原有像素
my_image = my_image.reshape((1, num_px * num_px * 3)).T

my_predicted_image = predict(d["w"], d["b"], my_image)

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

注意,这里代码和原文有改变。原因参见链接。主要是scipy库发生了变化。

运行原文代码,报错信息如下

NameError: name 'ndimage' is not defined
AttributeError: module 'scipy' has no attribute 'misc'

修改后的代码需要引入2个库

import imageio   
from PIL import Image     

运行代码后,结果如下

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

可以识别出是猫咪
在这里插入图片描述

8.完整代码

全部代码下载链接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章