解析python實(shí)現(xiàn)Lasso回歸
Lasso原理

Lasso與彈性擬合比較python實(shí)現(xiàn)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
#def main():
# 產(chǎn)生一些稀疏數(shù)據(jù)
np.random.seed(42)
n_samples, n_features = 50, 200
X = np.random.randn(n_samples, n_features) # randn(...)產(chǎn)生的是正態(tài)分布的數(shù)據(jù)
coef = 3 * np.random.randn(n_features) # 每個特征對應(yīng)一個系數(shù)
inds = np.arange(n_features)
np.random.shuffle(inds)
coef[inds[10:]] = 0 # 稀疏化系數(shù)--隨機(jī)的把系數(shù)向量1x200的其中10個值變?yōu)?
y = np.dot(X, coef) # 線性運(yùn)算 -- y = X.*w
# 添加噪聲:零均值,標(biāo)準(zhǔn)差為 0.01 的高斯噪聲
y += 0.01 * np.random.normal(size=n_samples)
# 把數(shù)據(jù)劃分成訓(xùn)練集和測試集
n_samples = X.shape[0]
X_train, y_train = X[:n_samples // 2], y[:n_samples // 2]
X_test, y_test = X[n_samples // 2:], y[n_samples // 2:]
# 訓(xùn)練 Lasso 模型
from sklearn.linear_model import Lasso
alpha = 0.1
lasso = Lasso(alpha=alpha)
y_pred_lasso = lasso.fit(X_train, y_train).predict(X_test)
r2_score_lasso = r2_score(y_test, y_pred_lasso)
print(lasso)
print("r^2 on test data : %f" % r2_score_lasso)
# 訓(xùn)練 ElasticNet 模型
from sklearn.linear_model import ElasticNet
enet = ElasticNet(alpha=alpha, l1_ratio=0.7)
y_pred_enet = enet.fit(X_train, y_train).predict(X_test)
r2_score_enet = r2_score(y_test, y_pred_enet)
print(enet)
print("r^2 on test data : %f" % r2_score_enet)
plt.plot(enet.coef_, color='lightgreen', linewidth=2,
label='Elastic net coefficients')
plt.plot(lasso.coef_, color='gold', linewidth=2,
label='Lasso coefficients')
plt.plot(coef, '--', color='navy', label='original coefficients')
plt.legend(loc='best')
plt.title("Lasso R^2: %f, Elastic Net R^2: %f"
% (r2_score_lasso, r2_score_enet))
plt.show()
運(yùn)行結(jié)果

總結(jié)
以上所述是小編給大家介紹的python實(shí)現(xiàn)Lasso回歸,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
pymongo給mongodb創(chuàng)建索引的簡單實(shí)現(xiàn)方法
這篇文章主要介紹了pymongo給mongodb創(chuàng)建索引的簡單實(shí)現(xiàn)方法,涉及Python使用pymongo模塊操作mongodb的技巧,需要的朋友可以參考下2015-05-05
Python標(biāo)準(zhǔn)庫內(nèi)置函數(shù)complex介紹
這篇文章主要介紹了Python標(biāo)準(zhǔn)庫內(nèi)置函數(shù)complex介紹,本文先是講解了complex的作用和使用注意,然后給出了使用示例,需要的朋友可以參考下2014-11-11
Python實(shí)現(xiàn)批量獲取當(dāng)前文件夾下的文件名
這篇文章主要為大家詳細(xì)介紹了如何利用Python實(shí)現(xiàn)批量獲取當(dāng)前文件夾下的文件名,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-02-02
python標(biāo)準(zhǔn)庫壓縮包模塊zipfile和tarfile詳解(常用標(biāo)準(zhǔn)庫)
在我們常用的系統(tǒng)windows和Linux系統(tǒng)中有很多支持的壓縮包格式,包括但不限于以下種類:rar、zip、tar,這篇文章主要介紹了python標(biāo)準(zhǔn)庫壓縮包模塊zipfile和tarfile詳解(常用標(biāo)準(zhǔn)庫),需要的朋友可以參考下2022-06-06
如何利用Python統(tǒng)計(jì)正數(shù)和負(fù)數(shù)的個數(shù)
Python檢查數(shù)據(jù)中的正/負(fù)數(shù)是一種常見的數(shù)據(jù)處理操作,可以通過編寫代碼來實(shí)現(xiàn),下面這篇文章主要給大家介紹了關(guān)于如何利用Python統(tǒng)計(jì)正數(shù)和負(fù)數(shù)的個數(shù)的相關(guān)資料,需要的朋友可以參考下2024-05-05

