线性回归原理推导与应用(十):逻辑回归多分类实战
本篇文章将利用sklearn中内置的鸢尾花数据进行逻辑回归建模并对鸢尾花进行分类。对于逻辑回归和线性回归的相关原理,可以查看之前的文章
数据导入
鸢尾花数据是机器学习里的常用数据,首先导入一些基础库并从sklearn中导入数据集
#导入用到的一些python库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as snsimport warnings
warnings.filterwarnings("ignore")#忽略警告
from sklearn.datasets import load_iris
data = load_iris() #获取数据
iris_target = data.target #数据结果值,即鸢尾花的分类结果
iris_features = pd.DataFrame(data=data.data, columns=data.feature_names) #鸢尾花特征的数据iris_features.info()
可以看到该数据集总共有150个样本,包含4个特征变量和1个目标分类变量。4个特征变量为三种鸢尾花的四个特征,分别是花萼长度(cm)、花萼宽度(cm)、花瓣长度(cm)、花瓣宽度(cm),这些形态特征可以被用来识别鸢尾花的种类。目标变量为花的类别,其都属于鸢尾属下的三个亚属,分别是山鸢尾 (Iris-setosa),变色鸢尾(Iris-versicolor)和维吉尼亚鸢尾(Iris-virginica)。具体字段名称与含义总结如下:
变量 | 描述 |
---|---|
sepal length | 花萼长度(cm) |
sepal width | 花萼宽度(cm) |
petal length | 花瓣长度(cm) |
petal width | 花瓣宽度(cm) |
target | 鸢尾的三个亚属类别,‘setosa’(0), ‘versicolor’(1), ‘virginica’(2) |
数据探索性分析
通过绘制所有特征变量与最终分类的分布和散点图,来大致看一下特征与结果之间的关系
## 合并特征与分类结果数据
iris_all = iris_features.copy()
iris_all['target'] = iris_targetsns.pairplot(data=iris_all, hue= 'target',palette="bright")
plt.show()
可以从图中中发现,不论是从对角线上的分布图还是从分类后的散点图,都可以看出对于不同种类的花,其萼片长、花瓣长、花瓣宽的分布差异较大,换句话说,这些属性是可以帮助我们去识别不同种类的花的。
同时也绘制一下箱线图看一下数据的具体分布
for col in iris_features.columns:sns.boxplot(x='target', y=col, saturation=0.5,palette='pastel', data=iris_all)plt.title(col)plt.show()
花萼长度这一个特征的箱线图如下:
建模
首先划分数据为训练集与测试集
#划分数据集与测试集
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(iris_features, iris_target, test_size = 0.2,random_state = 1024)
利用sklearn中的逻辑回归函数建模,其中函数提供了多分类的功能,对应的参数为:multi_class='auto','ovr',''multinomial''
,也就是之前文章中所说的多分类OVR的方法
首先指定为ovr的分类方法,同时输出相关的参数:
# 定义 逻辑回归模型
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(solver='lbfgs', multi_class='ovr')
clf.fit(x_train, y_train)
# 查看其对应的w
print('the weight of Logistic Regression:\n',clf.coef_)# 查看其对应的w0
print('the intercept(w0) of Logistic Regression:\n',clf.intercept_)输出结果如下:
the weight of Logistic Regression:[[-0.45418407 0.77862646 -2.2268873 -0.87662661][-0.41614677 -1.98168225 0.82180991 -1.2628189 ][-0.28832573 -0.49869581 2.70303022 2.23465912]]
the intercept(w0) of Logistic Regression:[ 6.82628324 6.16028196 -13.72510278]
也可以指定为multinomial的分类方法,对应softmax分类,同时输出相关的参数:
clf = LogisticRegression(solver='lbfgs', multi_class='multinomial')
clf.fit(x_train, y_train)
# 查看其对应的w
print('the weight of Logistic Regression:\n',clf.coef_)# 查看其对应的w0
print('the intercept(w0) of Logistic Regression:\n',clf.intercept_)输出结果如下:
the weight of Logistic Regression:[[-0.42950628 0.83667747 -2.39313278 -0.95907637][ 0.47647805 -0.24379394 -0.13247376 -0.93516504][-0.04697178 -0.59288353 2.52560654 1.89424141]]
the intercept(w0) of Logistic Regression:[ 9.70326709 1.8803977 -11.58366479]
可以看到OVR方法有三个线性回归的方程,这个就是之前OVR原理中说到的三个分类器,数据会根据这三个线性分类器的结果判断其最终的结果。
而multinomia的方法也是三个线性回归得分方程,这是将数据放到三个线性回归中计算得出三个结果并使用softmax计算得到分类结果
模型训练好后就可以使用模型进行预测
# 在训练集和测试集上分布利用训练好的模型进行预测
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
输出测试集的预测分类结果和实际的分类结果看一下:
test_predict
# 测试集预测分类
array([1, 0, 2, 2, 0, 0, 1, 2, 1, 0, 0, 0, 1, 2, 1, 0, 1, 0, 2, 0, 2, 0,1, 0, 2, 1, 2, 2, 2, 2])y_test
#实际分类结果
array([1, 0, 2, 2, 0, 0, 1, 2, 1, 0, 0, 0, 1, 2, 1, 0, 1, 0, 2, 0, 2, 0,1, 0, 2, 1, 2, 2, 2, 2])
模型评价
逻辑回归作为分类模型,评价一个模型的优劣也是通过分类模型的评价指标来评判的。相关指标的详细介绍可参阅:https://blog.csdn.net/qq_42692386/article/details/147896278
首先输出混淆矩阵并将其展示为热力图的形式展示
# 查看混淆矩阵
from sklearn import metricsconfusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print('The confusion matrix result:\n',confusion_matrix_result)# 利用热力图对于结果进行可视化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()
得到的混淆矩阵如下:
可以看到预测的结果是百分百正确的。当然由于测试集数据的划分不同,有的时候结果和准确率也会不同。
同时也可以直接输出准确率:
clf.score(x_test,y_test)
得到的结果也为1。