【机器学习】线性模型之逻辑回归

文章目录

  • 逻辑回归
    • Sigmoid 函数
    • 概率输出结果
    • 预测值与真实标签之间的并不匹配
    • 交叉熵
    • 逻辑回归模型
  • 梯度下降
  • 逻辑回归模型求解
  • 编程求解
  • sklearn 实现,并查看拟合指标

逻辑回归

逻辑回归是一种广义线性模型,形式上引入了 S i g m o i d Sigmoid Sigmoid 函数映射,是非线性模型。但本质上,逻辑回归仍然是一个线性回归模型,因为除去 S i g m o i d Sigmoid Sigmoid 映射函数关系,其他的步骤和算法都是线性回归的。

下面,考虑一个二分类问题 f : R p → { 0 , 1 } f : R^p → \{0, 1\} f:Rp{0,1}

Sigmoid 函数

σ ( z ) = 1 1 + e − z \sigma(z) = \frac{1}{1+e^{-z}} σ(z)=1+ez1
【机器学习】线性模型之逻辑回归_第1张图片
引入 S i g m o i d Sigmoid Sigmoid 函数,将线性函数预测值转换成概率值
{ p ( y i = 1 ∣ x i ) = 1 1 + e − ( w T x i + b ) p ( y i = 0 ∣ x i ) = e − ( w T x i + b ) 1 + e − ( w T x i + b ) \begin{cases} p(y_i = 1|x_i) = \large \frac{1}{1+e^{−(w^Tx_i+b)}} \\ p(y_i = 0|x_i) = \large \frac{e^{−(w^Tx_i+b)}}{1+e^{−(w^Tx_i+b)}} \end{cases} p(yi=1∣xi)=1+e(wTxi+b)1p(yi=0∣xi)=1+e(wTxi+b)e(wTxi+b)

概率输出结果

  • 考虑模型参数为 w = ( 1 , 1 ) T , b = − 1 w=(1,1)^T,b=-1 w=(1,1)T,b=1
  • 4 个来自不同类别的样本
    { ( x 1 , y 1 = 0 ) , ( x 2 , y 1 = 1 ) , ( x 3 , y 3 = 1 ) , ( x 4 , y 4 = 0 ) } \{(x_1,y_1=0),(x_2,y_1=1),(x_3,y_3=1),(x_4,y_4=0)\} {(x1,y1=0),(x2,y1=1),(x3,y3=1),(x4,y4=0)}
  • 计算不同样本的输出结果:
    x 1 = ( 0.5 , 1 ) ,   p 1 = 1 1 + exp ⁡ ( − ( 0.5 ∗ 1 + 1 ∗ 1 − 1 ) ) = 0.62 x 2 = ( 1 , 2 ) ,   p 2 = 1 1 + exp ⁡ ( − ( 1 ∗ 1 + 2 ∗ 1 − 1 ) ) = 0.88 x 3 = ( − 0.2 , 1 ) ,   p 3 = 1 1 + exp ⁡ ( − ( − 0.2 ∗ 1 + 1 ∗ 1 − 1 ) ) = 0.45 x 4 = ( 1 , − 3 ) ,   p 4 = 1 1 + exp ⁡ ( − ( 1 ∗ 1 + 3 ∗ 1 − 1 ) ) = 0.05 \begin{aligned} & x_{1} =(0.5,1),~p_1=\frac{1}{1+\exp(-(0.5*1+1*1-1))}=0.62 \\ & x_{2} =(1,2),~p_2=\frac{1}{1+\exp(-(1*1+2*1-1))}=0.88 \\ & x_{3} =(-0.2,1),~p_3=\frac{1}{1+\exp(-(-0.2*1+1*1-1))}=0.45 \\ & x_{4} =(1,-3),~p_4=\frac{1}{1+\exp(-(1*1+3*1-1))}=0.05 \end{aligned} x1=(0.5,1), p1=1+exp((0.51+111))1=0.62x2=(1,2), p2=1+exp((11+211))1=0.88x3=(0.2,1), p3=1+exp((0.21+111))1=0.45x4=(1,3), p4=1+exp((11+311))1=0.05

预测值与真实标签之间的并不匹配

特征 输出概率(p) 预测标签  ( y ^ ) 真实标签  ( y ) x 1 0.62 1 0 x 2 0.88 1 1 x 3 0.45 0 1 x 4 0.05 0 0 \begin{array}{c|c|c|c|c}\hline\text{特征}&\text{输出概率(p)}&\text{预测标签 }(\hat{y})&\text{真实标签 }(y)\\\hline x_1&0.62&1&0\\\hline x_2&0.88&1&1\\\hline x_3&0.45&0&1\\\hline x_4&0.05&0&0\\\hline\end{array} 特征x1x2x3x4输出概率(p)0.620.880.450.05预测标签 (y^)1100真实标签 (y)0110

交叉熵

ℓ ( y , p ) = − ( y l o g ( p ) + ( 1 − y ) l o g ( 1 − p ) ) ℓ(y, p) = −(y log(p) + (1 − y)log(1 − p)) (y,p)=(ylog(p)+(1y)log(1p))

  • x 1 , p 1 = 0.62 , y 1 = 0 x_1,p_1=0.62,y_1=0 x1,p1=0.62,y1=0,代入交叉熵函数,得到: ℓ ( y 1 , p 1 ) = − ( y 1 log ⁡ p 1 + ( 1 − y 1 ) log ⁡ ( 1 − p 1 ) ) = 0.968 \ell(y_1,p_1)=-(y_1\log p_1+(1-y_1)\log(1-p_1))=0.968 (y1,p1)=(y1logp1+(1y1)log(1p1))=0.968

  • x 2 , p 2 = 0.88 , y 2 = 1 x_2,p_2=0.88,y_2=1 x2,p2=0.88,y2=1,代入交叉熵函数,得到: ℓ ( y 2 , p 2 ) = − ( y 2 log ⁡ p 2 + ( 1 − y 2 ) log ⁡ ( 1 − p 2 ) ) = 0.128 \ell(y_2,p_2)=-(y_2\log p_2+(1-y_2)\log(1-p_2))=0.128 (y2,p2)=(y2logp2+(1y2)log(1p2))=0.128

  • x 3 , p 3 = 0.45 , y 3 = 1 x_3, p_3= 0.45, y_3= 1 x3,p3=0.45,y3=1,代入交叉熵函数,得到: ℓ ( y 3 , p 3 ) = − ( y 3 log ⁡ p 3 + ( 1 − y 3 ) log ⁡ ( 1 − p 3 ) ) = 0.799 \ell(y_3,p_3)=-(y_3\log p_3+(1-y_3)\log(1-p_3))=0.799 (y3,p3)=(y3logp3+(1y3)log(1p3))=0.799

  • x 4 , p 4 = 0.05 , y 4 = 0 x_4,p_4=0.05,y_4=0 x4,p4=0.05,y4=0,代入交叉熵函数,得到: ℓ ( y 4 , p 4 ) = − ( y 4 log ⁡ p 4 + ( 1 − y 4 ) log ⁡ ( 1 − p 4 ) ) = 0.051 \ell(y_4,p_4)=-(y_4\log p_4+(1-y_4)\log(1-p_4))=0.051 (y4,p4)=(y4logp4+(1y4)log(1p4))=0.051

逻辑回归模型

给出包含特征和标签的实际问题中:
D = { ( x i , y i ) } i = 1 n D = \{(x_i , y_i)\}^n_{i=1} D={(xi,yi)}i=1n
通过最小化所有样本的平均交叉熵损失估计模型的参数 w w w b b b

逻辑回归模型:
m i n L ( w , b ) minL(w, b) minL(w,b) 其中:
L ( w , b ) = 1 n ∑ i = 1 n ℓ ( y i , p i ) L(w, b) = \frac{1}{n} ∑^n_{i=1} ℓ(y_i , p_i) L(w,b)=n1i=1n(yi,pi)
高斯-赛德尔求非线性方程组

梯度下降

  • 考虑光滑函数的凸优化问题 min ⁡ f ( w ) \min f(w) minf(w),梯度下降法的迭代规则 w t + 1 = w t − α ∇ f ( w t ) w_{t+1}=w_t-\alpha\nabla f(w_t) wt+1=wtαf(wt) 有:
    f ( w t + 1 ) ≤ f ( w t ) + ⟨ ∇ f ( w t ) , w t + 1 − w t ⟩ + L 2 ∥ w t + 1 − w t ∣ ∣ ≤ f ( w t ) − α ∥ ∇ f ( w t ) ∥ 2 + L 2 α ∥ ∇ f ( w t ) ∥ 2 = f ( w t ) − α ( 1 − 1 2 L α ) ∥ ∇ f ( w t ) ∥ 2 \begin{aligned} f(w_{t+1})& \leq f(w_{t})+\langle\nabla f(w_{t}),w_{t+1}-w_{t}\rangle+\frac{L}{2}\|w_{t+1}-w_{t}|| \\ &\leq f(w_{t})-\alpha\|\nabla f(w_{t})\|^{2}+\frac{L}{2}\alpha\|\nabla f(w_{t})\|^{2} \\ &=f(w_{t})-\alpha(1-\frac{1}{2}L\alpha)\|\nabla f(w_{t})\|^{2} \end{aligned} f(wt+1)f(wt)+f(wt),wt+1wt+2Lwt+1wt∣∣f(wt)α∥∇f(wt)2+2Lα∥∇f(wt)2=f(wt)α(121)∥∇f(wt)2
  • 选择 0 < α < 2 7 0<\alpha<\frac{2}{7} 0<α<72 使得 α ( 1 − 1 2 L α ) > 0 \alpha(1-\frac{1}{2}L\alpha)>0 α(121)>0,那么每次 迭代之后,目标函数值都会下降。
  • 根据单调有界定理,目标函数值最终将会收敛。

逻辑回归模型求解

  • 考虑逻辑回归模型:
    min ⁡ w , b L ( w , b ) : = − 1 n ∑ i = 1 n ( y i log ⁡ ( p i ) + ( 1 − y i ) log ⁡ ( 1 − p i ) ) \min_{w,b}L(w,b):=-\dfrac{1}{n}\sum_{i=1}^{n}(y_i\log(p_i)+(1-y_i)\log(1-p_i)) w,bminL(w,b):=n1i=1n(yilog(pi)+(1yi)log(1pi))

  • 计算损失函数的梯度:
    ∂ L ∂ w = − 1 n ∑ i = 1 n ∂ ∂ w ( y i log ⁡ ( p i ) + ( 1 − y i ) log ⁡ ( 1 − p i ) ) = − 1 n ∑ i = 1 n ( y i p i − 1 − y i 1 − p i ) ∂ p i ∂ w \begin{aligned} \frac{\partial L}{\partial w} & = -\frac1n\sum_{i=1}^n\frac{\partial}{\partial w} (y_i\log(p_i)+(1-y_i)\log(1-p_i)) \\\\ & = -\frac1n\sum_{i=1}^n(\frac{y_i}{p_i}-\frac{1-y_i}{1-p_i})\frac{\partial p_i}{\partial w} \end{aligned} wL=n1i=1nw(yilog(pi)+(1yi)log(1pi))=n1i=1n(piyi1pi1yi)wpi

  • 需要先计算
    ∂ p ∂ w = ∂ ∂ w ( 1 1 + exp ⁡ ( − ( ⟨ w , x i ⟩ + b ) ) ) = exp ⁡ ( − ( ⟨ w , x i ⟩ + b ) ) x i ( 1 + exp ⁡ ( − ( ⟨ w , x i ⟩ + b ) ) ) 2 = p i ( 1 − p i ) x i \begin{aligned} \frac{\partial p}{\partial w}& =\frac{\partial}{\partial w}(\frac{1}{1+\exp(-(\langle w,x_i\rangle+b))}) \\ &=\frac{\exp(-(\langle w,x_i\rangle+b))x_i}{(1+\exp(-(\langle w,x_i\rangle+b)))^2} \\ &=p_i(1-p_i)x_i \end{aligned} wp=w(1+exp((⟨w,xi+b))1)=(1+exp((⟨w,xi+b)))2exp((⟨w,xi+b))xi=pi(1pi)xi

  • 将其代入回上式,计算得到:
    ∂ L ∂ w = − 1 n ∑ i = 1 n ( y i p i − 1 − y i 1 − p i ) ∂ p i ∂ w = 1 n ∑ i = 1 n ( p i − y i ) x i \frac{\partial L}{\partial w}=-\frac{1}{n}\sum_{i=1}^{n}(\frac{y_i}{p_i}-\frac{1-y_i}{1-p_i})\frac{\partial p_i}{\partial w}=\frac{1}{n}\sum_{i=1}^{n}(p_i-y_i)x_i wL=n1i=1n(piyi1pi1yi)wpi=n1i=1n(piyi)xi

  • 同理,可得:
    ∂ L ∂ b = − 1 n ∑ i = 1 n ( y i p i − 1 − y i 1 − p i ) ∂ p i ∂ b = 1 n ∑ i = 1 n ( p i − y i ) \frac{\partial L}{\partial b}=-\frac1n\sum_{i=1}^n(\frac{y_i}{p_i}-\frac{1-y_i}{1-p_i})\frac{\partial p_i}{\partial b}=\frac1n\sum_{i=1}^n(p_i-y_i) bL=n1i=1n(piyi1pi1yi)bpi=n1i=1n(piyi)

  • 基于梯度下降的逻辑回归迭代规则,给定初始值 w 1 , b 1  ⁣ : w_1,b_1\colon w1,b1:
    { w t + 1 = w t − α n ∑ i = 1 n ( p i ( t ) − y i ) x i b t + 1 = b t − α n ∑ i = 1 n ( p i ( t ) − y i ) \begin{cases} w_{t+1}=w_t-\frac{\alpha}{n}\sum_{i=1}^n(p_i^{(t)}-y_i)x_i \\\\ b_{t+1}=b_t-\frac{\alpha}{n}\sum_{i=1}^n(p_i^{(t)}-y_i) \end{cases} wt+1=wtnαi=1n(pi(t)yi)xibt+1=btnαi=1n(pi(t)yi)

  • 其中,
    p i ( t ) = 1 1 + exp ⁡ ( − ( ⟨ w t , x i ⟩ + b t ) ) p_i^{(t)}=\frac1{1+\exp(-(\langle w_t,x_i\rangle+b_t))} pi(t)=1+exp((⟨wt,xi+bt))1

编程求解

import numpy as np

def sigma_fun(z):
    z = z.astype('float')
    z_ravel = z.ravel()  # 将 numpy 数组展平
    length = len(z_ravel)
    ls = []
    for index in range(length):
        if z_ravel[index] >= 0:
            ls.append(1.0 / (1 + np.exp(-z_ravel[index])))
        else:
            ls.append(np.exp(z_ravel[index]) / (np.exp(z_ravel[index]) + 1))
    return np.array(ls).reshape(z.shape)

def cross_entropy(y, p):
    return -(y * np.log(p + 0.0000001) + (1 - y) * np.log(1 - p + 0.0000001))

def gradient_descent(X, y, W, b, alpha, t):
    for i in range(t):
        z = np.dot(X, W) + b
        p = sigma_fun(z)
        loss = cross_entropy(y, p)
        print('第 {} 次迭代的权重参数为:{}'.format(i, W.round(6).tolist()))
        print('第 {} 次迭代的偏置参数为:{}'.format(i, b))
        print('第 {} 次迭代的平均损失为:{}'.format(i, np.mean(loss).round(6)))
        nablaLW = np.sum((p - y) * X, axis=0).reshape(X.shape[1], 1)
        W = W - (alpha / X.shape[0]) * nablaLW
        nablaLb = np.sum(p - y)
        b = b - (alpha / X.shape[0]) * nablaLb
        print('第 {} 次迭代的梯度参数 W 为:{}'.format(i, nablaLW.round(6).tolist()))
        print('第 {} 次迭代的梯度参数 b 为:{}\n'.format(i, nablaLb))


X = np.array([[0.5, 1], [1, 2], [-0.2, 1], [1, -3]])
y = np.array([[0], [1], [1], [0]])

b = -1
W = np.ones((X.shape[1], 1))
alpha = 0.5

print('步长 α 为:{}\n'.format(alpha))
gradient_descent(X, y, W, b, alpha, 6)
# output
步长 α 为:0.50 次迭代的权重参数为:[[1.0], [1.0]]0 次迭代的偏置参数为:-10 次迭代的平均损失为:0.4869330 次迭代的梯度参数 W 为:[[0.349419], [-0.308058]]0 次迭代的梯度参数 b 为:0.00084828504482574451 次迭代的权重参数为:[[0.956323], [1.038507]]1 次迭代的偏置参数为:-1.00010603563060331 次迭代的平均损失为:0.4803791 次迭代的梯度参数 W 为:[[0.345769], [-0.265492]]1 次迭代的梯度参数 b 为:0.0131704400155699332 次迭代的权重参数为:[[0.913102], [1.071694]]2 次迭代的偏置参数为:-1.00175234063254952 次迭代的平均损失为:0.4745922 次迭代的梯度参数 W 为:[[0.341829], [-0.232955]]2 次迭代的梯度参数 b 为:0.022393390716281723 次迭代的权重参数为:[[0.870373], [1.100813]]3 次迭代的偏置参数为:-1.00455151447208473 次迭代的平均损失为:0.4693423 次迭代的梯度参数 W 为:[[0.337668], [-0.207736]]3 次迭代的梯度参数 b 为:0.029246570559326564 次迭代的权重参数为:[[0.828164], [1.12678]]4 次迭代的偏置参数为:-1.00820733579200054 次迭代的平均损失为:0.4644894 次迭代的梯度参数 W 为:[[0.333348], [-0.187982]]4 次迭代的梯度参数 b 为:0.034283852149878865 次迭代的权重参数为:[[0.786496], [1.150278]]5 次迭代的偏置参数为:-1.01249281731073535 次迭代的平均损失为:0.4599435 次迭代的梯度参数 W 为:[[0.328922], [-0.172379]]5 次迭代的梯度参数 b 为:0.03792999829875388

sklearn 实现,并查看拟合指标

from sklearn.linear_model import LogisticRegression as LR
import pandas as pd
import numpy as np

X = np.array([[0.5, 1], [1, 2], [-0.2, 1], [1, -3]])
y = np.array([0, 1, 1, 0])

lr = LR()
lr.fit(X, y)

predicted = lr.predict(X)
print('预测值:', predicted)

Accuracy = ((predicted == y).sum() / len(y))
print('准确率:', Accuracy)

TP = sum((y == 1) & (predicted == 1))
FP = sum((y == 0) & (predicted == 1))
Precision = TP / (TP + FP)
print('精确率:', round(Precision, 3))

Recall = ((predicted == y).sum() / y.sum()).round(3)
print('召回率:', Recall)

F1 = 2 * Precision * Recall / (Precision + Recall)
print('F1 score值:', round(F1, 3))
# output
预测值: [1 1 1 0]
得分: 0.75
准确率: 0.75
精确率: 0.667
召回率: 1.5
F1 score值: 0.923

你可能感兴趣的:(机器学习,机器学习,逻辑回归,人工智能)