NG深度学习第一门课作业1 构建一个逻辑回归分类器来识别猫

欢迎来到你的第一个(必需的)编程任务!你将建立一个逻辑回归分类器来识别猫。这项作业将带你逐步了解如何用神经网络思维来做这件事,因此也将磨练你对深度学习的直觉。

 

第一部分:导包

在开始之前,我们有需要引入的库:

numpy :是用Python进行科学计算的基本软件包。
h5py:是与H5文件中存储的数据集进行交互的常用软件包。
matplotlib:是一个著名的库,用于在Python中绘制图表。
lr_utils :在本文的资料包里,一个加载资料包里面的数据的简单功能的库。

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

 

第二部分:问题概述

1-加载数据

# Loading the data (cat/non-cat)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
print(train_set_x_orig.shape)
print(train_set_y.shape)
print(test_set_x_orig.shape)
print(test_set_y.shape)
print(classes)

结果:

(209, 64, 64, 3)
(1, 209)
(50, 64, 64, 3)
(1, 50)
[b'non-cat' b'cat']

含义:

  • train_set_x_orig :保存的是训练集里面的图像数据(本训练集有209张64x64的图像)。
  • train_set_y_orig :保存的是训练集的图像对应的分类值(【0 | 1】,0表示不是猫,1表示是猫)。
  • test_set_x_orig :保存的是测试集里面的图像数据(本训练集有50张64x64的图像)。
  • test_set_y_orig : 保存的是测试集的图像对应的分类值(【0 | 1】,0表示不是猫,1表示是猫)。
  • classes : 保存的是以bytes类型保存的两个字符串数据,数据为:[b’non-cat’ b’cat’]。

 

2-试着查看训练集中的随机一张照片,index可以输入在0-208之间,示例输入index=23

# Example of a picture
index = 23
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.

含义:

使用np.squeeze的目的是压缩维度,【未压缩】train_set_y[:,index]的值为[1] , 【压缩后】np.squeeze(train_set_y[:,index])的值为1。只有压缩后的值才能进行解码操作。

 

3-练习:查找以下值:

  • m_train :训练集里图片的数量。
  • m_test :测试集里图片的数量。
  • num_px : 训练、测试集里面的图片的宽度和高度(均为64x64)。

其中,train_set_x_orig 是一个维度为(m_​​train,num_px,num_px,3)的数组。

### 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[1]
### 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)

 

4-练习:重塑训练和测试数据集

为了方便,我们要把维度为(64,64,3)的numpy数组重新构造为(64 x 64 x 3,1)的数组,要乘以3的原因是每张图片是由64x64像素构成的,而每个像素点由(R,G,B)三原色构成的,所以要乘以3。在此之后,我们的训练和测试数据集是一个numpy数组,【每列代表一个平坦的图像】 ,应该有m_train和m_test列。也就是把数组变为209行的矩阵。

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

X_flatten = X.reshape(X.shape[0], -1).T      # X.T是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  #将测试集的维度降低并转置。
# train_set_x_flatten = train_set_x_orig.reshape(-1, train_set_x_orig.shape[0])

### 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(像素通道的最大值),因为在RGB中不存在比255大的数据,所以我们可以放心的除以255,让标准化的数据位于[0,1]之间,现在标准化我们的数据集:

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

 

第三部分 学习算法的一般架构

是时候设计一个简单的算法来区分猫图像和非猫图像了。 你将使用神经网络思维建立逻辑回归。下图解释了为什么逻辑回归实际上是一个非常简单的神经网络!

现在总算是把我们加载的数据弄完了,我们现在开始构建神经网络。

以下是数学表达式,如果对数学公式不甚理解,请仔细看一下吴恩达的视频。

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

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

 

第四部分 构建神经网络

建立神经网络的主要步骤是: 
1. 定义模型结构(例如输入特征的数量) 
2. 初始化模型的参数 
3. 循环:

  • 计算当前损失(正向传播)
  • 计算当前梯度(反向传播)
  • 更新参数(梯度下降)

通常分别构建1-3个,并将它们集成到一个我们称为model()的函数中。

1-练习:使用“Python基础”中的代码,实现sigmoid()。

# GRADED FUNCTION: sigmoid

def sigmoid(z):
    """
    参数:z  - 任何大小的标量或numpy数组。
    返回:s  -  sigmoid(z)
    """
    ### START CODE HERE ### (≈ 1 line of code)
    s = 1 / (1 + np.exp(-z))  # exp()表示指数函数
    ### END CODE HERE ###
    
    return s

测试:

print ("sigmoid([0, 2]) = " + str(sigmoid(np.array([0,2]))))  #测试sigmoid函数

结果:

sigmoid([0, 2]) = [ 0.5         0.88079708]

 

2 -初始化参数

练习:在下面的单元格中实现参数初始化,初始化我们需要的参数w和b。

# GRADED FUNCTION: initialize_with_zeros

def initialize_with_zeros(dim):
    """
        此函数为w创建一个维度为(dim,1)的0向量,并将b初始化为0。

        参数:
            dim  - 我们想要的w矢量的大小(或者这种情况下的参数数量)

        返回:
            w  - 维度为(dim,1)的初始化向量。
            b  - 初始化的标量(对应于偏差)
    """
    ### START CODE HERE ### (≈ 1 line of code)
    w = np.zeros((dim, 1))
    b = 0
    ### END CODE HERE ###
    #使用断言来确保我要的数据是正确的
    assert(w.shape == (dim, 1))    #w的维度是(dim,1)
    assert(isinstance(b, float) or isinstance(b, int))  #b的类型是float或者是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

 

3 -前向和反向传播

现在您的参数已经初始化,您可以执行“向前”和“向后”传播步骤来学习参数。

练习:实现一个计算成本函数及其梯度的函数propagate()。

# GRADED FUNCTION: propagate

def propagate(w, b, X, Y):
    """
    实现前向和后向传播的成本函数及其梯度。
    参数:
        w  - 权重,大小不等的数组(num_px * num_px * 3,1)
        b  - 偏差,一个标量
        X  - 矩阵类型为(num_px * num_px * 3,训练数量)
        Y  - 真正的“标签”矢量(如果非猫则为0,如果是猫则为1),矩阵维度为(1,训练数据数量)

    返回:
        cost- 逻辑回归的负对数似然成本
        dw  - 相对于w的损失梯度,因此与w的维度相同
        db  - 相对于b的损失梯度,因此与b的维度相同
    """
    m = X.shape[1]

    # 前向传播
    ### START CODE HERE ### (≈ 2 lines of code)
    A = sigmoid(np.dot(w.T,X) + b) #计算激活值,请参考公式2,dot()函数表示矩阵相乘。
    cost = (- 1 / m) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A))) #计算成本,请参考公式3和4。
    ### END CODE HERE ###

    # 反向传播
    ### 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-使用梯度下降更新参数

练习:写下优化函数

目标是通过最小化成本函数 J 来学习 w和b 。对于参数 θ ,更新规则是 θ=θ−α dθ,其中 α 是学习率。

# GRADED FUNCTION: optimize

def optimize(w , b , X , Y , num_iterations , learning_rate , print_cost = False):
    """
    此函数通过运行梯度下降算法来优化w和b

    参数:
        w  - 权重,大小不等的数组(num_px * num_px * 3,1)
        b  - 偏差,一个标量
        X  - 维度为(num_px * num_px * 3,训练数据的数量)的数组。
        Y  - 真正的“标签”矢量(如果非猫则为0,如果是猫则为1),矩阵维度为(1,训练数据的数量)
        num_iterations  - 优化循环的迭代次数
        learning_rate  - 梯度下降更新规则的学习率
        print_cost  - 每100步打印一次损失值

    返回:
        params  - 包含权重w和偏差b的字典
        grads  - 包含权重和偏差相对于成本函数的梯度的字典
        成本 - 优化期间计算的所有成本列表,将用于绘制学习曲线。

    提示:
    我们需要写下两个步骤并遍历它们:
        1)计算当前参数的成本和梯度,使用propagate()。
        2)使用w和b的梯度下降法则更新参数。
    """

    costs = []

    for i in range(num_iterations):
        # 成本和梯度计算
        ### START CODE HERE ###
        grads, cost = propagate(w, b, X, Y)  # 直接调用上一步的函数
        ### END CODE HERE ###

        dw = grads["dw"]  # 获取字典对应的键来取出值
        db = grads["db"]
    
        # 更新规则   
        ### START CODE HERE ###
        w = w - learning_rate * dw  # w=w-学习率*梯度
        b = b - learning_rate * db
        ### END CODE HERE ###

        # 打印每隔100次的代价
        if i % 100 == 0:
            costs.append(cost)

        # 打印成本数据
        if (print_cost) and (i % 100 == 0):
            print("迭代的次数: %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.5593049248448891
dw = [[0.90158428]
 [1.76250842]]
db = 0.4304620716786828

 

5-练习:预测部分

optimize函数会输出已学习的w和b的值,我们可以使用w和b来预测数据集X的标签。

现在我们要实现预测函数predict()。计算预测有两个步骤:

计算预测结果 Y^=A=σ(wTX+b)Y^=A=σ(wTX+b)
将a的值变为0(如果激活值<= 0.5)或者为1(如果激活值> 0.5),

然后将预测值存储在向量Y_prediction中。

# GRADED FUNCTION: predict

def predict(w, b, X):
    '''
    使用学习逻辑回归参数logistic (w,b)预测标签是0还是1,

    参数:
        w  - 权重,大小不等的数组(num_px * num_px * 3,1)
        b  - 偏差,一个标量
        X  - 维度为(num_px * num_px * 3,训练数据的数量)的数据

    返回:
        Y_prediction  - 包含X中所有图片的所有预测[0 | 1]的一个numpy数组(向量)
    '''
    
    m = X.shape[1]  #图片的数量
    Y_prediction = np.zeros((1,m))  # 维度是1行m列
    w = w.reshape(X.shape[0], 1) 
    
    # 计算预测猫在图片中出现的概率
    ### 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]):
        
        #将概率a [0,i]转换为实际预测p [0,i]
        ### START CODE HERE ### (≈ 4 lines of code)
        if A[0, i] <= 0.5:
            Y_prediction[0, i] = 0
        else:
            Y_prediction[0, i] = 1
        ### END CODE HERE ###
    
    assert(Y_prediction.shape == (1, m)) #使用断言
    
    return Y_prediction

测试:

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

结果:

predictions = [[ 1.  1.]]

记住:您已经实现了几个功能:

  • 初始化(w,b)
  • 迭代优化损失以学习参数(w,b):◾计算成本及其梯度 ◾更新使用梯度下降的参数
  • 使用所学(w,b)来预测给定示例集的标签

 

6-将所有功能合并到一个模型中

把这些函数统统整合到一个model()函数中,届时只需要调用一个model()即可。

练习:实现模型功能。

使用以下符号:

  • 您对测试集的预测的Y_prediction
  • 在训练集中为您的预测设置Y_prediction_train
  • optimize()输出的w, costs, grads
# GRADED FUNCTION: model

def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
    """
    通过调用之前实现的函数来构建逻辑回归模型

    参数:
        X_train  - numpy的数组,维度为(num_px * num_px * 3,m_train)的训练集
        Y_train  - numpy的数组,维度为(1,m_train)(矢量)的训练标签集
        X_test   - numpy的数组,维度为(num_px * num_px * 3,m_test)的测试集
        Y_test   - numpy的数组,维度为(1,m_test)的(向量)的测试标签集
        num_iterations  - 表示用于优化参数的迭代次数的超参数
        learning_rate  - 表示optimize()更新规则中使用的学习速率的超参数
        print_cost  - 设置为true以每100次迭代打印成本

    返回:
        d  - 包含有关模型信息的字典。
    """
    
    ### START CODE HERE ###
    
    # 用零初始化参数 (≈ 1 line of code)
    w, b = initialize_with_zeros(X_train.shape[0])

    # 梯度下降 (≈ 1 line of code)
    parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
    
    # 从字典“参数”中检索参数w和b
    w = parameters["w"]
    b = parameters["b"]
    
    # 预测测试/训练集的例子 (≈ 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 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

测试(2000次迭代,学习率为0.005):

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

结果:

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 %

我们更改一下学习率和迭代次数,有可能会发现训练集的准确性可能会提高,但是测试集准确性会下降,这是由于过拟合造成的,但是我们并不需要担心,我们以后会使用更好的算法来解决这些问题的。

到这里所有的代码编写工作就完成了。

 

7-查看一个分类错误的例子

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

 

8-绘制图像

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

解释:你可以看到成本在下降。它显示参数正在被学习。但是,您可以看到,您可以在训练集中对模型进行更多的训练。尝试增加上面单元格中的迭代次数,然后重新运行单元格。你可能会看到训练集的精度提高了,但是测试集的精度降低了。这叫做过度拟合。

 

9-进一步分析(可选/未分级练习)

祝贺你建立了你的第一个图像分类模型。让我们进一步分析它,并检查学习率α的可能选择。

学习率的选择

提醒:为了让梯度下降发挥作用,你必须明智地选择学习速度。学习率α决定了我们更新参数的速度。如果学习率太大,我们可能会“超过”最佳值。同样,如果它太小,我们将需要太多迭代才能收敛到最佳值。这就是为什么使用良好的学习率至关重要。 让我们将模型的学习曲线与几种学习率选择进行比较。运行下面的单元格。这大约需要1分钟。也可以尝试不同于我们初始化学习率变量所包含的三个值,看看会发生什么。

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 %

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

           图   不同的学习率在相同的迭代次数下的变化

解释: 不同的学习率会产生不同的成本,从而产生不同的预测结果。 如果学习率太大(0.01),成本可能上下波动。它甚至可能有所不同(尽管在这个例子中,使用0.01最终还是会得到一个很好的成本值)。 较低的成本并不意味着更好的模式。你必须检查是否有可能过度拟合。当训练精度远远高于测试精度时,就会发生这种情况。

在深度学习中,我们通常建议您:

  • 选择能够更好地将成本函数最小化的学习率。
  • 如果你的模型过度拟合,使用其他技术来减少过度拟合。(我们将在以后的视频中讨论这一点。)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值