解析python實現(xiàn)Lasso回歸
更新時間:2019年09月11日 10:30:57 作者:青陽不會被占用
Lasso是一個線性模型,它給出的模型具有稀疏的系數(shù)。接下來通過本文給大家分享python實現(xiàn)Lasso回歸的相關(guān)知識,感興趣的朋友一起看看吧
Lasso原理
Lasso與彈性擬合比較python實現(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ù)--隨機的把系數(shù)向量1x200的其中10個值變?yōu)? y = np.dot(X, coef) # 線性運算 -- y = X.*w # 添加噪聲:零均值,標準差為 0.01 的高斯噪聲 y += 0.01 * np.random.normal(size=n_samples) # 把數(shù)據(jù)劃分成訓練集和測試集 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:] # 訓練 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) # 訓練 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()
運行結(jié)果
總結(jié)
以上所述是小編給大家介紹的python實現(xiàn)Lasso回歸,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
pymongo給mongodb創(chuàng)建索引的簡單實現(xiàn)方法
這篇文章主要介紹了pymongo給mongodb創(chuàng)建索引的簡單實現(xiàn)方法,涉及Python使用pymongo模塊操作mongodb的技巧,需要的朋友可以參考下2015-05-05Python標準庫內(nèi)置函數(shù)complex介紹
這篇文章主要介紹了Python標準庫內(nèi)置函數(shù)complex介紹,本文先是講解了complex的作用和使用注意,然后給出了使用示例,需要的朋友可以參考下2014-11-11python標準庫壓縮包模塊zipfile和tarfile詳解(常用標準庫)
在我們常用的系統(tǒng)windows和Linux系統(tǒng)中有很多支持的壓縮包格式,包括但不限于以下種類:rar、zip、tar,這篇文章主要介紹了python標準庫壓縮包模塊zipfile和tarfile詳解(常用標準庫),需要的朋友可以參考下2022-06-06如何利用Python統(tǒng)計正數(shù)和負數(shù)的個數(shù)
Python檢查數(shù)據(jù)中的正/負數(shù)是一種常見的數(shù)據(jù)處理操作,可以通過編寫代碼來實現(xiàn),下面這篇文章主要給大家介紹了關(guān)于如何利用Python統(tǒng)計正數(shù)和負數(shù)的個數(shù)的相關(guān)資料,需要的朋友可以參考下2024-05-05