亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2019年09月11日 10:30:57   作者:青陽(yáng)不會(huì)被占用  
Lasso是一個(gè)線性模型,它給出的模型具有稀疏的系數(shù)。接下來通過本文給大家分享python實(shí)現(xiàn)Lasso回歸的相關(guān)知識(shí),感興趣的朋友一起看看吧

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)文章

最新評(píng)論