算法原理
正則化
這里補充下正則化的知識。當一個模型太復雜時,就容易過擬合,解決的辦法是減少輸入特征的個數,或者獲取更多的訓練樣本。正則化也是用來解決模型過擬合的一種方法。常用的有L1和L2范數做為正則化項。
- L1范數
L1范數作為正則化項,會讓模型參數θ稀疏話,就是讓模型參數向量里為0的元素盡量多。L1就是在成本函數后加入:
- L2范數
而L2范數作為正則化項,則是讓模型參數盡量小,但不會為0,即盡量讓每個特征對預測值都有一些小的貢獻。L2就是在成本函數后加入:
實戰——乳腺癌檢測
數據導入
本次實戰依舊是使用sklearn中的數據集,如圖所示。
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
print(cancer.DESCR)
切分數據集
X = cancer.data
y = cancer.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=33)
模型訓練與評估
邏輯回歸算法使用sklearn.linear_model 模塊中的LogisticRegression方法。常用的參數如下:
- penalty:設置正則化項,其取值為'l1'或'l2',默認為'l2'。
- C:正則化強度,C越大,權重越小。
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X_train, y_train)
model.score(X_test, y_test)
# result
# 0.94736842105263153
我們換為L1范數:
model2 = LogisticRegression(penalty='l1')
model2.fit(X_train, y_train)
model2.score(X_test, y_test)
# result
# 0.95614035087719296
這里查看模型的參數,發現確實有很多特征的參數為0。