Python实现逻辑回归对比试验(四)

数据说明

​ 我们将建立一个逻辑回归模型来预测一个学生是否被大学录取。假设你是一个大学系的管理员,你想根据两次考试的结果来决定每个申请人的录取机会。你有以前的申请人的历史数据,你可以用它作为逻辑回归的训练集。对于每一个培训例子,你有两个考试的申请人的分数和录取决定。为了做到这一点,我们将建立一个分类模型,根据考试成绩估计入学概率。

​ 以下截取部分数据

34.62365962451697,78.0246928153624,0
30.28671076822607,43.89499752400101,0
35.84740876993872,72.90219802708364,0
60.18259938620976,86.30855209546826,1
79.0327360507101,75.3443764369103,1
45.08327747668339,56.3163717815305,0
61.10666453684766,96.51142588489624,1
75.02474556738889,46.55401354116538,1
76.09878670226257,87.42056971926803,1

第一列代表的是成绩一,第二列代表的是成绩二,第三列代表的是录取情况

数据可视化

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import time
# 导入数据集
path = 'data' + os.sep + 'LogiReg_data.txt'
pdData = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
pdData.head()
print('数据集为:')
print(pdData)

# 利用画图工具将数据放在二维坐标之内
positive = pdData[pdData['Admitted'] == 1]
negative = pdData[pdData['Admitted'] == 0]
fig, ax = plt.subplots(figsize=(10,5))
ax.scatter(positive['Exam 1'], positive['Exam 2'], s=30, c='b', marker='o', label='Admitted')
ax.scatter(negative['Exam 1'], negative['Exam 2'], s=30, c='r', marker='x', label='Not Admitted')
ax.legend()
ax.set_xlabel('Exam 1 Score')
ax.set_ylabel('Exam 2 Score')
plt.show()

在这里插入图片描述

步骤

  1. 定义sigmoid函数

    # 定义sigmoid函数
    def sigmoid(z):
        return 1/(1+np.exp(-z))
    
  2. 定义预测函数 h θ ( x ) = g ( θ T x ) = 1 1 + e − θ T x h_\theta(x)=g(\theta^Tx)=\frac{1}{1+e^{-\theta^Tx}} hθ(x)=g(θTx)=1+eθTx1

    def model(x, theta):
        return sigmoid(np.dot(x, theta.T))
    
  3. 对数据进行处理,第一列添加“1”,方便矩阵运算

    pdData.insert(0, 'Ones', 1)
    orig_data = pdData.as_matrix()  # 将得到的数据转换为矩阵,方便处理
    cols = orig_data.shape[1]
    x = orig_data[:, 0:cols-1]
    y = orig_data[:, cols-1:cols]
    theta = np.zeros([1, 3])  # 初始化参数值
    
  4. 定义损失函数 l ( θ ) = L ( θ ) = ∑ i = 1 m ( y i l o g h θ ( x i ) + ( 1 − y i ) l o g ( 1 − h θ ( x ) ) ) l(\theta)=L(\theta)=\sum_{i=1}^m\Big(y_ilogh_\theta(x_i)+(1-y_i)log(1-h_\theta(x))) l(θ)=L(θ)=i=1m(yiloghθ(xi)+(1yi)log(1hθ(x))) ,引入 J ( θ ) = − 1 m l ( θ ) J(\theta)=-\frac{1}{m}l(\theta) J(θ)=m1l(θ)

    # 定义损失函数
    def cost(x, y, theta):
        left = np.multiply(-y, np.log(model(x, theta)))
        right = np.multiply(1 - y, np.log(1 - model(x, theta)))
        return np.sum(left - right) / (len(x))
    

5.定义梯度下降,通过对损失函数求偏导,不清楚的可以看一下上一篇博客

# 定义梯度下降
def gradient(X, y, theta):
    grad = np.zeros(theta.shape)
    error = (model(X, theta) - y).ravel()
    for j in range(len(theta.ravel())):
        term = np.multiply(error, X[:, j])
        grad[0, j] = np.sum(term) / len(X)
    return grad

6.定义不同的停止策略

# 以下是三种不同的停止策略
STOP_ITER = 0  # 按照迭代次数
STOP_COST = 1  # 按照损失值
STOP_GRAD = 2  # 按照梯度的变化


def stopCriterion(type, value, threshold):
    if type == STOP_ITER:
        return value > threshold
    if type == STOP_COST:
        return abs(value[-1]-value[-2])<threshold
    if type == STOP_GRAD:
        return np.linalg.norm(value)<threshold  # 计算梯度值的算术平方根

损失值:对比前后两次的损失值差异的大小

梯度:当所有的梯度的算数平方根小于指定的阈值的时候停止

  1. 数据的清洗

    # 对数据进行洗牌
    def shuffleData(data):
        np.random.shuffle(data)
        cols = data.shape[1]
        x = data[:, 0:cols-1]
        y = data[:, cols-1:]
        return x,y
    

避免数据的排序存在一定的规律,对实验的结果产生一定的影响

  1. 运行

    def descent(data, theta, batchSize, stopType, thresh, alpha):
        init_time = time.time()
        i = 0 # 迭代次数
        k = 0 # batch
        x,y = shuffleData(data)
        grad = np.zeros(theta.shape) # 计算的梯度
        costs = [cost(x,y,theta)] # 损失值
    
        while True:
            grad = gradient(x[k:k+batchSize],y[k:k+batchSize],theta)
            k += batchSize # 取batchsize个数量的数据
            if k >=data.shape[0]:
                k = 0
                x,y = shuffleData(data) # 重新洗牌
            theta = theta - alpha*grad
            costs.append(cost(x, y, theta)) # 计算新的损失
            i += 1
    
            # 停止条件
            if stopType == STOP_ITER:
                value = i
            if stopType == STOP_COST:
                value = costs
            if stopType == STOP_GRAD:
                value = grad
            if stopCriterion(stopType, value, thresh):
                break
        return theta, i-1, costs, grad, time.time() - init_time
    
    
    def runExpe(data, theta, batchSize, stopType, thresh, alpha):
        theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha)
        fig, ax = plt.subplots(figsize=(12,4))
        ax.plot(np.arange(len(costs)), costs, 'r')
        ax.set_xlabel('Iterations')
        ax.set_ylabel('Cost')
        plt.show()
        print('迭代时间:',dur)
    
  2. 几个对比试验:

    # 实验一:批量梯度下降,停止条件为迭代次数
    # runExpe(orig_data, theta, batchSize=100,stopType=STOP_ITER, thresh=5000, alpha=0.000001)
    

在这里插入图片描述

​ 批量梯度下降、迭代次数5000
迭代时间: 6.470702886581421

# 实验二:批量梯度下降,停止条件为损失值,增大步长
# runExpe(orig_data, theta, batchSize=100,stopType= STOP_COST, thresh=0.000001, alpha=0.001)

在这里插入图片描述

根据损失值停止
迭代时间: 261.9208984375

# 实验三:批量梯度下降,停止条件为梯度的变化
# runExpe(orig_data, theta, batchSize=100, stopType=STOP_GRAD, thresh=0.05, alpha=0.001)

在这里插入图片描述

根据梯度的变化、停止
迭代时间: 54.62109398841858

# 实验四:随机梯度下降,步长为0.000001
# runExpe(orig_data, theta, 1, STOP_ITER, thresh=5000, alpha=0.000001)

在这里插入图片描述

随机梯度下降,
步长为0.000001
迭代时间: 2.414062738418579

# 实验五:随机梯度下降,步长为0.001
# runExpe(orig_data, theta, 1, STOP_ITER, thresh=5000, alpha=0.001)

在这里插入图片描述

随机梯度下降,步长为0.001
迭代时间: 6.755859375

# 实验六:小批量梯度下降
# runExpe(orig_data, theta, 16, STOP_ITER, thresh=15000, alpha=0.001)

在这里插入图片描述
小批量梯度下降
迭代时间: 27.3564453125
步长为:0.001

# 实验七:先对数据进行预处理,使之成正态分布,再进行小批量梯度下降
# 对数据进行标准化 将数据按其属性(按列进行)减去其均值,然后除以其方差。最后得到的结果是,对每个属性/每列来说
# 所有数据都聚集在0附近,方差值为1
from sklearn import preprocessing as pp


scaled_data = orig_data.copy()
scaled_data[:, 1:3] = pp.scale(orig_data[:, 1:3])

runExpe(scaled_data, theta, 16, STOP_ITER, thresh=5000, alpha=0.001)

在这里插入图片描述

步长为:0.001
迭代时间: 9.232421636581421

#精确度,设定阈值
def predict(X, theta):
    return [1 if x >= 0.5 else 0 for x in model(X, theta)]

scaled_X = scaled_data[:, :3]
y = scaled_data[:, 3]
predictions = predict(scaled_X, theta)
correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y)]
accuracy = (sum(map(int, correct)) % len(correct))
print ('accuracy = {0}%'.format(accuracy))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值