其中, 是目標(biāo)變量, 是輸入特征矩陣, 是模型的回歸系數(shù), 是正則化強度的調(diào)節(jié)參數(shù)(控制正則化項的影響), 是L1和L2正則化之間的平衡參數(shù)(當(dāng) 時等價于Lasso,當(dāng) 時等價于嶺回歸),彈性網(wǎng)絡(luò)本質(zhì)上是一個回歸模型,通常用于連續(xù)目標(biāo)變量的預(yù)測,因此,它默認(rèn)情況下不適用于分類任務(wù),因為它優(yōu)化的是最小二乘誤差而不是分類損失.
ElasticNetCV和 ElasticNet都是scikit-learn中用于實現(xiàn)彈性網(wǎng)絡(luò)(Elastic Net)回歸的類,但它們有一些顯著的區(qū)別。
ElasticNetCV: 自動化的交叉驗證模型
ElasticNetCV 是一種帶有 交叉驗證 的彈性網(wǎng)絡(luò)回歸模型。它的主要優(yōu)點是能夠在訓(xùn)練過程中自動選擇最佳的正則化參數(shù)(alpha)和 l1_ratio(L1 和 L2 正則化的比例),因此適用于模型調(diào)參不多、希望自動找到最佳超參數(shù)的場景。
ElasticNet: 固定參數(shù)的彈性網(wǎng)絡(luò)模型
ElasticNet是一個固定超參數(shù)的彈性網(wǎng)絡(luò)模型,要求用戶自己設(shè)置 alpha 和l1_ratio參數(shù),因此,它適合那些已經(jīng)知道最佳參數(shù)值或不需要自動調(diào)參的情況。
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['axes.unicode_minus'] = False
# 讀取數(shù)據(jù)
df = pd.read_excel('2024-11-11公眾號Python機器學(xué)習(xí)AI.xlsx')
# 劃分特征和目標(biāo)變量
X = df.drop(['y'], axis=1)
y = df['y']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
# 標(biāo)準(zhǔn)化特征數(shù)據(jù)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
讀取數(shù)據(jù),分離特征和目標(biāo)變量 y,然后將數(shù)據(jù)集分為訓(xùn)練集和測試集,對特征數(shù)據(jù)進(jìn)行標(biāo)準(zhǔn)化處理,以確保所有特征具有相似的尺度
利用彈性網(wǎng)絡(luò)交叉驗證選擇最佳超參數(shù)并篩選重要特征
from sklearn.linear_model import ElasticNetCV
# 設(shè)定彈性網(wǎng)絡(luò)模型并進(jìn)行交叉驗證以選擇最佳超參數(shù)
elastic_net = ElasticNetCV(l1_ratio=np.linspace(0.1, 1, 10), # 設(shè)定 l1_ratio 范圍為非零值
alphas=np.logspace(-4, 4, 100),
cv=5,
max_iter=10000, # 增加最大迭代次數(shù)
random_state=42)
elastic_net.fit(X_train_scaled, y_train)
# 輸出最佳的 alpha 和 l1_ratio 值
print("Best alpha:", elastic_net.alpha_)
print("Best l1_ratio:", elastic_net.l1_ratio_)
# 獲取特征系數(shù)
feature_coef = elastic_net.coef_
# 篩選出非零特征
selected_features = X.columns[feature_coef != 0]
print("Selected features:", selected_features)
通過彈性網(wǎng)絡(luò)交叉驗證自動選擇最佳超參數(shù),并篩選出在最佳模型中具有顯著貢獻(xiàn)的特征。
l1_ratio是影響模型更接近Lasso回歸或嶺回歸的關(guān)鍵參數(shù):
彈性網(wǎng)絡(luò)特征選擇結(jié)果的可視化
plt.figure(figsize=(10, 6), dpi=1200)
plt.barh(selected_features, feature_coef[feature_coef != 0])
plt.xlabel('Feature Coefficients')
plt.ylabel('Features')
plt.title('Elastic Net Feature Selection Results')
plt.gca().xaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))
plt.savefig('1.pdf', format='pdf', bbox_inches='tight')
plt.show()
通過繪制水平條形圖展示了彈性網(wǎng)絡(luò)特征選擇的結(jié)果,其中橫軸為特征系數(shù)的大小,縱軸為被選擇的特征,圖中顯示了模型認(rèn)為重要的特征及其相對影響力,特征 X_9 對模型貢獻(xiàn)最大
彈性網(wǎng)絡(luò)系數(shù)路徑圖的繪制
系數(shù)路徑圖展示了彈性網(wǎng)絡(luò)在不同正則化強度(alpha)下各特征系數(shù)的變化情況。隨著 alpha 增加,大部分特征的系數(shù)逐漸趨于零,說明強正則化會抑制不重要的特征。紅色虛線表示模型自動選擇的最佳 alpha 值,此時模型在擬合效果與正則化之間達(dá)到了最佳平衡,保留的非零系數(shù)特征對模型預(yù)測最有貢獻(xiàn)。
from sklearn.linear_model import ElasticNet
# Best alpha 和 Best l1_ratio
best_alpha = 0.06734150657750829
best_l1_ratio = 0.5
# 定義 alpha 范圍以繪制路徑圖
alphas = np.logspace(-4, 4, 100)
coefs = []
non_zero_features = []
# 逐個 alpha 值訓(xùn)練模型并存儲系數(shù)
for a in alphas:
model = ElasticNet(alpha=a, l1_ratio=best_l1_ratio, max_iter=10000, random_state=42)
model.fit(X_train_scaled, y_train)
coefs.append(model.coef_)
# 當(dāng) alpha 等于最佳 alpha 時,記錄非零特征
if np.isclose(a, best_alpha, atol=1e-6):
non_zero_features = X.columns[model.coef_ != 0]
# 輸出非零特征
print("Selected features at Best Alpha:", non_zero_features)
使用之前通過ElasticNetCV獲得的最佳參數(shù) (alpha 和 l1_ratio) 構(gòu)建 ElasticNet 模型,可以看到模型的系數(shù)路徑圖與先前的結(jié)果完全一致。
文章轉(zhuǎn)自微信公眾號@Python機器學(xué)習(xí)AI