ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

吴恩达深度学习-第一课神经网络和深度学习-第2周课后编程

2021-07-25 18:02:14  阅读:162  来源: 互联网

标签:cost -- px 第一课 shape num 课后 深度 np


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


##第二周的课后编程训练
# 1- 介绍了项目中需要的一些库,并导入 numpy,matplotlib.pyplot,h5py, scipy, Image
# 2- 加载项目的 数据(训练集,测试集)
# 3- 运行模型,判断图片是否是猫
# 阶段2
# 1- 介绍项目中的数据集的结构, 让我们使用 .shape[]来取数据集中的某一部
#    例如1.1- array.shape[] , 取数组中指定的索引下标的值
#       1.2- array。shape(),matrix.shape(),是获取集合的结构。例如数组的长度,矩阵的 维度
# 2- 使用 reshape方法, 将数组 转换为 向量。 即如何向量化
#    实践: X_flatten = X.reshape(X.shape[0], -1).T   , X是一个数组,取值后,使用 -1,确保是专为 图片像素的矩阵
#    >>> X.shape
#       (209, 64, 64, 3)
#      x.reshape(x.shape(0),-1) = (209, 64*64*3)
#                                                      .T是向量转置,将行向量,转化为 列向量
# 3- 将 训练值标准化,这样可以加快 梯度下降的运行
#      标准化方法1 - x/ ||X||,  || X || = np.linalg.norm(x, axis=1 , keepdims=True), x是一个矩阵。 矩阵是向量构成的
#      标准化方法2 - 针对图片的矩阵, 由于图片的像素值是0-255,所以可以是 矩阵X 直接除以 255,即 x/255
# 4- 构建算法模型,
#    4.1- 构建激活函数, 本例使用 sigmoid
#    4.2- 初始化权重参数 w和b, 本例子使用 np.zeros, 将矩阵W 全部初始化 为 0
#    4.3- 计算图的实现, 包括 前向传播 和 后向传播。 返回 代价函数和 梯度
#    4.4- 参数的优化,及 梯度下降更新 权重参数 w和b的值, 返回 迭代梯度下降 优化后的 权重参数 w和b
#    4.5- 计算预测值, 根据得到的 权重参数 w和b ,计算得到预测值,再根据判断逻辑, 将预测值 转化为分类值
#    4.6- 在上诉的步骤 结合起来运算得到 模型d , 模型d 包含的信息 有 代价函数, w和b,预测值,迭代次数,学习因子等等
# #

##
# 定义一个激活函数, sigmoid函数
# #
def sigmoid(z):
    """
    Arguments:
    z -- A scalar or numpy array of any size.
    """
    s = 1 / ( 1 + np.exp(-z))

    return s

"""
这个函数是用于创建一个 列向量(dim, 1) ,用来将 权重参数 w和b 初始化为 0 
Argument:
dim -- 我们想要的 w 的大小, 输入特征 X 一样

Returns:
w -- initialized vector of shape (dim, 1)
b -- initialized scalar (corresponds to the bias)
"""

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

"""
   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[0]
    # 前向传播, 将输入X 转化为 输出 代价函数 cost#
    # np.dot() 矩阵相乘,或者 点积 #
    A = sigmoid(np.dot(w.T,X) + b)  ## 权重参数 矩阵 乘以 输入参数 矩阵 z = w.x + b
    cost = (-1/m) * (np.dot(Y,np.log(A).T) + np.dot((1-Y),np.log(1-A).T))  ## J = -1/m * sum(y*logy^ + (1-y)* log(1-y^))

    ## 反向传播 实现
    # 将 输入 Y, 转化为 输出 dw, db
    # dw = dJ/dA * dz/dw =
    dw = -1/m * np.dot(X,(A-Y).T)
    db = -1/m * np.sum((A-Y))

    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
  在progapate()计算得到了梯度 dw,db, 那么使用 梯度下降的方法 更新 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, 学习因子a
    print_cost -- True to print the loss every 100 steps
    
    Returns:
    params -- 包含优化后的 权重值 w 和 b 的字典
    grads -- 包含优化后的 梯度值 dw 和 db 的字典
    costs -- 在优化过程中产生的 代价函数值 的 集合list, 它用于绘制学习曲线
    
"""
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 (≈ 2 lines of code)
        w = w - learning_rate * dw
        b = b - learning_rate * db

        # 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
"""
预测函数,optimize()优化计算后 得到的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
"""
def predict(w,b,X):
    ## 步骤1 - 计算 预测值 Y^ = sigmoid(Z) = sigmoid(w.X + b)
    m = X.shape[1]  # 获取 测试集的 测试样本个数
    Y_prediction = np.zeros((1,m)) # 构建 预测值 的向量, 1行m列
    w = w.reshape(w.shape[0],1)  # 重组后的 数组 w 只有 一行, 但是 shape的值相乘 还是等于 从前的 shape值相乘。

    A = sigmoid(np.dot(w.T,X) + b) # 获取预测值
    # 步骤2 - 将预测值 带入 逻辑, 得到 判断值, 是不是 猫
    for i in range(A.shape[1]):
        if A[i] > 0.5:
            Y_prediction[0,i] = 1
        else:
            Y_prediction[0,i] = 0
    assert(Y_prediction.shape == (1, m))

    return Y_prediction

"""
将所有的步骤都结合起来, 运行得到 算法模型 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 -- 超参数, 梯度下降的迭代次数
    learning_rate -- 学习因子
    print_cost -- 是否100行,打印一次代价函数 cost function
    
    Returns:
    d -- 包含模型的所有信息, 预测的分类值,训练集和测试集的准确率
"""
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
    # 初始化 w , b
    w,b = initialize_with_zeros(X_train.shape[0])

    # 计算最优的 w,b ,  使用 梯度下降方法
    params, grads, costs = optimize(w,b,X_train,Y_train,learning_rate, print_cost)
    w = params["w"]
    b = params["b"]

    # 计算预测值 , 包括 训练集和 测试集
    Y_train_pre = predict(w,b,X_train)
    Y_test_pre = predict(w,b,X_test)

    # 计算并打印错误率, 包括 训练集 和 测试集
    print("train set error rate is %" + format(100 - np.mean(np.abs(Y_train_pre - Y_train)) * 100 ))
    print("test set error rate is %" + format(100 - np.mean(np.abs(Y_test_pre - Y_test)) * 100 ))

    # 构建并返回 模型信息, 迭代过程的代价函数, 预测值, 权重参数 w和b , 学习因子, 梯度下降迭代的次数
    d = {"costs": costs,
         "Y_prediction_test": Y_train_pre,
         "Y_prediction_train" : Y_test_pre,
         "w" : w,
         "b" : b,
         "learning_rate" : learning_rate,
         "num_iterations": num_iterations}

    return d

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


##第二周的课后编程训练
# 1- 介绍了项目中需要的一些库,并导入 numpy,matplotlib.pyplot,h5py, scipy, Image
# 2- 加载项目的 数据(训练集,测试集)
# 3- 运行模型,判断图片是否是猫
# 阶段2
# 1- 介绍项目中的数据集的结构, 让我们使用 .shape[]来取数据集中的某一部
#    例如1.1- array.shape[] , 取数组中指定的索引下标的值
#       1.2- array。shape(),matrix.shape(),是获取集合的结构。例如数组的长度,矩阵的 维度
# 2- 使用 reshape方法, 将数组 转换为 向量。 即如何向量化
#    实践: X_flatten = X.reshape(X.shape[0], -1).T   , X是一个数组,取值后,使用 -1,确保是专为 图片像素的矩阵
#    >>> X.shape
#       (209, 64, 64, 3)
#      x.reshape(x.shape(0),-1) = (209, 64*64*3)
#                                                      .T是向量转置,将行向量,转化为 列向量
# 3- 将 训练值标准化,这样可以加快 梯度下降的运行
#      标准化方法1 - x/ ||X||,  || X || = np.linalg.norm(x, axis=1 , keepdims=True), x是一个矩阵。 矩阵是向量构成的
#      标准化方法2 - 针对图片的矩阵, 由于图片的像素值是0-255,所以可以是 矩阵X 直接除以 255,即 x/255
# 4- 构建算法模型,
#    4.1- 构建激活函数, 本例使用 sigmoid
#    4.2- 初始化权重参数 w和b, 本例子使用 np.zeros, 将矩阵W 全部初始化 为 0
#    4.3- 计算图的实现, 包括 前向传播 和 后向传播。 返回 代价函数和 梯度
#    4.4- 参数的优化,及 梯度下降更新 权重参数 w和b的值, 返回 迭代梯度下降 优化后的 权重参数 w和b
#    4.5- 计算预测值, 根据得到的 权重参数 w和b ,计算得到预测值,再根据判断逻辑, 将预测值 转化为分类值
#    4.6- 在上诉的步骤 结合起来运算得到 模型d , 模型d 包含的信息 有 代价函数, w和b,预测值,迭代次数,学习因子等等
# #

##
# 定义一个激活函数, sigmoid函数
# #
def sigmoid(z):
    """
    Arguments:
    z -- A scalar or numpy array of any size.
    """
    s = 1 / ( 1 + np.exp(-z))

    return s

"""
这个函数是用于创建一个 列向量(dim, 1) ,用来将 权重参数 w和b 初始化为 0 
Argument:
dim -- 我们想要的 w 的大小, 输入特征 X 一样

Returns:
w -- initialized vector of shape (dim, 1)
b -- initialized scalar (corresponds to the bias)
"""

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

"""
   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[0]
    # 前向传播, 将输入X 转化为 输出 代价函数 cost#
    # np.dot() 矩阵相乘,或者 点积 #
    A = sigmoid(np.dot(w.T,X) + b)  ## 权重参数 矩阵 乘以 输入参数 矩阵 z = w.x + b
    cost = (-1/m) * (np.dot(Y,np.log(A).T) + np.dot((1-Y),np.log(1-A).T))  ## J = -1/m * sum(y*logy^ + (1-y)* log(1-y^))

    ## 反向传播 实现
    # 将 输入 Y, 转化为 输出 dw, db
    # dw = dJ/dA * dz/dw =
    dw = -1/m * np.dot(X,(A-Y).T)
    db = -1/m * np.sum((A-Y))

    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
  在progapate()计算得到了梯度 dw,db, 那么使用 梯度下降的方法 更新 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, 学习因子a
    print_cost -- True to print the loss every 100 steps
    
    Returns:
    params -- 包含优化后的 权重值 w 和 b 的字典
    grads -- 包含优化后的 梯度值 dw 和 db 的字典
    costs -- 在优化过程中产生的 代价函数值 的 集合list, 它用于绘制学习曲线
    
"""
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 (≈ 2 lines of code)
        w = w - learning_rate * dw
        b = b - learning_rate * db

        # 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
"""
预测函数,optimize()优化计算后 得到的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
"""
def predict(w,b,X):
    ## 步骤1 - 计算 预测值 Y^ = sigmoid(Z) = sigmoid(w.X + b)
    m = X.shape[1]  # 获取 测试集的 测试样本个数
    Y_prediction = np.zeros((1,m)) # 构建 预测值 的向量, 1行m列
    w = w.reshape(w.shape[0],1)  # 重组后的 数组 w 只有 一行, 但是 shape的值相乘 还是等于 从前的 shape值相乘。

    A = sigmoid(np.dot(w.T,X) + b) # 获取预测值
    # 步骤2 - 将预测值 带入 逻辑, 得到 判断值, 是不是 猫
    for i in range(A.shape[1]):
        if A[i] > 0.5:
            Y_prediction[0,i] = 1
        else:
            Y_prediction[0,i] = 0
    assert(Y_prediction.shape == (1, m))

    return Y_prediction

"""
将所有的步骤都结合起来, 运行得到 算法模型 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 -- 超参数, 梯度下降的迭代次数
    learning_rate -- 学习因子
    print_cost -- 是否100行,打印一次代价函数 cost function
    
    Returns:
    d -- 包含模型的所有信息, 预测的分类值,训练集和测试集的准确率
"""
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
    # 初始化 w , b
    w,b = initialize_with_zeros(X_train.shape[0])

    # 计算最优的 w,b ,  使用 梯度下降方法
    params, grads, costs = optimize(w,b,X_train,Y_train,learning_rate, print_cost)
    w = params["w"]
    b = params["b"]

    # 计算预测值 , 包括 训练集和 测试集
    Y_train_pre = predict(w,b,X_train)
    Y_test_pre = predict(w,b,X_test)

    # 计算并打印错误率, 包括 训练集 和 测试集
    print("train set error rate is %" + format(100 - np.mean(np.abs(Y_train_pre - Y_train)) * 100 ))
    print("test set error rate is %" + format(100 - np.mean(np.abs(Y_test_pre - Y_test)) * 100 ))

    # 构建并返回 模型信息, 迭代过程的代价函数, 预测值, 权重参数 w和b , 学习因子, 梯度下降迭代的次数
    d = {"costs": costs,
         "Y_prediction_test": Y_train_pre,
         "Y_prediction_train" : Y_test_pre,
         "w" : w,
         "b" : b,
         "learning_rate" : learning_rate,
         "num_iterations": num_iterations}

    return d

标签:cost,--,px,第一课,shape,num,课后,深度,np
来源: https://blog.csdn.net/zhang5324496/article/details/119085078

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有