本篇文章將利用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。