Coursera吴恩达Deep Learning.ai第一课第二周Logistic Regression with a Neural Network mindset

Logistic Regression with a Neural Network mindset

在这里你将会构建一个识别猫的逻辑回归分类器。

指导:不要在代码中使用循环(for/while),除非明确要求你这么做。

您将学习构建学习算法的通用架构,包括:

  • 初始化参数。

  • 计算成本函数及其梯度。

  • 使用优化算法(梯度下降)。

  • 按正确的顺序将上述所有三个函数收集到主模型函数中。

1 –包

首先,让我们运行下面的单元格来导入在此分配期间需要的所有包。

  • 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 - 问题集概述

问题陈述:您将获得一个数据集(“data.h5”),其中包含:

  • 标记为猫(y = 1)或非猫(y = 0)的m_train图像训练集。
  • 标记为猫或非猫的m_test图像测试集。
  • 每个图像的形状(num_px,num_px,3),其中3表示3个通道(RGB)。 因此,每个图像是正方形(height = num_px)和(width = 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()

我们对需要进行预处理的图像数据集(训练和测试)的末尾添加了“_orig”,(标签train_set_y和test_set_y不需要任何预处理)。

train_set_x_orig和test_set_x_orig的每一行都是一个表示图像的数组。您可以通过运行以下代码来可视化示例。 您也可以随意更改索引值并重新运行以查看其他图像。

# Example of a picture
index = 25
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 = [1], it's a 'cat' picture.

深度学习中的许多软件错误来自于不适合的矩阵/向量维度。如果你可以保持你的矩阵/矢量尺寸,你将在很长一段时间内消除许多错误。

练习:找到以下值:

  • m_train(训练样例数)
  • m_test(测试例数)
  • num_px(= height =训练图像的宽度)

请记住,train_set_x_orig是一个数组(m_train,num_px,num_px,3)。 您可以通过编写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[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))

练习:重新训练训练和测试数据集,以便将大小(num_px,num_px,3)的图像展平为单个矢量形状(num_px * num_px * 3,1)。在此之后,我们的训练(和测试)数据集是一个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 transpose 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))
print ("sanity check after reshaping: " + str(train_set_x_flatten[0:5,0]))

要表示彩色图像,必须为每个像素指定红色,绿色和蓝色通道(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,...)
  • 重塑数据集,使每个示例现在都是大小的向量(num_px * num_px * 3,1)
  • “标准化”数据

3 - 学习算法的一般体系结构

您将使用神经网络思维模式构建Logistic回归。 下图解释了为什么Logistic回归实际上是一个非常简单的神经网络!

算法的数学表达式:

关键步骤:

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

4 - 构建算法的各个部分##

构建神经网络的主要步骤是:

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

您经常单独构建1-3并将它们集成到一个我们称为model()的函数中。

4.1 - 辅助功能

# GRADED FUNCTION: sigmoid
 
def sigmoid(z):
    """
    Compute the sigmoid of z
    Arguments:
    z -- A scalar or numpy array of any size.
    Return:
    s -- sigmoid(z)
    """
 
    ### START CODE HERE ### (≈ 1 line of code)
    s = 1.0/(1+np.exp(-z))
    ### END CODE HERE ###
    
    return s
print ("sigmoid([0, 2]) = " + str(sigmoid(np.array([0,2]))))

4.2 - 初始化参数

练习:在下面的单元格中实现参数初始化。 您必须将w初始化为零向量。 (请使用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.
    
    Argument:
    dim -- size of the w vector we want (or number of parameters in this case)
    
    Returns:
    w -- initialized vector of shape (dim, 1)
    b -- initialized scalar (corresponds to the bias)
    """
    
    ### START CODE HERE ### (≈ 1 line of code)
    w, b = np.zeros((dim,1)), 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将具有形状(num_px×num_px×3,1)。

4.3 - 前向和后向传播

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

练习:实现一个函数propagate()来计算成本函数及其渐变。

提示:前向传播:

# 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)
    b -- bias, a scalar
    X -- data of size (num_px * num_px * 3, number of examples)
    Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)
    Return:
    cost -- negative log-likelihood cost for logistic regression
    dw -- gradient of the loss with respect to w, thus same shape as w
    db -- gradient of the loss with respect to b, thus same shape as b
    
    Tips:
    - Write your code step by step for the propagation. np.log(), np.dot()
    """
    
    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) # A
    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 == ())
    
    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))

d)优化

  • 您已初始化参数。
  • 您还可以计算成本函数及其渐变。
  • 现在,您想使用渐变下降更新参数。

# 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
    
    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
    
    Returns:
    params -- dictionary containing the weights w and bias 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().
        2) Update the parameters using gradient descent rule for w and 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)
        costs.append(cost)
        ### 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
        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和b。 我们能够使用w和b来预测数据集X的标签。实现predict()函数。 计算预测有两个步骤:

# GRADED FUNCTION: predict
 
def predict(w, b, X):
    '''
    Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
    
    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
    '''
    
    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]
        ### 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)))

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

  • 初始化(w,b)
  • 迭代优化损失以学习参数(w,b):
  • 计算成本及其梯度

  • 使用梯度下降更新参数

  • 使用学习的(w,b)预测给定示例集的标签

5 - 将所有函数合并到模型中

现在,您将通过将所有构建块(前面部分中实现的功能)按正确的顺序放在一起来了解整个模型的结构。

练习:实现模型功能。 使用以下表示法:
- Y_prediction用于测试集的预测。
- Y_prediction_train用于预测训练集。
- w,cost,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)
    Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train)
    X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test)
    Y_test -- test labels represented by a numpy array (vector) of shape (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
    
    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 = 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

运行以下代码来训练你的模型。

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

评论:训练准确率接近100%。 这是一个很好的健全性检查:您的模型正在运行,并且具有足够的容量来适应训练数据。 测试误差为68%。 考虑到我们使用的小数据集并且逻辑回归是线性分类器,这对于这个简单模型实际上并不坏。

此外,您会发现该模型显然过度拟合了训练数据。 在本专业化的后期,您将学习如何减少过度拟合,例如使用正则化。 使用下面的代码(并更改索引变量),您可以查看测试集图片上的预测。

# Example of a picture that was wrongly classified.
index = 1
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[d["Y_prediction_test"][0,index]].decode("utf-8") +  "\" picture.")
/opt/conda/lib/python3.5/site-packages/ipykernel/__main__.py:4: DeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
 
 
y = 1, you predicted that it is a "cat" picture.

我们还绘制成本函数和渐变。

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

解释:你可以看到成本在下降。它表明正在学习参数。但是,您可以看到您可以在训练集上进一步训练模型。尝试增加上面单元格中的迭代次数,然后重新运行单元格。您可能会看到训练集精度上升,但测试集精度下降。这称为过度拟合。

6 - 进一步分析(可选/未评分的练习)

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

选择学习率
提醒:为了使Gradient Descent工作,您必须明智地选择学习率。学习率α确定我们更新参数的速度。如果学习率太大,我们可能会“超调”最佳值。同样,如果它太小,我们将需要太多的迭代来收敛到最佳值。

让我们将模型的学习曲线与几种学习率选择进行比较。运行下面的单元格。这应该需要大约1分钟。也可以尝试使用与我们初始化的learning_rates变量包含的三个值不同的值,并查看会发生什么。

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),成本可能会上下波动。它甚至可能发散。
  • 较低的成本并不意味着更好的模型。你必须检查是否有可能过度拟合。当训练精度远高于测试精度时,就会发生这种情况。
  • 在深度学习中,我们通常建议您:
  • 选择更好地降低成本函数的学习率。

  • 如果您的模型过度拟合,请使用其他技术来减少过度拟合。 

7 - 使用您自己的图像进行测试(可选/未分级练习)

恭喜你完成了这项任务。您可以使用自己的图像并查看模型的输出。要做到这一点:

  1. 单击此笔记本上方栏中的“File”,然后单击“Open”以进入Coursera Hub。
  2. 将图像添加到此“images”文件夹中的Jupyter Notebook目录中
  3. 在以下代码中更改图像的名称
  4. 运行代码并检查算法是否正确(1 = 猫,0 =非猫)!
## 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.

记住:

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

最后,如果你愿意,我们邀请你在这款笔记本上尝试不同的东西。 确保在尝试之前提交。 提交后,您可以使用的内容包括:

  • 使用学习率和迭代次数进行游戏
  • 尝试不同的初始化方法并比较结果
  • 测试其他预处理(将数据居中,或按行标准差划分每行)

猜你喜欢

转载自blog.csdn.net/coder_kiwi/article/details/81021789