机器学习预测汽车油耗效率 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()
相关推荐
来让爷抱一个6 小时前
MonkeyCode 多模型切换技巧:什么时候用 Claude/GPT/DeepSeek
人工智能·ai编程
李白你好6 小时前
AI Agent 架构的自动化渗透测试工具
运维·人工智能·自动化
2601_949499946 小时前
8 大工业光模块供应商选型:芯瑞科技 400G OSFP 助力 AI 算力集群升级
人工智能·科技
温柔只给梦中人7 小时前
NLP学习:注意力机制
人工智能·学习·自然语言处理
weixin_429630267 小时前
3.49 HVLF:一种跨场景的整体视觉定位框架
深度学习·机器学习·计算机视觉
广州灵眸科技有限公司7 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) Easy-Eai编译环境准备与更新
服务器·前端·人工智能·python·深度学习
深度学习lover7 小时前
<数据集>yolo樱桃识别<目标检测>
人工智能·深度学习·yolo·目标检测·计算机视觉·数据集·樱桃识别
深圳市机智人激光雷达7 小时前
技术筑牢安全冗余:激光雷达在自动驾驶高阶感知中的底层价值与范式演进
人工智能·安全·机器学习·3d·机器人·自动驾驶·无人机
江澎涌7 小时前
拆解与 AI 的一次对话
人工智能·算法·程序员
lqqjuly7 小时前
神经架构搜索深度解析(Neural Architecture Search, NAS)
人工智能·知识图谱