回归问题-预测汽车油耗效率MPG

预测汽车油耗效率 MPG

本实验将通过一个简单的线性回归模型来预测汽车的油耗效率 MPG。通过这次实验,我们将更深入地理解线性回归模型。

数据集来源

https://archive.ics.uci.edu/dataset/9/auto+mpg

数据读取

首先,我们读取数据集,该数据集包含九列,每列都有其特定的意义。特别是 mpg 列,代表汽车的油耗效率。

  • mpg:燃油效率
  • cylinders:气缸数
  • displacement:排量
  • horsepower:马力
  • weight:重量
  • acceleration:加速度
  • model_year:型号年份
  • origin:原产地编号
  • car_name:汽车名称
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

path = './auto-mpg.data'
columns = ["mpg", "cylinders", "displacement", "horsepower", "weight", "acceleration", "model year", "origin", "car name"]
# mpg - > 燃油效率
# cylinders -> 气缸
# displacement - > 排量
# horsepower - > 马力
# weight - > 重量
# acceleration - > 加速度
# model_year - > 型号年份
# origin = > 编号
# car_name - > 原产地
cars = pd.read_csv(path, sep='\s+', names=columns)
# 显示数据集信息
cars.info()

数据探索

在可视化数据时,我们发现 origincar_name 是离散型变量,不适合用于线性回归模型。同时,horsepower 列中存在一些问号(‘?’),我们需要排除这些值。

# 排除 'horsepower' 列中的问号
cars = cars[cars.horsepower != '?']

# 用散点图展示各变量与燃油效率的关系
fig, axs = plt.subplots(3, 2, figsize=(13, 20))
axs[0, 0].scatter(cars['cylinders'], cars['mpg'], alpha=0.5)
axs[0, 0].set_title('Cylinders vs MPG')
axs[0, 1].scatter(cars['displacement'], cars['mpg'], alpha=0.5)
axs[0, 1].set_title('Displacement vs MPG')
axs[1, 0].scatter(cars['weight'], cars['mpg'], alpha=0.5)
axs[1, 0].set_title('Weight vs MPG')
axs[1, 1].scatter(cars['acceleration'], cars['mpg'], alpha=0.5)
axs[1, 1].set_title('Acceleration vs MPG')
axs[2, 0].scatter([float(x) for x in cars['horsepower'].tolist()], cars['mpg'], alpha=0.5)
axs[2, 0].set_title('Horsepower vs MPG')
plt.tight_layout()
plt.show()

数据集拆分

我们将数据集的 20% 作为测试集,其余作为训练集。

from sklearn.model_selection import train_test_split

Y = cars['mpg']
X = cars[['weight']]
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)

单变量线性回归

模型搭建

from sklearn.linear_model import LinearRegression

# 训练模型
lr = LinearRegression()
lr.fit(X_train, Y_train)

结果可视化

训练集
plt.scatter(X_train, Y_train, color='red', alpha=0.3)
plt.plot(X_train, lr.predict(X_train), color='green', alpha=0.3)
plt.xlabel('Weight')
plt.ylabel('MPG')
plt.title('Training Data')
plt.show()

测试集
plt.scatter(X_test, Y_test, color='blue', alpha=0.3)
plt.plot(X_train, lr.predict(X_train), color='green', alpha=0.3)
plt.xlabel('Weight')
plt.ylabel('MPG')
plt.title('Test Data')
plt.show()

模型评估

print('Coefficient:', lr.coef_)
print('Intercept:', lr.intercept_)
print('Score:', lr.score(X, Y))

多变量线性回归模型

我们将使用 weight, horsepower, 和 displacement 三个变量来构建多变量线性回归模型。

# 选择三个变量进行建模
mul = ['weight', 'horsepower', 'displacement']
mul_lr = LinearRegression()
mul_lr.fit(cars[mul], cars['mpg'])
cars['mpg_prediction'] = mul_lr.predict(cars[mul])

模型得分

print('Multiple Linear Regression Score:', mul_lr.score(cars[mul], cars['mpg']))

结果可视化

fig, axs = plt.subplots(3, 1, figsize=(8, 8))
axs[0].scatter(cars['weight'], cars['mpg'], c='blue', alpha=0.3)
axs[0].scatter(cars['weight'], cars['mpg_prediction'], c='red', alpha=0.3)
axs[0].set_title('Weight')
axs[1].scatter([float(x) for x in cars['horsepower'].tolist()], cars['mpg'], c='blue', alpha=0.3)
axs[1].scatter([float(x) for x in cars['horsepower'].tolist()], cars['mpg_prediction'], c='red', alpha=0.3)
axs[1].set_title('Horsepower')
axs[2].scatter(cars['displacement'], cars['mpg'], c='blue', alpha=0.3)
axs[2].scatter(cars['displacement'], cars['mpg_prediction'], c='red', alpha=0.3)
axs[2].set_title('Displacement')
plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@程序员小袁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值