You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tzc1/代码/任务8.3 使用Lasso回归选取财政收入预测的关键特...

35 lines
1.6 KiB

3 months ago
# -*- coding: utf-8 -*-
###############################################################################
####################### 任务实现 #######################
###############################################################################
# 代码 8-2
# 使用了 Lasso 回归模型来分析数据集的特征,
# 从中筛选出与目标变量 y 相关的重要特征,并将结果保存到一个新的 CSV 文件中。以下是对代码的逐步分析:
import numpy as np
import pandas as pd
from sklearn.linear_model import Lasso
# inputfile = '../data/data.csv' #输入的数据文件
inputfile = './data.csv' #输入的数据文件
data = pd.read_csv(inputfile) #读取数据
# lasso = Lasso(1000) #调用Lasso()函数设置λ的值为1000
lasso = Lasso(alpha=1000, max_iter=5000) # 增加迭代次数
lasso.fit(data.iloc[:,0:13],data['y'])
print('相关系数为:',np.round(lasso.coef_,5)) #输出结果,保留五位小数
## 计算相关系数非零的个数
print('相关系数非零个数为:',np.sum(lasso.coef_ != 0))
mask = lasso.coef_ != 0 #返回一个相关系数是否为零的布尔数组
print('相关系数是否为零:',mask)
# outputfile = '../tmp/new_reg_data.csv' #输出的数据文件
outputfile = './new_reg_data.csv' #输出的数据文件
# new_reg_data = data.iloc[:, mask] #返回相关系数非零的数据
# 返回相关系数非零的数据
new_reg_data = data.iloc[:, :13].loc[:, mask] # 只选择0到12列中非零的列
new_reg_data.to_csv(outputfile) #存储数据
print('输出数据的维度为:',new_reg_data.shape) #查看输出数据的维度