建立一个logstic分类器来识别猫

0.用到的数学公式

$$z^{(i)} = w^T x^{(i)} + b $$
$x^{(i)}$是第i个训练样本
$$\hat{y}^{(i)} = a^{(i)} = sigmoid(z^{(i)})$$
$$ \mathcal{L}(a^{(i)}, y^{(i)}) = - y^{(i)} \log(a^{(i)}) - (1-y^{(i)} ) \log(1-a^{(i)})$$
$$ J = \frac{1}{m} \sum_{i=1}^m \mathcal{L}(a^{(i)}, y^{(i)})$$
$J$ 是损失函数,表示预测值与期望输出值的差值

1.导入包

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.定义σ激活函数

$$sigmoid( w^T x + b) = \frac{1}{1 + e^{-(w^T x + b)}}$$

def sigmoid(z): # z是任何大小的标量或者numpy数组
    s = 1 / (1 + np.exp(-z))
    return s # s -- sigmoid(z)

3.初始化参数

def initialize_with_zeros(dim): # dim - 我们想要的w矢量的大小(或者这种情况下的参数数量)
    w = np.zeros((dim, 1))
    b = 0
    
    assert(w.shape == (dim, 1))
    assert(isinstance(b, float) or isinstance(b, int))
    return w, b # w--初始化形状为(dim, 1)的零矩阵  b - 初始化的标量(对应于偏差)

4.向前传播和向后传播

$$A = \sigma(w^T X + b) = (a^{(0)}, a^{(1)}, ..., a^{(m-1)}, a^{(m)})$$
$$J = -\frac{1}{m}\sum_{i=1}^{m}y^{(i)}\log(a^{(i)})+(1-y^{(i)})\log(1-a^{(i)})$$
$$ \frac{\partial J}{\partial w} = \frac{1}{m}X(A-Y)^T$$
$$ \frac{\partial J}{\partial b} = \frac{1}{m} \sum_{i=1}^m (a^{(i)}-y^{(i)})$$

def propagate(w, b, X, Y):
    # w -- weights, 一个形状为(num_px * num_px * 3, 1)的numpy数组
    # b -- bias, 一个标量
    # X -- 形状为(num_px * num_px * 3, number of examples)的数据集
    # Y -- 形状为(1, number of examples)的判断标签向量 (图片无猫为0, 有猫为1) 
    m = X.shape[1]#数据集列数
    
    A = sigmoid(np.dot(w.T,X) + b)
    cost = (-1/m)*np.sum(Y * np.log(A) + (1 - Y)*np.log(1-A))
    
    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}
    #cost -- 逻辑回归的负对数似然成本
    #dw -- 相对于w的损失梯度, 形状和w一样
    #db -- 相对于b的损失梯度, 形状和b一样
    return grads, cost

5.优化

$$ \theta = \theta - \alpha \text{ } d\theta$$

def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
    # w -- weights, 一个形状为(num_px * num_px * 3, 1)的numpy数组
    # b -- bias, 一个标量
    # X -- 形状为(num_px * num_px * 3, number of examples)的数据集
    # Y -- 形状为(1, number of examples)的判断标签向量 (图片无猫为0, 有猫为1)
    #num_iterations -- 优化循环的迭代次数
    #learning_rate -- 梯度下降更新规则的学习率
    #print_cost -- 是否打印每100步的损失
    costs = []
    for i in range(num_iterations):
        grads, cost = propagate(w, b,X, Y)
        
        dw = grads["dw"]
        db = grads["db"]
        
        w = w - learning_rate * dw
        b = b - learning_rate * db
        
        if i % 100 == 0:
            costs.append(cost)
            
        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}
    #params -- 包含w和b的字典
    #grads -- 包含权重和偏差相对于成本函数的梯度的字典
    #costs -- 在优化过程中计算的所有成本列表,这将用于绘制学习曲线。
    return params, grads, costs

6.预测

$$\hat{Y} = A = \sigma(w^T X + b)$$

def predict(w, b, X):
    # w -- weights, 一个形状为(num_px * num_px * 3, 1)的numpy数组
    # b -- bias, 一个标量
    # X -- 形状为(num_px * num_px * 3, number of examples)的数据集
    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)
    
    for i in range(A.shape[1]):
        if A[0, i] <= 0.5:
            Y_prediction[0, i] = 0
        else:
            Y_prediction[0, i] = 1
    
    assert(Y_prediction.shape == (1, m))
    # Y_prediction -- 包含所有预测(0/1)的numpy数组(向量),用于X中的示例
    return Y_prediction

7.目标模型


def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
    '''
    通过调用之前实现的函数来构建逻辑回归模型
    变量:
    X_train -- 一个形状为(num_px * num_px * 3,m_train)的numpy数组表示的训练集
    Y_train -- 形状为(1,m_train)的numpy数组的训练标签(矢量)
    X_test -- 一个(num_px * num_px * 3,m_test)的numpy数组形式表示测试集
    Y_test -- 由形状(1,m_test)的numpy数组(矢量)表示的测试标签
    num_iterations -- 代表迭代次数的超参数来优化参数
    learning_rate -- 表示在optimize()的更新规则中使用的学习速率的超参数
    print_cost -- 设置为true则以每100次迭代打印成本
    
    返回值:
    d -- 包含关于模型的信息的字典。
    '''
    
    # 用零初始化参数
    w, b = initialize_with_zeros(X_train.shape[0])

    # 梯度下降
    parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
    
    # 从字典“参数”中检索参数w和b
    w = parameters["w"]
    b = parameters["b"]
    
    # 预测测试/训练集的例子
    Y_prediction_test = predict(w, b, X_test)
    Y_prediction_train = predict(w, b, X_train)

    # 打印训练/测试的结果
    print("训练准确性: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
    print("测试准确性: {} %".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()

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 = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.

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

图片描述

第一次写,希望大家能提意见


橙茗
26 声望5 粉丝

python c


引用和评论

0 条评论