基于Scikit-learn的多元线性回归模型构建与验证
废话不多说,直接上代码
# import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import joblib # 用于保存和加载模型
# 1. 导入数据(假设你有一个包含特征和目标值的CSV文件)
# 例如,data.csv 中有若干特征列和一个名为 'target' 的目标列
data = pd.read_csv('FuelConsumptionCo21.csv')
# 2. 准备数据
# 分离特征和目标值
X = data.drop('target', axis=1)
y = data['target']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 3. 创建并训练模型
model = LinearRegression()
model.fit(X_train, y_train)
print(model.coef_)
print(model.intercept_)
# 4. 进行预测并评估模型
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print(f'Mean Squared Error: {mse}')
# 5. 保存模型
joblib.dump(model, 'linear_regression_model.pkl')
# 6. 加载模型(可选,验证模型是否正确保存和加载)
loaded_model = joblib.load('linear_regression_model.pkl')
loaded_y_pred = loaded_model.predict(X_test)
loaded_mse = mean_squared_error(y_test, loaded_y_pred)
print(f'Mean Squared Error after loading: {loaded_mse}')
原始数据是汽车 二氧化碳污染指标排放,数据如下
ENGINESIZE | CYLINDERS | FUELCONSUMPTION_CITY | FUELCONSUMPTION_HWY | FUELCONSUMPTION_COMB | FUELCONSUMPTION_COMB_MPG | target |
2 | 4 | 9.9 | 6.7 | 8.5 | 33 | 196 |
2.4 | 4 | 11.2 | 7.7 | 9.6 | 29 | 221 |
1.5 | 4 | 6 | 5.8 | 5.9 | 48 | 136 |
3.5 | 6 | 12.7 | 9.1 | 11.1 | 25 | 255 |
3.5 | 6 | 12.1 | 8.7 | 10.6 | 27 | 244 |
3.5 | 6 | 11.9 | 7.7 | 10 | 28 | 230 |
3.5 | 6 | 11.8 | 8.1 | 10.1 | 28 | 232 |
3.7 | 6 | 12.8 | 9 | 11.1 | 25 | 255 |
3.7 | 6 | 13.4 | 9.5 | 11.6 | 24 | 267 |
2.4 | 4 | 10.6 | 7.5 | 9.2 | 31 | 212 |
2.4 | 4 | 11.2 | 8.1 | 9.8 | 29 | 225 |
3.5 | 6 | 12.1 | 8.3 | 10.4 | 27 | 239 |
5.9 | 12 | 18 | 12.6 | 15.6 | 18 | 359 |
5.9 | 12 | 18 | 12.6 | 15.6 | 18 | 359 |
4.7 | 8 | 17.4 | 11.3 | 14.7 | 19 | 338 |
4.7 | 8 | 18.1 | 12.2 | 15.4 | 18 | 354 |
4.7 | 8 | 17.4 | 11.3 | 14.7 | 19 | 338 |
4.7 | 8 | 18.1 | 12.2 | 15.4 | 18 | 354 |
5.9 | 12 | 18 | 12.6 | 15.6 | 18 | 359 |
2 | 4 | 9.9 | 7.4 | 8.8 | 32 | 202 |
2 | 4 | 11.5 | 8.1 | 10 | 28 | 230 |
2 | 4 | 10.8 | 7.5 | 9.3 | 30 | 214 |