【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()
相关推荐
w_t_y_y1 分钟前
Agent 开发框架(二)CrewAI
人工智能
2501_945837433 分钟前
OpenClaw:让 AI 从 “聊天” 到 “干活” 的本地智能体革命
人工智能
实在智能RPA6 分钟前
Agent 如何处理流程中的异常情况?——2026企业级智能体稳定性架构深度拆解
开发语言·人工智能·ai·架构·php
AIoT科技物语7 分钟前
免费开源!50+算法,Java基于YOLO框架的视频AI识别算法平台,适配低空无人机巡检、摄像头安防场景
java·人工智能·算法·yolo·开源
翔云1234567 分钟前
一文读懂人工智能,机器学习,深度学习,神经网络,Transformer
人工智能·深度学习·机器学习
盛世宏博北京8 分钟前
多协议温湿度传感器技术解析及系统集成方案设计
大数据·人工智能·温湿度传感器
sakana8 分钟前
如何写一个自己的skill
前端·人工智能
FONE_Platform9 分钟前
FONE亮相第十二届CDIE数字化创新博览会
人工智能·ai·cdie
编程百晓生9 分钟前
《SAP FICO系统配置从入门到精通共40篇》021、CO-PC实战笔记:在制品与差异计算,那些年车间里的“账实不符”
服务器·人工智能·笔记·ar·从入门到精通·sap fico·sap fico系统
weixin_4634497815 分钟前
智媒时代,如何借力权威发声?——探秘官媒发布系统的变革力量
人工智能·自动化