吴恩达深度学习之logistic回归(识别图片是否为猫)

本文的主题是吴恩达深度学习的第一次作业,内容为识别图片上的内容是否为猫,是一个二分类问题。

第一次作业的内容不多,主要是单神经元的的应用。
大致为以下步骤(从总体上来说):

  • 初始化w和b
  • 设置好迭代次数num_iterations和学习率learning_rate
  • 正向传播计算出预测值,再反向传播修正w和b,反复进行此步骤num_iterations次
  • 利用训练出来的模型预测测试数据的结果并分析准确度

代码如下:
相比于作业上给出的模板,本代码没有使用from lr_utils import load_dataset,lr_utils本身不是一个包,是一个同目录下自己写的python文件,我是把里面的函数拿出来放到本代码里了。

import numpy as np
import matplotlib.pyplot as plt
import pylab
import h5py
import scipy
from PIL import Image
from scipy import ndimage

# 数据导入
def load_dataset():
    train_dataset = h5py.File('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('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

# 具体实现函数
# sigomid激活函数
def sigmoid(s):
    s = 1. / (1. + np.exp(-s))
    return s

# 矩阵初始化为0
def init_with_zero(dim):
    w = np.zeros(shape = (dim, 1), dtype = np.float32)
    b = 0
    assert(w.shape == (dim, 1))
    assert(isinstance(b, float) or isinstance(b, int))
    return w, b

# 计算估计值和偏导数----->对于单个神经元
def propagate(w, b, X, Y):
    # 正向传播
    m = X.shape[1]
    A = sigmoid(np.dot(w.T, X) + b)  # w是列向量,A是行向量,Y是行向量
    cost = -1.0 / m * (np.dot(Y, np.log(A.T)) + np.dot((1.0 - Y), np.log((1.0 - A).T)))
    # 反向传播
    dw = 1./m * np.dot(X, (A - Y).T)
    db = 1./m * np.sum(A - Y, axis = 1)
    grads = {"dw": dw,
             "db": db}
    return grads, cost

# 梯度下降法求参数w和b(机器学习过程)
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
    costs = []
    for i in range(num_iterations):
        grads, cost = propagate(w, b, X, Y)
        dw = grads['dw']
        db = grads['db']
        # 修正w和b
        w = w - learning_rate * dw
        b = b - learning_rate * db

        if i % 100 == 0:
            costs.append(cost)
            if print_cost:
                print("cost after iterations %d : %f" %(i, cost))
    params = {'w' : w,
              'b' : b}
    grads = {'dw' : dw,
             'db' : db}
    return params, grads, costs

# 利用学习得来的参数w和b进行预测
def predict(w, b, X):
    m = X.shape[1]
    Y_prediction = np.zeros((1, m))
    w = w.reshape(X.shape[0], 1)
    # 求预测值
    A = sigmoid(np.dot(w.T, X) + b)
    # 存放到Y_prediction中
    for i in range(A.shape[1]):
        if A[0, i] > 0.5:
            Y_prediction[0, i] = 1
        else:
            Y_prediction[0, i] = 0
    return Y_prediction

# 最终模型
def model(X_train, Y_train, X_test, Y_test, num_iterations = 1000, learning_rate = 0.005, print_cost = False):
    # 使用随机数构建w向量
    w, b = init_with_zero(X_train.shape[0])
    # 梯度下降法
    parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate)
    # 求预测值
    w = parameters['w']
    b = parameters['b']
    Y_prediction_test = predict(w, b, X_test)
    Y_prediction_train = predict(w, b, X_train)
    # 与最终结果的拟合度
    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

'''                            正文                           '''
# 加载文件
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()

# 显示数据集信息
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[1]

# 数据预处理
train_set_x_flatten = train_set_x_orig.reshape(m_train, -1).T
test_set_x_flatten = test_set_x_orig.reshape(m_test, -1).T

# 数据的中心化和标准化
train_set_x = train_set_x_flatten / 255.0
test_set_x = test_set_x_flatten / 255.0
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)

# 以可视化的方式显示模型的相关信息
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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值