机器学习-逻辑回归

转自,凯神师傅。https://blog.csdn.net/wyk1823376647/article/details/79270288

逻辑回归主要思想:针对现有数据对分类边界建立回归公式,以此进行分类。

回归表示最佳拟合就是寻找能最好拟合数据的参数。

这里写图片描述

  • 自变量为任意实数,值域为为[0,1]
  • 解释:将任意的输入映射到[0,1]区间,我们在线性回归中可以得到一个预测值,再将该值映射到 Sigmoid 函数中,这样就完成了由值到概率的转换,也就是分类任务

这里写图片描述

推导过程: 
这里写图片描述

  • 分类任务:

P(y = 1 | x;θ) = hθ(x)hθ(x) 
P(y = 0 | x;θ) = 1 - hθ(x)hθ(x)

  • 整合: 
    P(y | x;θ) = (hθ(x))y(1−hθ(x))1−y(hθ(x))y(1−hθ(x))1−y
  • 对于二分类任务(0,1)整合后: 
    y 取 0只保留:(1−hθ(x))1−y(1−hθ(x))1−y 
    y 取1只保留: (hθ(x))y(hθ(x))y

  • 似然函数: 
    这里写图片描述

  • 求导过程: 
    这里写图片描述

  • 参数更新: 
    θj:=θj−α1m∑ni=1(hθ(xi)−yi)xjiθj:=θj−α1m∑i=1n(hθ(xi)−yi)xij

    • α :学习率,更新的力度(不能大,不能小)
    • (hθ(xi)−yi)xji(hθ(xi)−yi)xij : 偏导方向
    • α1m∑ni=1(hθ(xi)−yi)xjiα1m∑i=1n(hθ(xi)−yi)xij : 更新的结果值
  • 对于二分类使用上述方法,多分类怎么办呢? 
    这里写图片描述

实现过程:

#三大件
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#%将那些用matplotlib绘制的图显示在页面里而不是弹出一个窗口
%matplotlib inline 
  •  
import os
# os.sep是目录连接符lunux下是/ ;window下是\\,读取是相对路径 data\\LogiReg_data.txt
path = 'data' + os.sep + 'LogiReg_data.txt'
pdData = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
#显示头五行数据
pdData.head()
  • 这里写图片描述
# 查看矩阵的shape
pdData.shape
  •  

(100,3)

positive = pdData[pdData['Admitted'] == 1] # returns the subset of rows such Admitted = 1, i.e. the set of *positive* examples
negative = pdData[pdData['Admitted'] == 0] # returns the subset of rows such Admitted = 0, i.e. the set of *negative* examples
#将数据的分布,绘画显示
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')
  •  

这里写图片描述

#在数据第一列加入全为 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])
  •  
  • 逻辑回归要实现的目标: 
    • 建立分类器: 
      • 因为数据有两个特征,所以假设函数为:y=θ0+θ1x1+θ2x2y=θ0+θ1x1+θ2x2
      • 求θ0,θ1,θ2(θ0θ0,θ1,θ2(θ0对应偏执项)
      • 为了求解,引入x0x0 = 1(即加入全为1的一列)
      • 即 y=θ0x0+θ1x1+θ2x2=θTxy=θ0x0+θ1x1+θ2x2=θTx
  • 设定阈值: 根据阈值判断录取结果

  • 要完成的模块:

    • sigmoid : 映射到概率的函数
    • model : 返回预测结果值(矩阵乘法θTxθTx)
    • cost : 根据参数计算损失(对数似然函数的负值的平均值,用于评测算法,越小越好)
    • gradient : 计算每个参数的梯度方向
    • descent : 进行参数更新
    • accuracy: 计算精度
# sigmoid
def sigmoid(z):
    return 1 / (1 + np.exp(-z))

# model
def model(X, theta):
    return sigmoid(np.dot(X, theta.T))
  •  
  • cost(损失函数): 
    • 将对数似然函数去负号: 
      • L(hθ(x),y)=−ylog(hθ(x))−(1−y)log(1−hθ(x))L(hθ(x),y)=−ylog(hθ(x))−(1−y)log(1−hθ(x))
    • 计算平均值: 
      • 1n∑ni=1L(hθ(x),y)1n∑i=1nL(hθ(x),y)
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))
  •  
  • 计算梯度: 
    • ∂j∂θj=−1m∑ni=1(yi−hθ(xi))xij∂j∂θj=−1m∑i=1n(yi−hθ(xi))xij
def gradient(X, y, theta):
    grad = np.zeros(theta.shape)
    error = (model(X, theta)- y).ravel()
    for j in range(len(theta.ravel())): #for each parmeter
        term = np.multiply(error, X[:,j])
        grad[0, j] = np.sum(term) / len(X)

    return grad
  •  
  • 比较三种不同梯度下降方法
STOP_ITER = 0
STOP_COST = 1
STOP_GRAD = 2

def stopCriterion(type, value, threshold):
    #设定三种不同的停止策略
    if type == STOP_ITER:        return value > threshold
    elif type == STOP_COST:      return abs(value[-1]-value[-2]) < threshold
    elif type == STOP_GRAD:      return np.linalg.norm(value) < threshold
  •  
#洗牌,每次梯度下降取样本前要把数据集的顺序打乱
#使得模型的泛化能力更强
def shuffleData(data):
    # 随机排序函数shuffle
    np.random.shuffle(data)
    cols = data.shape[1]
    X = data[:, 0:cols-1]
    y = data[:, cols-1:]
    return X, y
  •  
import time

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 #取batch数量个数据
        if k >= n: 
            k = 0 
            X, y = shuffleData(data) #重新洗牌
        theta = theta - alpha*grad # 参数更新
        costs.append(cost(X, y, theta)) # 计算新的损失
        i += 1 

        if stopType == STOP_ITER:       value = i
        elif stopType == STOP_COST:     value = costs
        elif 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):
    #import pdb; pdb.set_trace();
    #执行一次梯度下降
    theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha)
    name = "Original" if (data[:,1]>2).sum() > 1 else "Scaled"
    name += " data - learning rate: {} - ".format(alpha)
    if batchSize==n: strDescType = "Gradient"
    elif batchSize==1:  strDescType = "Stochastic"
    else: strDescType = "Mini-batch ({})".format(batchSize)
    name += strDescType + " descent - Stop: "
    if stopType == STOP_ITER: strStop = "{} iterations".format(thresh)
    elif stopType == STOP_COST: strStop = "costs change < {}".format(thresh)
    else: strStop = "gradient norm < {}".format(thresh)
    name += strStop
    print ("***{}\nTheta: {} - Iter: {} - Last cost: {:03.2f} - Duration: {:03.2f}s".format(
        name, theta, iter, costs[-1], dur))
    fig, ax = plt.subplots(figsize=(12,4))
    ax.plot(np.arange(len(costs)), costs, 'r')
    ax.set_xlabel('Iterations')
    ax.set_ylabel('Cost')
    ax.set_title(name.upper() + ' - Error vs. Iteration')
    return theta
  • 每次迭代都遍历所有的样本

  • STOP_ITER 按迭代次数进行停止

    • 迭代次数 thresh=5000
  • 学习率:alpha=0.000001
#选择的梯度下降方法是基于所有样本的
n=100
runExpe(orig_data, theta, n, STOP_ITER, thresh=5000, alpha=0.000001)
  • 这里写图片描述
  • STOP_COST 根据损失值停止
  • 设定阈值为 1e−61e−6,差不多需要110 000 次迭代
  • 学习率:alpha=0.001
  • 这种策略虽然准确度较高,但是迭代次数多,计算量大
runExpe(orig_data, theta, n, STOP_COST, thresh=0.000001, alpha=0.001)
  •  

这里写图片描述

  • STOP_GRAD :根据梯度变化停止
  • 设定阈值 thresh=0.05,差不多需要 40 000 次迭代
runExpe(orig_data, theta, n, STOP_GRAD, thresh=0.05, alpha=0.001)
  • 这里写图片描述
  • 1 : 每次迭代一个样本
  • 模型很不稳定,效果很不好
runExpe(orig_data, theta, 1, STOP_ITER, thresh=5000, alpha=0.001)
  • 1

这里写图片描述

  • 迭代次数增多:thresh=15000
  • alpha=0.000002:把学习率调小一些
runExpe(orig_data, theta, 1, STOP_ITER, thresh=15000, alpha=0.000002)
  •  

这里写图片描述

  • 16 :一次迭代 16 个
runExpe(orig_data, theta, 16, STOP_ITER, thresh=15000, alpha=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, n, STOP_ITER, thresh=5000, alpha=0.001)
  •  
  • 原始数据,只能达到达到0.61,而我们得到了0.38个在这里! 所以对数据做预处理是非常重要的。

这里写图片描述

  • 用batch的更合适 (随机梯度下降更快,但是我们需要迭代的次数也需要更多)
runExpe(scaled_data, theta,16, STOP_GRAD, thresh=0.002*2, alpha=0.001)
  •  

这里写图片描述

  • 精度
  • 设定阈值为:0.5 : 
    • 即预测概率大于等于0.5的值为1,小于0.5的值为0,来进行分类
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))
  •  

常用数学符号的 LaTeX 表示方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值