机器学习预测汽车油耗效率 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()
相关推荐
cyyt3 分钟前
深度学习周报(5.11~5.17)
人工智能·深度学习
搬砖的小码农_Sky8 分钟前
如何在RX 7900 XTX显卡上运行ROCm?
深度学习·机器学习·gpu算力
鹏子训11 分钟前
MemoryOS:开源时序知识图谱AI记忆系统
人工智能·知识图谱·记忆模块·ai记忆·memoryos·时序记忆
泰迪智能科技13 分钟前
高校人工智能与大数据产品体系及解决方案介绍
大数据·人工智能
GEO从入门到精通15 分钟前
学习GEO资料要多久能看到效果?
人工智能·学习
沪漂阿龙21 分钟前
面试题详解:Agent 记忆管理全解析——历史对话获取、摘要记忆、事实记忆、知识图谱记忆一次讲透
大数据·人工智能·知识图谱
X54先生(人文科技)21 分钟前
《元创力》纪实录·卷宗2.1器物的诊断:当一座平台成为文明的“常见病”
人工智能·开源协议·零知识证明
玹外之音25 分钟前
【无标题】
人工智能·ai·ai编程
BU摆烂会噶26 分钟前
【LangGraph】短期记忆与中断行为
人工智能·python·langchain·人机交互