本文是機器學習系列的第三篇,算上前置機器學習系列是第八篇。本文的概念相對簡單,主要側重於代碼實踐。
上一篇文章說到,咱們能夠用線性迴歸作預測,但顯然現實生活中不止有預測的問題還有分類的問題。咱們能夠從預測值的類型上簡單區分:連續變量的預測爲迴歸,離散變量的預測爲分類。編程
咱們把連續的預測值進行人工定義,邊界的一邊定義爲1,另外一邊定義爲0。這樣咱們就把迴歸問題轉換成了分類問題。網絡
如上圖,咱們把連續的變量分佈壓制在0-1的範圍內,並以0.5做爲咱們分類決策的邊界,大於0.5的機率則判別爲1,小於0.5的機率則判別爲0。app
咱們沒法使用無窮大和負無窮大進行算術運算,咱們經過邏輯迴歸函數(Sigmoid函數/S型函數/Logistic函數)能夠講數值計算限定在0-1之間。dom
$$ \sigma(x) = \frac{1}{1+e^{-x}} $$機器學習
以上就是邏輯迴歸的簡單解釋。下面咱們應用真實的數據案例來進行二分類代碼實踐。函數
添加引用:性能
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt
導入數據集(你們不用在乎這個域名):學習
df = pd.read_csv('https://blog.caiyongji.com/assets/hearing_test.csv') df.head()
age | physical_score | test_result |
---|---|---|
33 | 40.7 | 1 |
50 | 37.2 | 1 |
52 | 24.7 | 0 |
56 | 31 | 0 |
35 | 42.9 | 1 |
該數據集,對5000名參與者進行了一項實驗,以研究年齡和身體健康對聽力損失的影響,尤爲是聽高音的能力。此數據顯示了研究結果對參與者進行了身體能力的評估和評分,而後必須進行音頻測試(經過/不經過),以評估他們聽到高頻的能力。測試
sns.scatterplot(x='age',y='physical_score',data=df,hue='test_result')
咱們用seaborn
繪製年齡和健康得分特徵對應測試結果的散點圖。spa
sns.pairplot(df,hue='test_result')
咱們經過pairplot
方法繪製特徵兩兩之間的對應關係。
咱們能夠大體作出判斷,當年齡超過60很難經過測試,經過測試者廣泛健康得分超過30。
from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score,classification_report,plot_confusion_matrix #準備數據 X = df.drop('test_result',axis=1) y = df['test_result'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=50) scaler = StandardScaler() scaled_X_train = scaler.fit_transform(X_train) scaled_X_test = scaler.transform(X_test) #定義模型 log_model = LogisticRegression() #訓練模型 log_model.fit(scaled_X_train,y_train) #預測數據 y_pred = log_model.predict(scaled_X_test) accuracy_score(y_test,y_pred)
咱們通過準備數據,定義模型爲LogisticRegression
邏輯迴歸模型,經過fit
方法擬合訓練數據,最後經過predict
方法進行預測。
最終咱們調用accuracy_score
方法獲得模型的準確率爲92.2%。
咱們是如何獲得準確率是92.2%的呢?咱們調用plot_confusion_matrix
方法繪製混淆矩陣。
plot_confusion_matrix(log_model,scaled_X_test,y_test)
咱們觀察500個測試實例,獲得矩陣以下:
咱們對以上矩陣進行定義以下:
準確率(Accuracy) 公式以下:
$$ Accuracy = \frac{TP+TN}{TP+TN+FP+FN} $$
帶入本例得:
$$ Accuracy = \frac{285+176}{285+176+20+19} = 0.922 $$
精確度(Precision) 公式以下:
$$ Precision = \frac{TP}{TP+FP} $$
帶入本例得:
$$ Precision = \frac{285}{285+19} = 0.9375 $$
召回率(Recall) 公式以下:
$$ Recall = \frac{TP}{TP+FN} $$
帶入本例得:
$$ Recall = \frac{285}{285+20} = 0.934 $$
咱們調用classification_report
方法可驗證結果。
print(classification_report(y_test,y_pred))
Logistic迴歸和Softmax迴歸都是基於線性迴歸的分類模型,二者無本質區別,都是從伯努利分結合最大對數似然估計。
最大似然估計:簡單來講,最大似然估計就是利用已知的樣本結果信息,反推最具備可能(最大機率)致使這些樣本結果出現的模型參數值。
術語「機率」(probability)和「似然」(likelihood)在英語中常常互換使用,可是它們在統計學中的含義卻大不相同。給定具備一些參數θ的統計模型,用「機率」一詞描述將來的結果x的合理性(知道參數值θ),而用「似然」一詞表示描述在知道結果x以後,一組特定的參數值θ的合理性。
Softmax迴歸模型首先計算出每一個類的分數,而後對這些分數應用softmax函數,估計每一個類的機率。咱們預測具備最高估計機率的類,簡單來講就是找得分最高的類。
導入數據集(你們不用在乎這個域名):
df = pd.read_csv('https://blog.caiyongji.com/assets/iris.csv') df.head()
sepal_length | sepal_width | petal_length | petal_width | species |
---|---|---|---|---|
5.1 | 3.5 | 1.4 | 0.2 | setosa |
4.9 | 3 | 1.4 | 0.2 | setosa |
4.7 | 3.2 | 1.3 | 0.2 | setosa |
4.6 | 3.1 | 1.5 | 0.2 | setosa |
5 | 3.6 | 1.4 | 0.2 | setosa |
該數據集,包含150個鳶尾花樣本數據,數據特徵包含花瓣的長度和寬度和萼片的長度和寬度,包含三個屬種的鳶尾花,分別是山鳶尾(setosa)、變色鳶尾(versicolor)和維吉尼亞鳶尾(virginica)。
sns.scatterplot(x='sepal_length',y='sepal_width',data=df,hue='species')
咱們用seaborn
繪製花萼長度和寬度特徵對應鳶尾花種類的散點圖。
sns.scatterplot(x='petal_length',y='petal_width',data=df,hue='species')
咱們用seaborn
繪製花瓣長度和寬度特徵對應鳶尾花種類的散點圖。
sns.pairplot(df,hue='species')
咱們經過pairplot
方法繪製特徵兩兩之間的對應關係。
咱們能夠大體作出判斷,綜合考慮花瓣和花萼尺寸最小的爲山鳶尾花,中等尺寸的爲變色鳶尾花,尺寸最大的爲維吉尼亞鳶尾花。
#準備數據 X = df.drop('species',axis=1) y = df['species'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=50) scaler = StandardScaler() scaled_X_train = scaler.fit_transform(X_train) scaled_X_test = scaler.transform(X_test) #定義模型 softmax_model = LogisticRegression(multi_class="multinomial",solver="lbfgs", C=10, random_state=50) #訓練模型 softmax_model.fit(scaled_X_train,y_train) #預測數據 y_pred = softmax_model.predict(scaled_X_test) accuracy_score(y_test,y_pred)
咱們通過準備數據,定義模型LogisticRegression
的multi_class="multinomial"
多元邏輯迴歸模型,設置求解器爲lbfgs
,經過fit
方法擬合訓練數據,最後經過predict
方法進行預測。
最終咱們調用accuracy_score
方法獲得模型的準確率爲92.1%。
咱們調用classification_report
方法查看準確率、精確度、召回率。
print(classification_report(y_test,y_pred))
咱們僅提取花瓣長度和花瓣寬度的特徵來繪製鳶尾花的分類圖像。
#提取特徵 X = df[['petal_length','petal_width']].to_numpy() y = df["species"].factorize(['setosa', 'versicolor','virginica'])[0] #定義模型 softmax_reg = LogisticRegression(multi_class="multinomial",solver="lbfgs", C=10, random_state=50) #訓練模型 softmax_reg.fit(X, y) #隨機測試數據 x0, x1 = np.meshgrid( np.linspace(0, 8, 500).reshape(-1, 1), np.linspace(0, 3.5, 200).reshape(-1, 1), ) X_new = np.c_[x0.ravel(), x1.ravel()] #預測 y_proba = softmax_reg.predict_proba(X_new) y_predict = softmax_reg.predict(X_new) #繪製圖像 zz1 = y_proba[:, 1].reshape(x0.shape) zz = y_predict.reshape(x0.shape) plt.figure(figsize=(10, 4)) plt.plot(X[y==2, 0], X[y==2, 1], "g^", label="Iris virginica") plt.plot(X[y==1, 0], X[y==1, 1], "bs", label="Iris versicolor") plt.plot(X[y==0, 0], X[y==0, 1], "yo", label="Iris setosa") from matplotlib.colors import ListedColormap custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) plt.contourf(x0, x1, zz, cmap=custom_cmap) contour = plt.contour(x0, x1, zz1, cmap=plt.cm.brg) plt.clabel(contour, inline=1, fontsize=12) plt.xlabel("Petal length", fontsize=14) plt.ylabel("Petal width", fontsize=14) plt.legend(loc="center left", fontsize=14) plt.axis([0, 7, 0, 3.5]) plt.show()
獲得鳶尾花根據花瓣分類的圖像以下:
相比於概念的理解,本文更側重上手實踐,經過動手編程你應該有「手熱」的感受了。截至到本文,你應該對機器學習的概念有了必定的掌握,咱們簡單梳理一下:
若是你還有不清楚的地方請參考: