Lasso原理
Lasso與彈性擬合比較python實現
import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import r2_score #def main(): # 產生一些稀疏數據 np.random.seed(42) n_samples, n_features = 50, 200 X = np.random.randn(n_samples, n_features) # randn(...)產生的是正態分布的數據 coef = 3 * np.random.randn(n_features) # 每個特征對應一個系數 inds = np.arange(n_features) np.random.shuffle(inds) coef[inds[10:]] = 0 # 稀疏化系數--隨機的把系數向量1x200的其中10個值變為0 y = np.dot(X, coef) # 線性運算 -- y = X.*w # 添加噪聲:零均值,標準差為 0.01 的高斯噪聲 y += 0.01 * np.random.normal(size=n_samples) # 把數據劃分成訓練集和測試集 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()
運行結果
總結
以上所述是小編給大家介紹的python實現Lasso回歸,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
