解析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) # 每個(gè)特征對(duì)應(yīng)一個(gè)系數(shù)
inds = np.arange(n_features)
np.random.shuffle(inds)
coef[inds[10:]] = 0 # 稀疏化系數(shù)--隨機(jī)的把系數(shù)向量1x200的其中10個(gè)值變?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)練集和測(cè)試集
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回歸,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
基于Tensorflow搭建一個(gè)神經(jīng)網(wǎng)絡(luò)的實(shí)現(xiàn)
神經(jīng)網(wǎng)絡(luò)可能會(huì)讓人感到恐懼,特別是對(duì)于新手機(jī)器學(xué)習(xí)的人來說。這篇文章主要介紹了基于Tensorflow搭建一個(gè)神經(jīng)網(wǎng)絡(luò)的實(shí)現(xiàn),從入門開始,感興趣的可以了解一下2021-05-05
Python實(shí)現(xiàn)信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06
手把手教你pycharm專業(yè)版安裝破解教程(linux版)
這篇文章主要介紹了 手把手教你pycharm專業(yè)版安裝破解教程(linux版),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
Python實(shí)現(xiàn)批量生成,重命名和刪除word文件
這篇文章主要為大家詳細(xì)介紹了Python如何利用第三方庫實(shí)現(xiàn)批量生成、重命名和刪除word文件的功能,文中的示例代碼講解詳細(xì),需要的可以參考一下2023-03-03

