【sklearn】回归模型常规建模流程

模型训练pipeline

基于数十种统计类型特征,构建LR回归模型。代码逻辑包含:样本切分、特征预处理、模型训练、模型评估、特征重要性的可视化。

步骤一:导入所需库

复制代码
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.metrics import mean_squared_error, r2_score

步骤二:读取数据

复制代码
data = pd.read_csv('data.csv')

步骤三:数据预处理

复制代码
# 去除缺失值
data.dropna(inplace=True)

# 划分自变量和因变量
X = data.iloc[:, :-1]
y = data.iloc[:, -1]

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

# 构建pipeline
pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('poly', PolynomialFeatures(degree=2, include_bias=False)),
    ('reg', LinearRegression())
])

# 训练模型
pipeline.fit(X_train, y_train)

# 预测结果
y_pred = pipeline.predict(X_test)

步骤四:模型评估

复制代码
# 均方误差
mse = mean_squared_error(y_test, y_pred)

# R2值
r2 = r2_score(y_test, y_pred)

print('MSE: %.3f' % mse)
print('R2 score: %.3f' % r2)

步骤五:特征重要性的可视化

复制代码
# 获取特征重要性
importance = pipeline.named_steps['reg'].coef_

# 将特征重要性与对应特征名对应
feature_names = pipeline.named_steps['poly'].get_feature_names(X.columns)
feature_importance = pd.DataFrame({'Feature': feature_names, 'Importance': importance})
feature_importance = feature_importance.sort_values('Importance', ascending=False)

# 绘制水平条形图
plt.figure(figsize=(10, 8))
plt.barh(feature_importance['Feature'], feature_importance['Importance'])
plt.title('Feature importance')
plt.xlabel('Importance')
plt.ylabel('Feature')
plt.show()
相关推荐
2601_9577875818 小时前
数据驱动的多平台内容矩阵运营效果分析与闭环优化技术
大数据·人工智能·矩阵
小小工匠18 小时前
Spring AI RAG - 06 敏感词过滤与内容安全防护
人工智能·安全·spring
1892280486118 小时前
NV265固态MT29F32T08GSLBHL8-24QMES:B
大数据·服务器·人工智能·科技·缓存
IT_陈寒18 小时前
Vue的v-for为什么不加key也能工作?我差点翻车
前端·人工智能·后端
穗余18 小时前
什么是模型幻觉?为什么会出现? 模型幻觉是阻碍落地的最重要的原因。
人工智能·机器学习
lightinging19 小时前
五款主流AI智能体多维对比
人工智能
love530love19 小时前
ComfyUI MediaPipe 猴子补丁终极完善版:补全上下文管理与姿态检测兼容
人工智能·windows·python·comfyui·protobuf·mediapipe
Bruce_Liuxiaowei19 小时前
AI攻防时间差:当漏洞发现速度碾压修复速度— 聚焦技术核心
网络·人工智能·网络安全·ai·系统安全
悟纤19 小时前
AI生成MV
人工智能·seedance2.0·ai mv·一键mv
Clark1119 小时前
手写LLM推理框架时,内存管理99%的人会踩的坑 | TFFInfer解析(五)——Tensor 张量系统与内存抽象(下)
人工智能