当前位置: 代码迷 >> 综合 >> Lasso 回归和弹性网
  详细解决方案

Lasso 回归和弹性网

热度:31   发布时间:2023-12-24 13:21:47.0

Lasso 回归

在这里插入图片描述
在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt
from math import sqrt
from sklearn import linear_model
import random
from numpy import genfromtxt
def main():data = genfromtxt("longley.csv",delimiter=",")print (data)x_ =data[1:,2:]y_ =data[1:,1]model = linear_model.LassoCV()#自动生成100个值,交叉验证选取最好的alphamodel.fit(x_,y_)print (model.alpha_)print (model.coef_)for  i in range(len(y_)):num = model.predict(x_[i,np.newaxis])print ("predict = {}, real = {}".format(num[0],y_[i]))
main()

result:
14.134043936116361
[0.10093575 0.00586331 0.00599214 0. 0. 0. ]
predict = 85.0965983414889, real = 83.0
predict = 87.53534930585705, real = 88.5
predict = 88.2883909807082, real = 88.2
predict = 90.79402805237368, real = 89.5
predict = 95.40732692456514, real = 96.2
predict = 97.42528633630407, real = 98.1
predict = 99.21657540452378, real = 99.0
predict = 99.87055688439, real = 100.0
predict = 102.76225662054381, real = 101.2
predict = 104.79114364555673, real = 104.6
predict = 107.20360511603185, real = 108.4
predict = 108.30964231708353, real = 110.8
predict = 111.60127997453014, real = 112.6
predict = 113.65601548042127, real = 114.2
predict = 115.77558105291722, real = 115.7
predict = 119.16636356270482, real = 116.9

弹性网

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt
from math import sqrt
from sklearn import linear_model
import random
from numpy import genfromtxt
def main():data = genfromtxt("longley.csv",delimiter=",")print (data)x_ =data[1:,2:]y_ =data[1:,1]model = linear_model.ElasticNetCV()#自动生成100个值,交叉验证选取最好的alphamodel.fit(x_,y_)print (model.alpha_)print (model.coef_)for  i in range(len(y_)):num = model.predict(x_[i,np.newaxis])print ("predict = {}, real = {}".format(num[0],y_[i]))
main()

result:

  1. List item

30.31094405430269
[0.1006612 0.00589596 0.00593021 0. 0. 0. ]
predict = 85.14227874981572, real = 83.0
predict = 87.5748570603973, real = 88.5
predict = 88.33171473856376, real = 88.2
predict = 90.8287728301414, real = 89.5
predict = 95.41682792918382, real = 96.2
predict = 97.42622835962862, real = 98.1
predict = 99.21255826913008, real = 99.0
predict = 99.87395979326243, real = 100.0
predict = 102.75589674689246, real = 101.2
predict = 104.77973819633003, real = 104.6
predict = 107.1864609377655, real = 108.4
predict = 108.29870412853728, real = 110.8
predict = 111.57755830286591, real = 112.6
predict = 113.62745171676997, real = 114.2
predict = 115.74523946587595, real = 115.7
predict = 119.12175277483993, real = 116.9