和我一起入门机器学习-逻辑回归

逻辑回归

上一篇博客从数学原理和代码角度解释了线性回归,但是该模型只适合特征与预测值呈线性关系的回归场景,接下来我们将介绍逻辑回归,逻辑回归是一种用于二分类问题的机器学习算法。

数学原理

逻辑斯蒂回归(Logistic Regression)虽然名字中有回归,但模型最初是为了解决二分类问题。线性回归模型帮助我们用最简单的线性方程实现了对数据的拟合,但只实现了回归而无法分类。因此LR就是在线性回归的基础上,构建的一种分类模型。

对线性模型进行二分类任务,简单的是通过阶跃函数,即将线性模型的输出值套上一个函数进行分割,大于z的判定为0,小于z的判定为1

但是该分段函数数学性质不好,既不连续也不可微。因此有人提出了对数几率函数,简称Sigmoid函数。
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> y = 1 1 + e − z y=\frac{1}{1+e^{-z}} </math>y=1+e−z1

该函数具有很好的数学性质,既可以用于预测类别,并且任意阶可微,因此可用于求解最优解,将线性函数带进去,可得LR模型为:
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> y = 1 1 + e − w T x + b y=\frac{1}{1+e^{-w^Tx+b}} </math>y=1+e−wTx+b1

损失函数

  • 什么是极大似然估计:通俗理解来说,就是利用已知的样本结果信息,反推最具有可能(最大概率)导致这些样本结果出现的模型参数值。极大似然估计提供了一种给定观察数据来评估模型参数的方法,即:"模型已定,参数未知"
    • 极大似然估计中采样需要满足一个重要的假设,就是所有的采样都是独立同分布的。

y为概率p,根据似然函数的对数可得
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> L = − [ y l o g y p r e + ( 1 − y ) l o g ( 1 − y p r e ) ] L=-[ylogy_{pre}+(1-y)log(1-y_{pre})] </math>L=−[ylogypre+(1−y)log(1−ypre)]

极大似然估计推导损失函数,写出似然函数:
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> P ( y ( i ) = 1 ∣ x ( i ) ; θ ) = h θ ( x ( i ) ) P(y^{(i)}=1|x^{(i)};\theta)=h_{\theta}(x^{(i)}) </math>P(y(i)=1∣x(i);θ)=hθ(x(i))
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> P ( y ( i ) = 0 ∣ x ( i ) ; θ ) = 1 − h θ ( x ( i ) ) P(y^{(i)}=0|x^{(i)};\theta)=1-h_{\theta}(x^{(i)}) </math>P(y(i)=0∣x(i);θ)=1−hθ(x(i))
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> L = Π i = 1 m P ( y ( i ) ∣ y p r e ( i ) ) L=\Pi_{i=1}^mP(y^{(i)}|y^{(i)}{pre}) </math>L=Πi=1mP(y(i)∣ypre(i))
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> = Π i = 1 m y p r e ( i ) y ( i ) ( 1 − y p r e ( i ) ) 1 − y ( i ) =\Pi
{i=1}^my_{pre}^{(i)y^{(i)}}(1-y_{pre}^{(i)})^{1-y^{(i)}} </math>=Πi=1mypre(i)y(i)(1−ypre(i))1−y(i)

取对数
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> l o g L = ∑ i = 1 m y ( i ) l o g y p r e ( i ) + ( 1 − y ( i ) ) l o g ( 1 − y p r e ( i ) ) logL=\sum_{i=1}^my^{(i)}logy_{pre}^{(i)}+(1-y^{(i)})log(1-y_{pre}^{(i)}) </math>logL=i=1∑my(i)logypre(i)+(1−y(i))log(1−ypre(i))

根据梯度下降法 求解,需要链式求导法则求解
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> ∂ J ( θ ) ∂ θ j = ∂ ∂ θ ( ∑ i = 1 m [ y ( i ) l o g ( h θ ( x ( i ) ) ) + ( 1 − y ( i ) ) l o g ( 1 − h θ ( x ( i ) ) ) ] ) \frac{\partial{J(\theta)}}{\partial{\theta_j}}=\frac{\partial}{\partial{\theta}}(\sum_{i=1}^m[y^{(i)}log(h_{\theta}(x^{(i)}))+(1-y^{(i)})log(1-h_{\theta}(x^{(i)}))]) </math>∂θj∂J(θ)=∂θ∂(i=1∑m[y(i)log(hθ(x(i)))+(1−y(i))log(1−hθ(x(i)))])
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> = ∑ i = 1 m [ y ( i ) 1 h θ ( x ( i ) ) − ( 1 − y ( i ) ) 1 1 − h θ ( x ( i ) ) ] ∂ ∂ θ h θ ( x ( i ) ) =\sum_{i=1}^m[y^{(i)}\frac{1}{h_{\theta}(x^{(i)})}-(1-y^{(i)})\frac{1}{1-h_{\theta}(x^{(i)})}]\frac{\partial}{\partial{\theta}}h_{\theta}(x^{(i)}) </math>=i=1∑m[y(i)hθ(x(i))1−(1−y(i))1−hθ(x(i))1]∂θ∂hθ(x(i))
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> = ∑ i = 1 m [ y ( i ) 1 h θ ( x ( i ) ) − ( 1 − y ( i ) ) 1 1 − h θ ( x ( i ) ) ] h θ ( x ( i ) ) ( 1 − h θ ( x ( i ) ) ) ∂ ∂ θ θ x ( i ) =\sum_{i=1}^m[y^{(i)}\frac{1}{h_{\theta}(x^{(i)})}-(1-y^{(i)})\frac{1}{1-h_{\theta}(x^{(i)})}]h_{\theta}(x^{(i)})(1-h_{\theta}(x^{(i)}))\frac{\partial}{\partial{\theta}}\theta{x^{(i)}} </math>=i=1∑m[y(i)hθ(x(i))1−(1−y(i))1−hθ(x(i))1]hθ(x(i))(1−hθ(x(i)))∂θ∂θx(i)
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> = ∑ i = 1 m [ y ( i ) ( 1 − h θ ( x ( i ) ) ) − ( 1 − y ( i ) ) h θ ( x ( i ) ) ] ∂ ∂ θ θ x ( i ) =\sum_{i=1}^m[y^{(i)}(1-h_{\theta}(x^{(i)}))-(1-y^{(i)})h_{\theta}(x^{(i)})]\frac{\partial}{\partial{\theta}}\theta{x^{(i)}} </math>=i=1∑m[y(i)(1−hθ(x(i)))−(1−y(i))hθ(x(i))]∂θ∂θx(i)
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> = ∑ i = 1 m [ y ( i ) − h θ ( x ( i ) ) ] x j ( i ) =\sum_{i=1}^m[y^{(i)}-h_{\theta}(x^{(i)})]x_j^{(i)} </math>=i=1∑m[y(i)−hθ(x(i))]xj(i)

逻辑斯蒂回归的优缺点

  • 优点
    • 将推荐问题转化为CTR点击率预估问题,能综合利用用户、物品、上下文等多种不同的特征
    • 模型简单,可解释性强
    • 训练开销小
      • 简单的线性计算
      • 训练时便于并行化,在预测时只需要对特征进行线性加权,所以性能比较好
    • 资源占用小,尤其是内存:在实际工程中只需要存储权重比较大的特征及特征对应的权重
  • 缺点
    • 表达能力不足,无法进行特征交叉,特征筛选等一系列高级操作
    • 准确率并不是很高:模型太过简单,很难去拟合数据的真实分布

代码实战

python 复制代码
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_breast_cancer

照常先导入所需要的包,我们这次使用的数据集是经典的乳腺癌数据集,该数据集包括了乳腺癌患者的不同特征。我们先大致看一下有哪一些特征

python 复制代码
# 加载乳腺癌数据集
data = load_breast_cancer()

print(data.feature_names)

# ['mean radius' 'mean texture' 'mean perimeter' 'mean area'
# 'mean smoothness' 'mean compactness' 'mean concavity'
# 'mean concave points' 'mean symmetry' 'mean fractal dimension'
# 'radius error' 'texture error' 'perimeter error' 'area error'
# 'smoothness error' 'compactness error' 'concavity error'
# 'concave points error' 'symmetry error' 'fractal dimension error'
# 'worst radius' 'worst texture' 'worst perimeter' 'worst area'
# 'worst smoothness' 'worst compactness' 'worst concavity'
# 'worst concave points' 'worst symmetry' 'worst fractal dimension']

print(data.target_names)

# ['malignant' 'benign']

数据集的特征包括以下几列(这个特征数还算少的,我们就先全部列出来,看一下是否符合,之后介绍的算法可能不会介绍全部的特征)

  • mean radius:平均半径
  • mean texture:平均纹理
  • mean perimeter:平均周长
  • mean area:平均面积
  • mean smoothness:平均平滑度
  • mean compactness:平均紧密度
  • mean concavity:平均凹度
  • mean concave points:平均凹点
  • mean symmetry:平均对称性
  • mean fractal dimension:平均分形维数
  • radius error:半径误差
  • texture error:纹理误差
  • perimeter error:周长误差
  • area error:面积误差
  • smoothness error:光滑度误差
  • compactness error:紧密度误差
  • concavity error:凹度误差
  • concave points error:凹点误差
  • symmetry error:对称性误差
  • fractal dimension error:分形维数误差
  • worst radius:最坏半径
  • worst texture:最坏纹理
  • worst perimeter:最坏周长
  • worst area:最坏面积
  • worst smoothness:最坏光滑度
  • worst compactness:最坏紧密度
  • worst concavity:最坏凹度
  • worst concave points:最坏凹点
  • worst symmetry:最坏对称性
  • worst fractal dimension:最坏分形误差

目标类别分别为

  • malignant:恶性
  • benign:良性

可以看到特征均是从半径、纹理、周长、面积、光滑度、紧密度、凹度、凹点、对称性和分形误差这几个角度展开的。目标为恶性和良性。也就是说这个问题是一个二分类问题,使用逻辑回归算法再合适不过了。

python 复制代码
# 特征选择
features = ['mean radius', 'mean texture', 'mean perimeter', 'mean area', 'mean smoothness']
target = 'target'

# 划分特征和目标变量
X = pd.DataFrame(data.data, columns=data.feature_names)[features]
y = data.target

# 数据集划分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 特征缩放
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

接下来调用逻辑回归模型,进行训练

python 复制代码
from sklearn.linear_model import LogisticRegression

# 创建逻辑回归模型
model = LogisticRegression()

# 模型训练
model.fit(X_train, y_train)

# 估计特征的权重
weights = model.coef_
intercept = model.intercept_

然后在测试集上看一下训练效果

python 复制代码
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

# 预测测试数据集
y_pred = model.predict(X_test)

# 计算评估指标
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)

print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1 score:", f1)

最后预测新样本

Python 复制代码
import numpy as np

# 新样本特征
new_sample = np.array([15.12, 15.16, 97.67, 712.2, 0.0898]).reshape(1, -1)

# 特征缩放
new_sample_scaled = scaler.transform(new_sample)

# 预测新样本的分类
prediction = model.predict(new_sample_scaled)

print("Prediction:", prediction)

补充

上面的代码实战用到了几个评价指标,这里对这几个评价指标做一个简单的介绍,之后会专门对评价指标进行总结

评价指标

首先我们先看这样一个矩阵

Positive Negative
Positive TP FP
Negative FN TN

上面这个矩阵也叫做混淆矩阵,行的positive、negative字段表示样本实际值,列的positive、negative字段表示预测的结果,那么我们就可以给出表格中值的几个概念

  • TP:True Positive。预测为正确的正样本
  • FP:False Positive。预测为错误的正样本
  • TN:True Negative。预测为正确的负样本
  • FN:True Negative。预测为正确的负样本

那么我们就可以解释代码中用到的几个指标

  • 准确率Accuracy:分类器正确分类的样本数与总的样本数之比,即预测正确的概率

    <math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> A c c u r a c y = T P + F N T P + F P + T N + F N Accuracy=\frac{TP+FN}{TP+FP+TN+FN} </math>Accuracy=TP+FP+TN+FNTP+FN

  • 精准率Precision:预测为正的样本中,实际为正样本的比例

    <math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> P e c i s i o n = T P T P + F P Pecision=\frac{TP}{TP+FP} </math>Pecision=TP+FPTP

  • 召回率Recall:实际为正的样本被预测为正样本的比例

    <math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> R e c a l l = T P T P + F N Recall=\frac{TP}{TP+FN} </math>Recall=TP+FNTP

  • F1 Score:由于精准率和召回率是互相矛盾的,为了综合考虑这两个指标,再尽可能提高这两个指标的同时,也希望两者之间的差异尽可能小。

    <math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> F 1 = 2 P ∗ R p + R F1=2\frac{P*R}{p+R} </math>F1=2p+RP∗R

相关推荐
跟着大数据和AI去旅行13 分钟前
使用肘部法则确定K-Means中的k值
python·机器学习·kmeans
QuantumYou25 分钟前
【对比学习串烧】 SWav和 BYOL
学习·机器学习
AI王也1 小时前
ChatGPT搭上langchain的知识库RAG应用,效果超预期
人工智能·chatgpt·langchain·aigc
沧穹科技1 小时前
音频北斗定位系统有什么用?
人工智能
学不会lostfound1 小时前
一、机器学习算法与实践_03概率论与贝叶斯算法笔记
算法·机器学习·概率论·高斯贝叶斯
Bruce小鬼2 小时前
最新版本TensorFlow训练模型TinyML部署到ESP32入门实操
人工智能·python·tensorflow
sp_fyf_20242 小时前
计算机人工智能前沿进展-大语言模型方向-2024-09-20
人工智能·搜索引擎·语言模型
kinlon.liu2 小时前
AI与自然语言处理(NLP):中秋诗词生成
人工智能·自然语言处理
正义的彬彬侠3 小时前
举例说明计算一个矩阵的秩的完整步骤
人工智能·机器学习·矩阵·回归
鸽芷咕3 小时前
【Python报错已解决】xlrd.biffh.XLRDError: Excel xlsx file; not supported
开发语言·python·机器学习·bug·excel