做者:Benjamin Obi Tayo Ph.D.算法
翻譯:老齊bash
與本文相關的圖書:《數據準備和特徵工程》微信
LASSO迴歸是對迴歸算法正則化的一個例子。正則化是一種方法,它經過增長額外參數來解決過擬合問題,從而減小模型的參數、限制複雜度。正則化線性迴歸最經常使用的三種方法是嶺迴歸、最小絕對值收斂和選擇算子(LASSO)以及彈性網絡迴歸。markdown
在本文中,我將重點介紹LASSO,而且對嶺迴歸和彈性網絡迴歸作簡單的擴展。網絡
假設咱們想在一個數據集上創建一個正則化迴歸模型,這個數據集包含n個觀察和m個特徵。app
LASSO迴歸是一個L1懲罰模型,咱們只需將L1範數添加到最小二乘的代價函數中:dom
看這裏函數
經過增大超參數α的值,咱們增強了模型的正則化強度,並下降了模型的權重。請注意,沒有把截距項w0正則化,還要注意α=0對應於標準迴歸。oop
經過調整正則化的強度,某些權重能夠變爲零,這使得LASSO方法成爲一種很是強大的降維技巧。測試
咱們將使用郵輪數據集cruise_ship_info.csv來演示LASSO技術
本案例已經發布在實驗平臺,請關注微信公衆號:老齊教室。並回復:
#姓名+手機號+案例#
獲取。注意:#
必需要有。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
複製代碼
df = pd.read_csv("cruise_ship_info.csv") df.head() 複製代碼
從《數據準備和特徵工程》中的有關闡述可知,協方差矩陣圖可用於特徵選擇和降維。從前述數據集中發現,在6個預測特徵( [‘age’, ‘tonnage’, ‘passengers’, ‘length’, ‘cabins’, ‘passenger_density’]
)中,若是咱們假設重要特徵與目標變量的相關係數爲0.6或更大,那麼目標變量「crew」與4個預測變量「tonnage」, 「passengers」, 「length, and 「cabins」的相關性很強。所以,咱們可以將特徵空間的維數從6減小到4。
cols_selected = ['Tonnage', 'passengers', 'length', 'cabins','crew'] df[cols_selected].head() 複製代碼
X = df[cols_selected].iloc[:,0:4].values # features matrix y = df[cols_selected]['crew'].values # target variable 複製代碼
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split( X, y,
test_size=0.4, random_state=0)
複製代碼
from sklearn.preprocessing import StandardScaler
sc_y = StandardScaler()
sc_x = StandardScaler()
y_std = sc_y.fit_transform(y_train[:, np.newaxis]).flatten()
X_train_std = sc_x.fit_transform(X_train)
X_test_std = sc_x.transform(X_test)
y_train_std = sc_y.fit_transform(y_train[:, np.newaxis]).flatten()
複製代碼
from sklearn.linear_model import Lasso from sklearn.metrics import r2_score alpha = np.linspace(0.01,0.4,10) r2_train =[] r2_test =[] norm = [] alpha = np.linspace(0.01,0.4,10) for i in range(10): lasso = Lasso(alpha = alpha[i]) lasso.fit(X_train_std,y_train_std) y_train_std = lasso.predict(X_train_std) y_test_std = lasso.predict(X_test_std) r2_train = np.append(r2_train, r2_score(y_train,sc_y.inverse_transform(y_train_std))) r2_test = np.append(r2_test, r2_score(y_test,sc_y.inverse_transform(y_test_std))) norm = np.append(norm,np.linalg.norm(lasso.coef_)) 複製代碼
plt.figure(figsize=(8,6)) plt.scatter(alpha,r2_train,label='r2_train') plt.plot(alpha,r2_train) plt.scatter(alpha,r2_test,label='r2_test') plt.plot(alpha,r2_test) plt.scatter(alpha,norm,label = 'norm') plt.plot(alpha,norm) plt.ylim(-0.1,1) plt.xlim(0,.43) plt.xlabel('alpha', size = 14) plt.ylabel('R2_score',size = 14) plt.legend() plt.show() 複製代碼
咱們觀察到,隨着正則化參數α的增長,迴歸係數的範數變得愈來愈小。這意味着更多的迴歸係數被強制爲零,這會增長誤差(模型過分簡化)。α保持較低值時,好比α=0.1或更低時,是誤差和方差的最佳平衡點。在決定使用哪一種降維方法以前,應將該方法與主成分分析法(PCA)進行比較。
原文連接:towardsdatascience.com/lasso-regre…
搜索技術問答的公衆號:老齊教室
在公衆號中回覆:老齊,可查看全部文章、書籍、課程。