數(shù)據(jù)科學(xué)和人工智能技術(shù)筆記 十二、邏輯回歸

十二、邏輯回歸

作者:Chris Albon

譯者:飛龍

協(xié)議:CC BY-NC-SA 4.0

C 超參數(shù)快速調(diào)優(yōu)

有時(shí),學(xué)習(xí)算法的特征使我們能夠比蠻力或隨機(jī)模型搜索方法更快地搜索最佳超參數(shù)。

scikit-learn 的LogisticRegressionCV方法包含一個(gè)參數(shù)C。 如果提供了一個(gè)列表,C是可供選擇的候選超參數(shù)值。 如果提供了一個(gè)整數(shù),C的這么多個(gè)候選值,將從 0.0001 和 10000 之間的對(duì)數(shù)標(biāo)度(C的合理值范圍)中提取。

# 加載庫
from sklearn import linear_model, datasets

# 加載數(shù)據(jù)
iris = datasets.load_iris()
X = iris.data
y = iris.target

# 創(chuàng)建邏輯回歸的交叉驗(yàn)證
clf = linear_model.LogisticRegressionCV(Cs=100)

# 訓(xùn)練模型
clf.fit(X, y)

'''
LogisticRegressionCV(Cs=100, class_weight=None, cv=None, dual=False,
           fit_intercept=True, intercept_scaling=1.0, max_iter=100,
           multi_class='ovr', n_jobs=1, penalty='l2', random_state=None,
           refit=True, scoring=None, solver='lbfgs', tol=0.0001, verbose=0) 
'''

在邏輯回歸中處理不平衡類別

像 scikit-learn 中的許多其他學(xué)習(xí)算法一樣,LogisticRegression帶有處理不平衡類的內(nèi)置方法。 如果我們有高度不平衡的類,并且在預(yù)處理期間沒有解決它,我們可以選擇使用class_weight參數(shù)來對(duì)類加權(quán),確保我們擁有每個(gè)類的平衡組合。 具體來說,balanced參數(shù)會(huì)自動(dòng)對(duì)類加權(quán),與其頻率成反比:

w_j = \frac{n}{kn_{j}}

其中 w_j 是類 j 的權(quán)重,n 是觀察數(shù),n_j 是類 j 中的觀察數(shù),k 是類的總數(shù)。

# 加載庫
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
import numpy as np

# 加載數(shù)據(jù)
iris = datasets.load_iris()
X = iris.data
y = iris.target

# 通過移除前 40 個(gè)觀測(cè),使類高度不均衡
X = X[40:,:]
y = y[40:]

# 創(chuàng)建目標(biāo)向量,如果表示類別是否為 0
y = np.where((y == 0), 0, 1)

# 標(biāo)準(zhǔn)化特征
scaler = StandardScaler()
X_std = scaler.fit_transform(X)

# 創(chuàng)建決策樹分類器對(duì)象
clf = LogisticRegression(random_state=0, class_weight='balanced')

# 訓(xùn)練模型
model = clf.fit(X_std, y)

邏輯回歸

盡管其名稱中存在“回歸”,但邏輯回歸實(shí)際上是廣泛使用的二分類器(即,目標(biāo)向量只有兩個(gè)值)。 在邏輯回歸中,線性模型(例如 \beta_{0} + \beta_ {1} x)包含在 logit(也稱為 sigmoid)函數(shù)中,{\frac{1}{1 + e^{-z}},滿足:

P(y_i=1 \mid X)={\frac{1}{1+e^{-(\beta_{0}+\beta_{1}x)}}}

其中 P(y_i=1 \mid X) 是第 i 個(gè)觀測(cè)的目標(biāo)值 y_i 為 1 的概率,X 是訓(xùn)練數(shù)據(jù),\beta_0\beta_1 是要學(xué)習(xí)的參數(shù),e 是自然常數(shù)。

# 加載庫
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.preprocessing import StandardScaler

# 加載只有兩個(gè)類別的數(shù)據(jù)
iris = datasets.load_iris()
X = iris.data[:100,:]
y = iris.target[:100]

# 標(biāo)準(zhǔn)化特征
scaler = StandardScaler()
X_std = scaler.fit_transform(X)

# 創(chuàng)建邏輯回歸對(duì)象
clf = LogisticRegression(random_state=0)

# 訓(xùn)練模型
model = clf.fit(X_std, y)

# 創(chuàng)建新的觀測(cè)
new_observation = [[.5, .5, .5, .5]]

# 預(yù)測(cè)類別
model.predict(new_observation)

# array([1]) 

# 查看預(yù)測(cè)的概率
model.predict_proba(new_observation)

# array([[ 0.18823041,  0.81176959]]) 

大量數(shù)據(jù)上的邏輯回歸

scikit-learn 的LogisticRegression提供了許多用于訓(xùn)練邏輯回歸的技術(shù),稱為求解器。 大多數(shù)情況下,scikit-learn 會(huì)自動(dòng)為我們選擇最佳求解器,或警告我們,你不能用求解器做一些事情。 但是,我們應(yīng)該注意一個(gè)特殊情況。

雖然精確的解釋超出了本書的范圍,但隨機(jī)平均梯度下降使得我們?cè)跀?shù)據(jù)非常大時(shí),比其他求解器更快訓(xùn)練模型。 但是,對(duì)特征尺度也非常敏感,標(biāo)準(zhǔn)化我們的特征尤為重要。 我們可以通過設(shè)置solver ='sag'來設(shè)置我們的學(xué)習(xí)算法來使用這個(gè)求解器。

# 加載庫
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.preprocessing import StandardScaler

# 加載數(shù)據(jù)
iris = datasets.load_iris()
X = iris.data
y = iris.target

# 標(biāo)準(zhǔn)化特征
scaler = StandardScaler()
X_std = scaler.fit_transform(X)

# 創(chuàng)建使用 SAG 求解器的邏輯回歸
clf = LogisticRegression(random_state=0, solver='sag')

# 訓(xùn)練模型
model = clf.fit(X_std, y)

帶有 L1 正則化的邏輯回歸

L1 正則化(也稱為最小絕對(duì)誤差)是數(shù)據(jù)科學(xué)中的強(qiáng)大工具。 有許多教程解釋 L1 正則化,我不會(huì)在這里嘗試這樣做。 相反,本教程將展示正則化參數(shù)C對(duì)系數(shù)和模型精度的影響。

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

本教程中使用的數(shù)據(jù)集是著名的鳶尾花數(shù)據(jù)集。鳶尾花數(shù)據(jù)包含來自三種鳶尾花y,和四個(gè)特征變量X的 50 個(gè)樣本。

數(shù)據(jù)集包含三個(gè)類別(三種鳶尾),但是為了簡單起見,如果目標(biāo)數(shù)據(jù)是二元的,則更容易。因此,我們將從數(shù)據(jù)中刪除最后一種鳶尾。

# 加載鳶尾花數(shù)據(jù)集
iris = datasets.load_iris()

# 從特征中創(chuàng)建 X
X = iris.data

# 從目標(biāo)中創(chuàng)建 y
y = iris.target

# 重新生成變量,保留所有標(biāo)簽不是 2 的數(shù)據(jù)
X = X[y != 2]
y = y[y != 2]

# 查看特征
X[0:5]

'''
array([[ 5.1,  3.5,  1.4,  0.2],
       [ 4.9,  3\. ,  1.4,  0.2],
       [ 4.7,  3.2,  1.3,  0.2],
       [ 4.6,  3.1,  1.5,  0.2],
       [ 5\. ,  3.6,  1.4,  0.2]]) 
'''

# 查看目標(biāo)數(shù)據(jù)
y

'''
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]) 
'''

# 將數(shù)據(jù)拆分為測(cè)試和訓(xùn)練集
# 將 30% 的樣本放入測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

因?yàn)檎齽t化懲罰由系數(shù)的絕對(duì)值之和組成,所以我們需要縮放數(shù)據(jù),使系數(shù)都基于相同的比例。

# 創(chuàng)建縮放器對(duì)象
sc = StandardScaler()

# 將縮放器擬合訓(xùn)練數(shù)據(jù),并轉(zhuǎn)換
X_train_std = sc.fit_transform(X_train)

# 將縮放器應(yīng)用于測(cè)試數(shù)據(jù)
X_test_std = sc.transform(X_test)

L1 的用處在于它可以將特征系數(shù)逼近 0,從而創(chuàng)建一種特征選擇方法。 在下面的代碼中,我們運(yùn)行帶有 L1 懲罰的邏輯回歸四次,每次都減少了C的值。 我們應(yīng)該期望隨著C的減少,更多的系數(shù)變?yōu)?0。

C = [10, 1, .1, .001]

for c in C:
    clf = LogisticRegression(penalty='l1', C=c)
    clf.fit(X_train, y_train)
    print('C:', c)
    print('Coefficient of each feature:', clf.coef_)
    print('Training accuracy:', clf.score(X_train, y_train))
    print('Test accuracy:', clf.score(X_test, y_test))
    print('')

'''
C: 10
Coefficient of each feature: [[-0.0855264  -3.75409972  4.40427765  0\.        ]]
Training accuracy: 1.0
Test accuracy: 1.0

C: 1
Coefficient of each feature: [[ 0\.         -2.28800472  2.5766469   0\.        ]]
Training accuracy: 1.0
Test accuracy: 1.0

C: 0.1
Coefficient of each feature: [[ 0\.         -0.82310456  0.97171847  0\.        ]]
Training accuracy: 1.0
Test accuracy: 1.0

C: 0.001
Coefficient of each feature: [[ 0\.  0\.  0\.  0.]]
Training accuracy: 0.5
Test accuracy: 0.5 
'''

注意,當(dāng)C減小時(shí),模型系數(shù)變小(例如,從C = 10時(shí)的4.36276075變?yōu)?code>C = 0.1時(shí)的0.0.97175097),直到C = 0.001,所有系數(shù)都是零。 這是變得更加突出的,正則化懲罰的效果。

OVR 邏輯回歸

邏輯回歸本身只是二分類器,這意味著它們無法處理具有兩個(gè)類別以上的目標(biāo)向量。 但是,邏輯回歸有一些聰明的擴(kuò)展來實(shí)現(xiàn)它。 在 One-VS-Rest(OVR)邏輯回歸中,針對(duì)每個(gè)類別訓(xùn)練單獨(dú)的模型,預(yù)測(cè)觀測(cè)是否是該類(因此使其成為二分類問題)。 它假定每個(gè)分類問題(例如是不是類 0)是獨(dú)立的。

# 加載庫
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.preprocessing import StandardScaler

# 加載數(shù)據(jù)
iris = datasets.load_iris()
X = iris.data
y = iris.target

# 標(biāo)準(zhǔn)化特征
scaler = StandardScaler()
X_std = scaler.fit_transform(X)

# 創(chuàng)建 OVR 邏輯回歸對(duì)象
clf = LogisticRegression(random_state=0, multi_class='ovr')

# 訓(xùn)練模型
model = clf.fit(X_std, y)

# 創(chuàng)建新的觀測(cè)
new_observation = [[.5, .5, .5, .5]]

# 預(yù)測(cè)類別
model.predict(new_observation)

# array([2]) 

# 查看預(yù)測(cè)概率
model.predict_proba(new_observation)

# array([[ 0.0829087 ,  0.29697265,  0.62011865]]) 
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容