1. 程式人生 > 實用技巧 >機器學習演算法(一): 基於邏輯迴歸的分類預測

機器學習演算法(一): 基於邏輯迴歸的分類預測

程式碼流程

Part1 Demo實踐

  • Step1:庫函式匯入
  • Step2:模型訓練
  • Step3:模型引數檢視
  • Step4:資料和模型視覺化
  • Step5:模型預測

Part2 基於鳶尾花(iris)資料集的邏輯迴歸分類實踐

  • Step1:庫函式匯入
  • Step2:資料讀取/載入
  • Step3:資料資訊簡單檢視
  • Step4:視覺化描述
  • Step5:利用 邏輯迴歸模型 在二分類上 進行訓練和預測
  • Step6:利用 邏輯迴歸模型 在三分類(多分類)上 進行訓練和預測

Demo實踐

Step1:庫函式匯入

##  基礎函式庫
import numpy as np 

## 匯入畫相簿
import matplotlib.pyplot as plt
import seaborn as sns ## 匯入邏輯迴歸模型函式 from sklearn.linear_model import LogisticRegression

Step2:訓練模型

##Demo演示LogisticRegression分類

## 構造資料集
x_fearures = np.array([[-1, -2], [-2, -1], [-3, -2], [1, 3], [2, 1], [3, 2]])
y_label = np.array([0, 0, 0, 1, 1, 1])

## 呼叫邏輯迴歸模型
lr_clf = LogisticRegression()

## 用邏輯迴歸模型擬合構造的資料集 lr_clf = lr_clf.fit(x_fearures, y_label) #其擬合方程為 y=w0+w1*x1+w2*x2

Step3:模型引數檢視

##檢視其對應模型的w  引數
print('the weight of Logistic Regression:',lr_clf.coef_)
##檢視其對應模型的w0  截距
print('the intercept(w0) of Logistic Regression:',lr_clf.intercept_)
##the weight of Logistic Regression:[[0.73462087 0.6947908]]
##the intercept(w0) of Logistic Regression:[-0.03643213]

Step4:資料和模型視覺化

## 視覺化構造的資料樣本點
plt.figure()
plt.scatter(x_fearures[:,0],x_fearures[:,1], c=y_label, s=50, cmap='viridis')
plt.title('Dataset')
plt.show()

# 視覺化決策邊界
plt.figure()
plt.scatter(x_fearures[:,0],x_fearures[:,1], c=y_label, s=50, cmap='viridis')
plt.title('Dataset')

nx, ny = 200, 100
x_min, x_max = plt.xlim()
y_min, y_max = plt.ylim()
x_grid, y_grid = np.meshgrid(np.linspace(x_min, x_max, nx),np.linspace(y_min, y_max, ny))

z_proba = lr_clf.predict_proba(np.c_[x_grid.ravel(), y_grid.ravel()])
z_proba = z_proba[:, 1].reshape(x_grid.shape)
plt.contour(x_grid, y_grid, z_proba, [0.5], linewidths=2., colors='blue')

plt.show()

### 視覺化預測新樣本

plt.figure()
## new point 1
x_fearures_new1 = np.array([[0, -1]])
plt.scatter(x_fearures_new1[:,0],x_fearures_new1[:,1], s=50, cmap='viridis')
plt.annotate(s='New point 1',xy=(0,-1),xytext=(-2,0),color='blue',arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red'))

## new point 2
x_fearures_new2 = np.array([[1, 2]])
plt.scatter(x_fearures_new2[:,0],x_fearures_new2[:,1], s=50, cmap='viridis')
plt.annotate(s='New point 2',xy=(1,2),xytext=(-1.5,2.5),color='red',arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red'))

## 訓練樣本
plt.scatter(x_fearures[:,0],x_fearures[:,1], c=y_label, s=50, cmap='viridis')
plt.title('Dataset')

# 視覺化決策邊界
plt.contour(x_grid, y_grid, z_proba, [0.5], linewidths=2., colors='blue')

plt.show()

Step5:模型預測

##在訓練集和測試集上分佈利用訓練好的模型進行預測
y_label_new1_predict=lr_clf.predict(x_fearures_new1)
y_label_new2_predict=lr_clf.predict(x_fearures_new2)
print('The New point 1 predict class:\n',y_label_new1_predict)
print('The New point 2 predict class:\n',y_label_new2_predict)
##由於邏輯迴歸模型是概率預測模型(前文介紹的p = p(y=1|x,\theta)),所有我們可以利用predict_proba函式預測其概率
y_label_new1_predict_proba=lr_clf.predict_proba(x_fearures_new1)
y_label_new2_predict_proba=lr_clf.predict_proba(x_fearures_new2)
print('The New point 1 predict Probability of each class:\n',y_label_new1_predict_proba)
print('The New point 2 predict Probability of each class:\n',y_label_new2_predict_proba)
##TheNewpoint1predictclass:
##[0]
##TheNewpoint2predictclass:
##[1]
##TheNewpoint1predictProbabilityofeachclass:
##[[0.695677240.30432276]]
##TheNewpoint2predictProbabilityofeachclass:
##[[0.119839360.88016064]]

可以發現訓練好的迴歸模型將X_new1預測為了類別0(判別面左下側),X_new2預測為了類別1(判別面右上側)。其訓練得到的邏輯迴歸模型的概率為0.5的判別面為上圖中藍色的線。

完整程式碼如下(已摺疊):

# -*- coding: utf-8 -*-
"""
Created on Mon May 18 17:53:32 2020

@author: Admin
"""

#Step1:庫函式匯入
##  基礎函式庫
import numpy as np 

## 匯入畫相簿
import matplotlib.pyplot as plt
import seaborn as sns

## 匯入邏輯迴歸模型函式
from sklearn.linear_model import LogisticRegression


#Step2:訓練模型
##Demo演示LogisticRegression分類

## 構造資料集
x_fearures = np.array([[-1, -2], [-2, -1], [-3, -2], [1, 3], [2, 1], [3, 2]])
y_label = np.array([0, 0, 0, 1, 1, 1])

## 呼叫邏輯迴歸模型
lr_clf = LogisticRegression()

## 用邏輯迴歸模型擬合構造的資料集
lr_clf = lr_clf.fit(x_fearures, y_label) #其擬合方程為 y=w0+w1*x1+w2*x2


#Step3:模型引數檢視
##檢視其對應模型的w
print('the weight of Logistic Regression:',lr_clf.coef_)
##檢視其對應模型的w0
print('the intercept(w0) of Logistic Regression:',lr_clf.intercept_)
##the weight of Logistic Regression:[[0.73462087 0.6947908]]
##the intercept(w0) of Logistic Regression:[-0.03643213]


#Step4:資料和模型視覺化
## 視覺化構造的資料樣本點
plt.figure()
plt.scatter(x_fearures[:,0],x_fearures[:,1], c=y_label, s=50, cmap='viridis')
plt.title('Dataset')
plt.show()


# 視覺化決策邊界
plt.figure()
plt.scatter(x_fearures[:,0],x_fearures[:,1], c=y_label, s=50, cmap='viridis')
plt.title('Dataset')

nx, ny = 200, 100
x_min, x_max = plt.xlim()
y_min, y_max = plt.ylim()
x_grid, y_grid = np.meshgrid(np.linspace(x_min, x_max, nx),np.linspace(y_min, y_max, ny))

z_proba = lr_clf.predict_proba(np.c_[x_grid.ravel(), y_grid.ravel()])
z_proba = z_proba[:, 1].reshape(x_grid.shape)
plt.contour(x_grid, y_grid, z_proba, [0.5], linewidths=2., colors='blue')

plt.show()


### 視覺化預測新樣本

plt.figure()
## new point 1
x_fearures_new1 = np.array([[0, -1]])
plt.scatter(x_fearures_new1[:,0],x_fearures_new1[:,1], s=50, cmap='viridis')
plt.annotate(s='New point 1',xy=(0,-1),xytext=(-2,0),color='blue',arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red'))

## new point 2
x_fearures_new2 = np.array([[1, 2]])
plt.scatter(x_fearures_new2[:,0],x_fearures_new2[:,1], s=50, cmap='viridis')
plt.annotate(s='New point 2',xy=(1,2),xytext=(-1.5,2.5),color='red',arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red'))

## 訓練樣本
plt.scatter(x_fearures[:,0],x_fearures[:,1], c=y_label, s=50, cmap='viridis')
plt.title('Dataset')

# 視覺化決策邊界
plt.contour(x_grid, y_grid, z_proba, [0.5], linewidths=2., colors='blue')

plt.show()


#Step5:模型預測
##在訓練集和測試集上分佈利用訓練好的模型進行預測
y_label_new1_predict=lr_clf.predict(x_fearures_new1)
y_label_new2_predict=lr_clf.predict(x_fearures_new2)
print('The New point 1 predict class:\n',y_label_new1_predict)
print('The New point 2 predict class:\n',y_label_new2_predict)
##由於邏輯迴歸模型是概率預測模型(前文介紹的p = p(y=1|x,\theta)),所有我們可以利用predict_proba函式預測其概率
y_label_new1_predict_proba=lr_clf.predict_proba(x_fearures_new1)
y_label_new2_predict_proba=lr_clf.predict_proba(x_fearures_new2)
print('The New point 1 predict Probability of each class:\n',y_label_new1_predict_proba)
print('The New point 2 predict Probability of each class:\n',y_label_new2_predict_proba)
##TheNewpoint1predictclass:
##[0]
##TheNewpoint2predictclass:
##[1]
##TheNewpoint1predictProbabilityofeachclass:
##[[0.695677240.30432276]]
##TheNewpoint2predictProbabilityofeachclass:
##[[0.119839360.88016064]]
View Code

基於鳶尾花(iris)資料集的邏輯迴歸分類實踐

在實踐的最開始,我們首先需要匯入一些基礎的函式庫包括:numpy (Python進行科學計算的基礎軟體包),pandas(pandas是一種快速,強大,靈活且易於使用的開源資料分析和處理工具),matplotlib和seaborn繪圖。

Step1:函式庫匯入

##  基礎函式庫
import numpy as np 
import pandas as pd

## 繪圖函式庫
import matplotlib.pyplot as plt
import seaborn as sns

本次我們選擇鳶花資料(iris)進行方法的嘗試訓練,該資料集一共包含5個變數,其中4個特徵變數,1個目標分類變數。共有150個樣本,目標變數為 花的類別 其都屬於鳶尾屬下的三個亞屬,分別是山鳶尾 (Iris-setosa),變色鳶尾(Iris-versicolor)和維吉尼亞鳶尾(Iris-virginica)。包含的三種鳶尾花的四個特徵,分別是花萼長度(cm)、花萼寬度(cm)、花瓣長度(cm)、花瓣寬度(cm),這些形態特徵在過去被用來識別物種。

變數

描述

sepal length

花萼長度(cm)

sepal width

花萼寬度(cm)

petal length

花瓣長度(cm)

petal width

花瓣寬度(cm)

target

鳶尾的三個亞屬類別,'setosa'(0), 'versicolor'(1), 'virginica'(2)

Step2:資料讀取/載入

##我們利用sklearn中自帶的iris資料作為資料載入,並利用Pandas轉化為DataFrame格式
from sklearn.datasets import load_iris
data = load_iris() #得到資料特徵
iris_target = data.target #得到資料對應的標籤
iris_features = pd.DataFrame(data=data.data, columns=data.feature_names) #利用Pandas轉化為DataFrame格式

Step3:資料資訊簡單檢視

##利用.info()檢視資料的整體資訊
iris_features.info()
'''
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 4 columns):
sepal length (cm)    150 non-null float64
sepal width (cm)     150 non-null float64
petal length (cm)    150 non-null float64
petal width (cm)     150 non-null float64
dtypes: float64(4)
memory usage: 4.8 KB
'''
##進行簡單的資料檢視,我們可以利用.head()頭部.tail()尾部
iris_features.head()

'''
   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
0                5.1               3.5                1.4               0.2
1                4.9               3.0                1.4               0.2
2                4.7               3.2                1.3               0.2
3                4.6               3.1                1.5               0.2
4                5.0               3.6                1.4               0.2

'''

iris_features.tail()

'''
  sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
145                6.7               3.0                5.2               2.3
146                6.3               2.5                5.0               1.9
147                6.5               3.0                5.2               2.0
148                6.2               3.4                5.4               2.3
149                5.9               3.0                5.1               1.8

'''
##其對應的類別標籤為,其中0,1,2分別代表'setosa','versicolor','virginica'三種不同花的類別

iris_target
'''
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

'''
##利用value_counts函式檢視每個類別數量

pd.Series(iris_target).value_counts()

##2    50

##1    50

##0    50

##dtype:int64

##對於特徵進行一些統計描述

iris_features.describe()

'''
      sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
count         150.000000        150.000000         150.000000        150.000000
mean            5.843333          3.057333           3.758000          1.199333
std             0.828066          0.435866           1.765298          0.762238
min             4.300000          2.000000           1.000000          0.100000
25%             5.100000          2.800000           1.600000          0.300000
50%             5.800000          3.000000           4.350000          1.300000
75%             6.400000          3.300000           5.100000          1.800000
max             7.900000          4.400000           6.900000          2.500000

'''

從統計描述中我們可以看到不同數值特徵的變化範圍

Step4:視覺化描述

## 合併標籤和特徵資訊
iris_all = iris_features.copy() ##進行淺拷貝,防止對於原始資料的修改
iris_all['target'] = iris_target

## 特徵與標籤組合的散點視覺化
sns.pairplot(data=iris_all,diag_kind='hist', hue= 'target')
plt.show()

從上圖可以發現,在2D情況下不同的特徵組合對於不同類別的花的散點分佈,以及大概的區分能力。

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 mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection='3d')

iris_all_class0 = iris_all[iris_all['target']==0].values
iris_all_class1 = iris_all[iris_all['target']==1].values
iris_all_class2 = iris_all[iris_all['target']==2].values
# 'setosa'(0), 'versicolor'(1), 'virginica'(2)
ax.scatter(iris_all_class0[:,0], iris_all_class0[:,1], iris_all_class0[:,2],label='setosa')
ax.scatter(iris_all_class1[:,0], iris_all_class1[:,1], iris_all_class1[:,2],label='versicolor')
ax.scatter(iris_all_class2[:,0], iris_all_class2[:,1], iris_all_class2[:,2],label='virginica')
plt.legend()

plt.show()

Step5:利用邏輯迴歸模型在二分類上進行訓練和預測

##為了正確評估模型效能,將資料劃分為訓練集和測試集,並在訓練集上訓練模型,在測試集上驗證模型效能。
from sklearn.model_selection import train_test_split
##選擇其類別為0和1的樣本(不包括類別為2的樣本)
iris_features_part=iris_features.iloc[:100]
iris_target_part=iris_target[:100]
##測試集大小為20%,80%/20%分
x_train,x_test,y_train,y_test=train_test_split(iris_features_part,iris_target_part,test_size=0.2,random_state=2020)   
    

##從sklearn中匯入邏輯迴歸模型
from sklearn.linear_model import LogisticRegression

##定義邏輯迴歸模型
clf=LogisticRegression(random_state=0,solver='lbfgs')

##在訓練集上訓練邏輯迴歸模型
clf.fit(x_train,y_train)


##檢視其對應的w
print('the weight of Logistic Regression:',clf.coef_)

##檢視其對應的w0
print('the intercept(w0) of Logistic Regression:',clf.intercept_)


##在訓練集和測試集上分佈利用訓練好的模型進行預測
train_predict=clf.predict(x_train)
test_predict=clf.predict(x_test)  
    

from sklearn import metrics
##利用accuracy(準確度)【預測正確的樣本數目佔總預測樣本數目的比例】評估模型效果
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))

##檢視混淆矩陣(預測值和真實值的各類情況統計矩陣)
confusion_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('Predictedlabels')
plt.ylabel('Truelabels')
plt.show()

##The accuracy of the Logistic Regressionis:1.0
##The accuracy of the Logistic Regressionis:1.0
##The confusion matrix result:
##[[9  0]
##[0  11]]

我們可以發現其準確度為1,代表所有的樣本都預測正確了。

Step6:利用 邏輯迴歸模型 在三分類(多分類)上 進行訓練和預測

##測試集大小為20%,80%/20%分
x_train,x_test,y_train,y_test=train_test_split(iris_features,iris_target,test_size=0.2,random_state=2020)


##定義邏輯迴歸模型
clf=LogisticRegression(random_state=0,solver='lbfgs')

   
##在訓練集上訓練邏輯迴歸模型
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_)
##由於這個是3分類,所有我們這裡得到了三個邏輯迴歸模型的引數,其三個邏輯迴歸組合起來即可實現三分類

    
##在訓練集和測試集上分佈利用訓練好的模型進行預測
train_predict=clf.predict(x_train)
test_predict=clf.predict(x_test)
##由於邏輯迴歸模型是概率預測模型(前文介紹的p=p(y=1|x,\theta)),所有我們可以利用predict_proba函式預測其概率

train_predict_proba=clf.predict_proba(x_train)
test_predict_proba=clf.predict_proba(x_test)

print('The test predict Probability of each class:\n',test_predict_proba)
##其中第一列代表預測為0類的概率,第二列代表預測為1類的概率,第三列代表預測為2類的概率。

##利用accuracy(準確度)【預測正確的樣本數目佔總預測樣本數目的比例】評估模型效果
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))


##檢視混淆矩陣
confusion_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()

##The confusion matrix result:
##[[10  0   0]
##[0   8   2] 
##[0   2   8]]   

全部程式碼如下(已摺疊):

# -*- coding: utf-8 -*-
"""
Created on Mon May 18 17:53:32 2020

@author: Admin
"""

#Step1:庫函式匯入
##  基礎函式庫
import numpy as np 
import pandas as pd

## 繪圖函式庫
import matplotlib.pyplot as plt
import seaborn as sns


#SStep2:資料讀取/載入
##我們利用sklearn中自帶的iris資料作為資料載入,並利用Pandas轉化為DataFrame格式
from sklearn.datasets import load_iris
data = load_iris() #得到資料特徵
iris_target = data.target #得到資料對應的標籤
iris_features = pd.DataFrame(data=data.data, columns=data.feature_names) #利用Pandas轉化為DataFrame格式


#Step3:資料資訊簡單檢視
##利用.info()檢視資料的整體資訊
iris_features.info()
'''
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 4 columns):
sepal length (cm)    150 non-null float64
sepal width (cm)     150 non-null float64
petal length (cm)    150 non-null float64
petal width (cm)     150 non-null float64
dtypes: float64(4)
memory usage: 4.8 KB
'''
##進行簡單的資料檢視,我們可以利用.head()頭部.tail()尾部
iris_features.head()

'''
   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
0                5.1               3.5                1.4               0.2
1                4.9               3.0                1.4               0.2
2                4.7               3.2                1.3               0.2
3                4.6               3.1                1.5               0.2
4                5.0               3.6                1.4               0.2

'''

iris_features.tail()

'''
  sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
145                6.7               3.0                5.2               2.3
146                6.3               2.5                5.0               1.9
147                6.5               3.0                5.2               2.0
148                6.2               3.4                5.4               2.3
149                5.9               3.0                5.1               1.8

'''
##其對應的類別標籤為,其中0,1,2分別代表'setosa','versicolor','virginica'三種不同花的類別

iris_target
'''
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

'''
##利用value_counts函式檢視每個類別數量

pd.Series(iris_target).value_counts()

##2    50

##1    50

##0    50

##dtype:int64

##對於特徵進行一些統計描述

iris_features.describe()

'''
      sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
count         150.000000        150.000000         150.000000        150.000000
mean            5.843333          3.057333           3.758000          1.199333
std             0.828066          0.435866           1.765298          0.762238
min             4.300000          2.000000           1.000000          0.100000
25%             5.100000          2.800000           1.600000          0.300000
50%             5.800000          3.000000           4.350000          1.300000
75%             6.400000          3.300000           5.100000          1.800000
max             7.900000          4.400000           6.900000          2.500000

'''


#Step4:視覺化描述
## 合併標籤和特徵資訊
iris_all = iris_features.copy() ##進行淺拷貝,防止對於原始資料的修改
iris_all['target'] = iris_target

## 特徵與標籤組合的散點視覺化
sns.pairplot(data=iris_all,diag_kind='hist', hue= 'target')
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 mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection='3d')

iris_all_class0 = iris_all[iris_all['target']==0].values
iris_all_class1 = iris_all[iris_all['target']==1].values
iris_all_class2 = iris_all[iris_all['target']==2].values
# 'setosa'(0), 'versicolor'(1), 'virginica'(2)
ax.scatter(iris_all_class0[:,0], iris_all_class0[:,1], iris_all_class0[:,2],label='setosa')
ax.scatter(iris_all_class1[:,0], iris_all_class1[:,1], iris_all_class1[:,2],label='versicolor')
ax.scatter(iris_all_class2[:,0], iris_all_class2[:,1], iris_all_class2[:,2],label='virginica')
plt.legend()

plt.show()   
    

# Step5:利用 邏輯迴歸模型 在二分類上 進行訓練和預測  
##為了正確評估模型效能,將資料劃分為訓練集和測試集,並在訓練集上訓練模型,在測試集上驗證模型效能。
from sklearn.model_selection import train_test_split
##選擇其類別為0和1的樣本(不包括類別為2的樣本)
iris_features_part=iris_features.iloc[:100]
iris_target_part=iris_target[:100]
##測試集大小為20%,80%/20%分
x_train,x_test,y_train,y_test=train_test_split(iris_features_part,iris_target_part,test_size=0.2,random_state=2020)   
    

##從sklearn中匯入邏輯迴歸模型
from sklearn.linear_model import LogisticRegression

##定義邏輯迴歸模型
clf=LogisticRegression(random_state=0,solver='lbfgs')

##在訓練集上訓練邏輯迴歸模型
clf.fit(x_train,y_train)


##檢視其對應的w
print('the weight of Logistic Regression:',clf.coef_)

##檢視其對應的w0
print('the intercept(w0) of Logistic Regression:',clf.intercept_)


##在訓練集和測試集上分佈利用訓練好的模型進行預測
train_predict=clf.predict(x_train)
test_predict=clf.predict(x_test)  
    

from sklearn import metrics
##利用accuracy(準確度)【預測正確的樣本數目佔總預測樣本數目的比例】評估模型效果
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))

##檢視混淆矩陣(預測值和真實值的各類情況統計矩陣)
confusion_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('Predictedlabels')
plt.ylabel('Truelabels')
plt.show()

##The accuracy of the Logistic Regressionis:1.0
##The accuracy of the Logistic Regressionis:1.0
##The confusion matrix result:
##[[9  0]
##[0  11]]


#Step6:利用 邏輯迴歸模型 在三分類(多分類)上 進行訓練和預測
##測試集大小為20%,80%/20%分
x_train,x_test,y_train,y_test=train_test_split(iris_features,iris_target,test_size=0.2,random_state=2020)


##定義邏輯迴歸模型
clf=LogisticRegression(random_state=0,solver='lbfgs')

   
##在訓練集上訓練邏輯迴歸模型
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_)
##由於這個是3分類,所有我們這裡得到了三個邏輯迴歸模型的引數,其三個邏輯迴歸組合起來即可實現三分類

    
##在訓練集和測試集上分佈利用訓練好的模型進行預測
train_predict=clf.predict(x_train)
test_predict=clf.predict(x_test)
##由於邏輯迴歸模型是概率預測模型(前文介紹的p=p(y=1|x,\theta)),所有我們可以利用predict_proba函式預測其概率

train_predict_proba=clf.predict_proba(x_train)
test_predict_proba=clf.predict_proba(x_test)

print('The test predict Probability of each class:\n',test_predict_proba)
##其中第一列代表預測為0類的概率,第二列代表預測為1類的概率,第三列代表預測為2類的概率。

##利用accuracy(準確度)【預測正確的樣本數目佔總預測樣本數目的比例】評估模型效果
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))


##檢視混淆矩陣
confusion_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()

##The confusion matrix result:
##[[10  0   0]
##[0   8   2] 
##[0   2   8]]   
View Code

邏輯迴歸原理簡介

當z≥0時,y≥0.5,分類為1,當z<0時,y<0.5,分類為0,其對應的y值我們可以視為類別1的概率預測值。Logistic迴歸雖然名字裡帶“迴歸”,但是它實際上是一種分類方法,主要用於兩分類問題(即輸出只有兩種,分別代表兩個類別),所以利用了Logistic函式(或稱為Sigmoid函式),函式形式為:

對應的函式影象可以表示如下:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-5,5,0.01)
y = 1/(1+np.exp(-x))

plt.plot(x,y)
plt.xlabel('z')
plt.ylabel('y')
plt.grid()
plt.show()

通過上圖我們可以發現 Logistic 函式是單調遞增函式,並且在z=0,而回歸的基本方程,將回歸方程寫入其中為:

所以,邏輯迴歸從其原理上來說,邏輯迴歸其實是實現了一個決策邊界:對於函式,當z≥0時,y≥0.5,分類為1,當z<0時,y<0.5,分類為0,其對應的y值我們可以視為類別1的概率預測值。

對於模型的訓練而言:實質上來說就是利用資料求解出對應的模型的特定的ω。從而得到一個針對於當前資料的特徵邏輯迴歸模型。而對於多分類而言,將多個二分類的邏輯迴歸組合,即可實現多分類。

群裡面有優秀的同學的回答:

首先邏輯迴歸的基礎是線性迴歸,通過一個線性方程將輸入的特徵值輸出為預測值y,但是y的取值範圍是正無窮到負無窮,並不是0或1,
因而邏輯迴歸通過一個函式來歸一化y值,使y的取值在區間(0,1)內,這個函式就是logistic函式,也就是我們通常說的sigmoid函式,它只是sigmoid函式的一種; logistic函式的優點: 1.logistic函式可以壓縮資料,不管x取什麼值,對應的函式值總是在(0,1)範圍內; 2.logistic函式和其反函式都是嚴格單調遞增的; 3.logistic函式連續、光滑,易於求導; 4.logistic函式關於點(0, 0.5)對稱。 缺點: 1.在趨向無窮的地方,函式值變化很小,容易缺失梯度。