机器学习预测汽车油耗效率 MPG

流程

  1. 数据获取
  2. 导入需要的包
  3. 引入文件,查看内容
  4. 划分训练集和测试集
  5. 调用模型
  6. 查看准确率

数据获取

python 复制代码
链接:https://pan.baidu.com/s/1KeIJykbcVpsfEk0xjhiICA?pwd=30oe 
提取码:30oe 
--来自百度网盘超级会员V1的分享

导入需要的包

python 复制代码
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

引入文件,查看内容

python 复制代码
path = 'auto-mpg.data'
columns = ["mpg", "cylinders", "displacement", "horsepower", "weight", "acceleration", "model year", "origin", "car name"]
cars = pd.read_csv(path, delim_whitespace=True, names=columns)
cars.head()

划分训练集和测试集

这里先用重量做特征

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

引入模型

线性回归

python 复制代码
lr = LinearRegression()
lr = lr.fit(X_train,Y_train)

查看准确率

文字

python 复制代码
print('score = {}'.format(lr.score(X,Y)))
#score = 0.691680406988993

可视化查看

python 复制代码
plt.scatter(X_test, Y_test, color = 'red', alpha=0.3)
plt.scatter(X_test, lr.predict(X_test),color = 'green',alpha=0.3)
plt.xlabel('weight')
plt.ylabel('mpg')
plt.title('test data')
plt.show()

准确率只有0.69因为只用到了weight

此时使用多变量线性回归

选三个变量建模

python 复制代码
cars = cars[cars.horsepower != '?']
mul = ['weight','horsepower','displacement'] # 选择三个变量进行建立模型
mul_lr = LinearRegression()
mul_lr.fit(cars[mul],cars['mpg']) # 训练模型
cars['mpg_prediction'] = mul_lr.predict(cars[mul])
cars.head()

预测准确率

python 复制代码
mul_score = mul_lr.score(cars[mul],cars['mpg'])
mul_score
#0.7069554693444708

从这里可以看出准确率上升了一个点

python 复制代码
fig = plt.figure(figsize = (8,10))
ax1 = fig.add_subplot(3,1,1)
ax2 = fig.add_subplot(3,1,2)
ax3 = fig.add_subplot(3,1,3)
ax1.scatter(cars['weight'], cars['mpg'], c='blue', alpha=0.3)
ax1.scatter(cars['weight'], cars['mpg_prediction'], c='red', alpha=0.3)
ax1.set_title('weight')
ax2.scatter([ float(x) for x in cars['horsepower'].tolist()], cars['mpg'], c='blue', alpha=0.3)
ax2.scatter([ float(x) for x in cars['horsepower'].tolist()], cars['mpg_prediction'], c='red', alpha=0.3)
ax2.set_title('horsepower')
ax3.scatter(cars['displacement'], cars['mpg'], c='blue', alpha=0.3)
ax3.scatter(cars['displacement'], cars['mpg_prediction'], c='red', alpha=0.3)
ax3.set_title('displacement')
plt.show()
相关推荐
aqi001 分钟前
鸿蒙版本的小小机器人APP开放源码啦
人工智能·华为·harmonyos·鸿蒙·harmony
眼泪划过的星空2 分钟前
快速了解LangGraph:构建智能Agent工作流的核心框架
人工智能·python·langchain
眞bilibili11 分钟前
如何快速无缝的从 vscode 转向AI编辑器 cursor、kiro、trae 等
人工智能·vscode·编辑器
码农小白AI12 分钟前
适配外贸出口质检标准!IACheck AI报告审核打通制造业来料成品质控壁垒
人工智能
二川bro33 分钟前
2026主流大模型横向对比:Kimi/Claude/GPT选型+网关管理实战
人工智能
2501_9423895535 分钟前
Nifty IT指数的K线犹如断线的风筝
人工智能·postgresql·时序数据库·storm·tdengine
u01030552738 分钟前
泛型类与类型安全详解
人工智能·1024程序员节
tiger从容淡定是人生41 分钟前
生态入口之战:GPT、Gemini、Copilot与DeepSeek的战略分野
图像处理·人工智能·chatgpt·copilot·软件构建
半兽先生1 小时前
大模型技术开发与应用——4.大模型提示词工程实战
人工智能·算法
太子釢1 小时前
手写一个 RAG:从零搭建可溯源的检索增强问答系统
人工智能