吴恩达深度学习_1_Week2神经网络的编程基础(2)

逻辑回归分类器


1、本项目导入包
2、数据预处理:计算维度—重塑维度—标准化数据集
3、构建神经网络:确定模型框架—初始化模型参数—Loop(计算损失、梯度、更新参数)
4、将所有函数集成到一个模型
5、优化:学习率的选择,将模型的学习曲线与另几种进行比较


第一门课:神经网络和深度学习
第二周:神经网络的编程基础

基础概念

构建学习算法的一般框架:
1、初始化参数;
2、计算成本函数及其梯度;
3、使用优化算法(梯度下降);
4、按正确的顺序将上述三个函数收集到一个主模型函数中

算法描述

1、Packages

import numpy as np
import matplotlib.pyplot as plt         # 用于在python中绘制图像
import h5py                             # 存储在H5文件中的数据集进行交互
import scipy                            # 测试模型
from PIL import Image                   # 测试模型
from scipy import ndimage
from lr_utils import load_dataset

2、Overview of the Problem set

问题概述

1、得到一个数据集 (“data.h5”) (包含一组标记为cat和非cat的train图像,一组标记为cat和非cat的test图像)
2、每个图像的形状为(num_px,num_px,3),3表示三个通道RDB,每个图像都是正方形:高度=宽度=num_px
3、要求:构建一个图像识别算法,正确将图片分类为猫或者非猫

代码实现

# Loading the data (cat/non-cat)
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
# 在图像数据集(训练和测试)的末尾添加了“_orig”,因为要对它们进行预处理。
# 预处理后,得到 train_set_x 和 test_set_x(标签 train_set_y 和 test_set_y 不需要任何预处理)
# train_set_x_orig和test_set_x_orig的每一行都是一个表示图像的数组。
# 可以通过运行以下代码来可视化示例。也可以随意更改索引值并重新运行以查看其他图像
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
train_set_x_orig.shape, train_set_y.shape, test_set_x_orig.shape, test_set_y.shape
# ((209, 64, 64, 3), (1, 209), (50, 64, 64, 3), (1, 50))
# train_set_x_orig每行都是一个图片,像素大小(64x64), rgb
# Example of a picture
index = 5
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.")

Exercise1: 查找以下值: 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 = 209
m_test = 50
num_px = 64
### 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_pxnum_px3,1)。在此之后,我们的训练和测试数据集是一个numpy_array,其中每一列代表一个扁平化的图像,应该有m_train(分别为m_test)列。
Exercise2: 重塑训练和测试数据集,以便将大小(num_px,num_px,3)的图像展平为形状(num_pxnum_px3,1)的单个向量。

在这里插入图片描述

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

3、General Architecture of the learning algorithm

现在可以从不是猫的图像中区别出猫的图像。你将使用一个神经网络构造一个逻辑回归,接下来的图片解释了为什么逻辑回归实际上是一个非常简单的神经网络。
在这里插入图片描述
在这里插入图片描述
关键步骤:在本练习中,您将执行以下步骤:初始化模型的参数-通过最小化成本来学习模型的参数-使用学习到的参数进行预测(在测试集上)-分析结果并得出结论

算法实现

The main steps for building a Neural Network are:
1、Define the model structure (such as number of input features)
2、Initialize the model’s parameters
3、Loop:
Calculate current loss (forward propagation)
Calculate current gradient (backward propagation)
Update parameters (gradient descent)
You often build 1-3 separately and integrate them into one function we call model().

1、Helper functions

在这里插入图片描述

# GRADED FUNCTION: sigmoid
def sigmoid(z):
    ### START CODE HERE ### (≈ 1 line of code)
    s = 1 / (1 + np.exp(-z))
    ### END CODE HERE ###
    return s
print ("sigmoid([0, 2]) = " + str(sigmoid(np.array([0,2]))))

在这里插入图片描述

2、Initializing parameters

在这里插入图片描述

# GRADED FUNCTION: initialize_with_zeros
def initialize_with_zeros(dim):
    ### START CODE HERE ### (≈ 1 line of code)
    w = np.zeros((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))

在这里插入图片描述

3、Forward and Backward propagation

在这里插入图片描述

# GRADED FUNCTION: propagate
def propagate(w, b, X, Y): 
    m = X.shape[1]
    
    # FORWARD PROPAGATION (FROM X TO COST)
    ### START CODE HERE ### (≈ 2 lines of code)
    A = sigmoid(w.T@X + b)            # compute activation
    cost = (-Y*np.log(A) + (Y-1)*np.log(1-A)).sum() / m
    # compute cost
    ### END CODE HERE ###
    
    # BACKWARD PROPAGATION (TO FIND GRAD)
    ### START CODE HERE ### (≈ 2 lines of code)
    dw = (X@(A-Y).T) / m
    db = (A - Y).mean()
    ### END CODE HERE ###

    assert(dw.shape == w.shape)
    assert(db.dtype == float)
    cost = np.squeeze(cost)
    assert(cost.shape == ()), 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))

在这里插入图片描述

4、Optimization

在这里插入图片描述

# GRADED FUNCTION: optimize

def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):  
    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 
        b = b - learning_rate * db
        ### END CODE HERE ###
        
        # Record the costs,每过100个样本,记录代价
        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"]))

在这里插入图片描述
在这里插入图片描述

# GRADED FUNCTION: predict

def predict(w, b, 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(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)))

在这里插入图片描述

Merge all functions into a model

Exercise: 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 for the outputs of optimize()

# GRADED FUNCTION: model

def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
    ### 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

Run the following cell to train your model.

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%。对于这个简单的模型来说,这实际上还不错,因为我们使用的数据集很小,而且逻辑回归是一个线性分类器。
此外,您会看到模型明显过度拟合训练数据。在本专业化的后面部分,您将学习如何减少过拟合,例如通过使用正则化。使用下面的代码(并更改索引变量),您可以查看测试集图片上的预测。
这里的classes的类型是dtype=’|S7’ ,取值的时候,需要用int强转一下,否则报错。

# Example of a picture that was wrongly classified.
index = 23
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.")

Let’s also plot the cost function and the gradients.

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

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

Further analysis (optional/ungraded exercise)

学习率的选择:
提醒:为了使梯度下降起作用,您必须明智地选择学习率。学习率α确定我们更新参数的速度。如果学习率太大,我们可能会“超过”最佳值。同样,如果它太小,我们将需要太多的迭代才能收敛到最佳值。这就是为什么使用经过良好调整的学习率至关重要的原因。
让我们将模型的学习曲线与几种学习率选择进行比较。运行下面的单元格。这大约需要 1 分钟。也可以随意尝试与我们初始化要包含的 learning_rates 变量的三个值不同的值,看看会发生什么。
例如:Handler 发送消息有两种方式,分别是 Handler.obtainMessage()Handler.sendMessage(),其中 obtainMessage 方式当数据量过大时,由于 MessageQuene 大小也有限,所以当 message 处理不及时时,会造成先传的数据被覆盖,进而导致数据丢失。

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.01 最终仍会以良好的成本值结束)。更低的成本并不意味着更好的模型。您必须检查是否可能存在过拟合。当训练精度远高于测试精度时,就会发生这种情况。
在深度学习中,我们通常建议您:选择能够更好地最小化成本函数的学习率。若模型过拟合,可使用其他技术来减少过拟合。

Test with your own image (optional/ungraded exercise)

## START CODE HERE ## (PUT YOUR IMAGE NAME) 
my_image = "cat_in_iran.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.")

从这次作业中要记住什么:
1.对数据集进行预处理非常重要
2. 您分别实现了每个函数:initialize()、propagate()、optimize()。然后你构建了一个 model()
3. 调整学习率(这是“超参数”的一个例子)可以对算法产生很大的影响。

Bibliography:
http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch/
https://stats.stackexchange.com/questions/211436/why-do-we-normalize-images-by-subtracting-the-datasets-image-mean-and-not-the-c

完整代码

  1. Ir_utils.py
import numpy as np
import h5py

# (1)得到一个数据集(包含一组标记为cat和非cat的train图像,一组标记为cat和非cat的test图像)
# (2)每个图像的形状为(num_px,num_px,3),3表示三个通道RDB,每个图像都是正方形:高度=宽度=num_px
# (3)要求:构建一个图像识别算法,正确将图片分类为猫或者非猫
# Loading the data (cat/non-cat)
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

# 在图像数据集(训练和测试)的末尾添加了“_orig”,因为要对它们进行预处理。
# 预处理后,得到 train_set_x 和 test_set_x(标签 train_set_y 和 test_set_y 不需要任何预处理)
# train_set_x_orig和test_set_x_orig的每一行都是一个表示图像的数组。
  1. init.py
# 构建一个逻辑回归分类器来识别猫
# 构建学习算法的一般框架:1、初始化参数;2、计算成本函数及其梯度;
#                    3、使用优化算法(梯度下降);4、按正确的顺序将上述三个函数收集到一个主模型函数中

# 1、packages
import numpy as np
import matplotlib.pyplot as plt  # 用于在python中绘制图像
import h5py  # 存储在H5文件中的数据集进行交互
import scipy  # 测试模型
from PIL import Image  # 测试模型
from scipy import ndimage
from lr_utils import load_dataset

# 2、Overview of the problem set
# 预处理一个新数据集常见步骤:1、计算出问题的维度和形状(m_train,m_test,num_px,...)
#                        2、重塑数据集,例如每一例设为一维列向量     3、标准化数据集

# (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, train_set_y.shape, test_set_x_orig.shape, test_set_y.shape)
# Example of a picture
index = 7
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.")

# (2)查找以下值: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。
m_train = 209
m_test = 50
num_px = 64
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))

# (3)重塑训练和测试数据集,将大小(num_px,num_px,3)的图像展平为形状(num_px*num_px*3,1)的单个向量
# 目的:数据集的每一列将会代表一个扁平化图像,具有m_train/m_test列
# Trick:将(a,b,c,d)——>(b*c*d,a)---X_flatten = X.reshape(X.shape[0],-1).T
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
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]))

# (4)标准化数据集
# 为表示彩色图像,为每个像素指定红色、绿色和蓝色通道(RGB),因此像素值实际上是从0-255的三个数字的向量
# 预处理步骤---将数据集居中和标准化---从每个样本中减去整个numpy数组的平均值,然后将每个样本除以整个numpy数组的标准差
# 对于图片数据集,只需将数据集的每一行除以 255(像素通道的最大值)同样有效
train_set_x = train_set_x_flatten / 255.
test_set_x = test_set_x_flatten / 255.


# 3、General Architecture of the learning algorithm
# 构造一个神经网络的主要步骤:1、确定模型框架(例如输入特征数)  2、初始化模型的参数
#                        3、Loop:计算当前损失(正向传播),计算当前梯度(反向传播),更新参数(梯度下降)---将其集成到model()函数中
# 关键步骤:初始化模型参数-通过最小化成本来学习模型的参数-使用学习到的参数进行预测-分析结果得到结论

# (1)构建激活函数进行预测
def sigmoid(z):
    s = 1 / (1 + np.exp(-z))
    return s
print("sigmoid([0, 2]) = " + str(sigmoid(np.array([0, 2]))))

# (2)初始化参数
def initialize_with_zeros(dim):
    w = np.zeros((dim, 1))
    b = 0
    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))

# (3)前向和反向传播---计算cost函数以及梯度
# GRADED FUNCTION: propagate
# 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
def propagate(w, b, X, Y):
    m = X.shape[1]
    # FORWARD PROPAGATION (FROM X TO COST)
    A = sigmoid(w.T @ X + b)                                        # compute activation
    cost = (-Y * np.log(A) + (Y - 1) * np.log(1 - A)).sum() / m     # compute cost
    # BACKWARD PROPAGATION (TO FIND GRAD)
    dw = (X @ (A - Y).T) / m
    db = (A - Y).mean()

    assert (dw.shape == w.shape)
    assert (db.dtype == float)
    cost = np.squeeze(cost)
    assert (cost.shape == ()), 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))


# 4、Optimization
# 使用梯度下降来更新参数,目的在于学习w和b来最小化损失函数J
# GRADED FUNCTION: optimize
# 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.
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False):
    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
        w = w - learning_rate * dw
        b = b - learning_rate * db
        # Record the costs,每过100个样本,记录代价
        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"]))

# 运用预测函数,计算预测值
# GRADED FUNCTION: predict
# 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
def predict(w, b, 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
    A = sigmoid(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
    assert (Y_prediction.shape == (1, m))
    return Y_prediction
print ("predictions = " + str(predict(w, b, X)))


# 5、Merge all functions into a model
# GRADED FUNCTION: model
# 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.
def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False):
    # 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)
    # 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)

# 以下代码可以查看测试集图片上的预测
index = 23
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.")
# 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、Further analysis(optional/ungraded exercise)
# 学习率的选择:学习率确定了更新参数的速度,若学习率太大可能会超过最佳值,若太小可能需要迭代才能收敛到最佳
# 将模型的学习曲线与几种学习率进行比较
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()
# 总结:不同的学习率带来不同的成本,甚至产生不同的预测结果


# 7、Test with your own image(optional/ungraded exercise)
my_image = "cat_in_iran.jpg"   # change this to the name of your image file

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.")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值