【机器学习案列】基于随机森林和xgboost的二手车价格回归预测

news/2024/10/4 21:10:25/

一、项目分析

1.1 项目任务

kaggle二手车价格回归预测项目,目的根据各种属性预测二手车的价格

1.2 评估准则
评估的标准是均方根误差:在这里插入图片描述
1.3 数据介绍
数据连接https://www.kaggle.com/competitions/playground-series-s4e9/data?select=train.csv
在这里插入图片描述
其中:

  • id:唯一标识符(或编号)
  • brand:品牌
  • model:型号
  • model_year:车型年份
  • mileage(注意这里可能是拼写错误,应该是mileage而不是milage):里程数
  • fuel_type:燃油类型
  • engine:发动机
  • transmission:变速器
  • ext_col:车身颜色(外部)
  • int_col:内饰颜色(内部)
  • accident:事故记录
  • clean_title:清洁标题(通常指车辆是否有清晰的产权记录,无抵押、无重大事故等)
  • price:价格

二、读取数据

2.1 导入相应的库

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split, GridSearchCV
import xgboost as xgb

2.2 读取数据

file_path = '/kaggle/input/playground-series-s4e9/train.csv'
df = pd.read_csv(file_path)df.head()
df.shape()

在这里插入图片描述
在这里插入图片描述

三、Exploratory Data Analysis(EDA)

3.1 车型年份与价格的关系

plt.figure(figsize=(10, 6))
sns.scatterplot(x='model_year', y='price', data=df)
plt.title('Model Year vs Price')
plt.xlabel('Model Year')
plt.ylabel('Price')
plt.show()

在这里插入图片描述
3.2 滞留量与价格的关系

plt.figure(figsize=(10, 6))
sns.scatterplot(x='milage', y='price', data=df)
plt.title('Milage vs Price')
plt.xlabel('Milage')
plt.ylabel('Price')
plt.show()

在这里插入图片描述
3.3 热图检查数值特征之间的关系

num_df = df.select_dtypes(include=['float64', 'int64'])
plt.figure(figsize=(12, 8))
corr_matrix = num_df.corr()
sns.heatmap(corr_matrix, annot=True, fmt=".2f", cmap="coolwarm", linewidths=0.5, annot_kws={"size": 10})
plt.title('Correlation Matrix', fontsize=16)
plt.xticks(rotation=45, ha='right')
plt.yticks(rotation=0)
plt.tight_layout()
plt.show()

在这里插入图片描述
3.4 按品牌统计图表

plt.figure(figsize=(12, 6))
sns.countplot(data=df, x='brand', order=df['brand'].value_counts().index)
plt.title('Count of Cars by Brand', fontsize=16)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

在这里插入图片描述

3.5 箱线图

plt.figure(figsize=(12, 6))
sns.boxplot(data=df, x='fuel_type', y='milage')
plt.title('Mileage by Fuel Type', fontsize=16)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

在这里插入图片描述

1.6 各品牌平均里程数

plt.figure(figsize=(12, 6))
sns.barplot(data=df, x='brand', y='milage', estimator=np.mean, ci=None)
plt.title('Average Mileage by Brand', fontsize=16)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

在这里插入图片描述

四、 数据预测处理

4.1 检查每个特征是否具有不同的值

for i in df.columns:if df[i].nunique()<2:print(f'{i} has only one unique value. ')

clean_title has only one unique value.

“Clean ”功能只有一个唯一值,所以我们可以将其删除。

df.drop(['id','clean_title'],axis=1,inplace=True)
df.shape

(188533, 11)

4.2 缺失值处理

df.isnull().sum().sum()

7535

df.dropna(inplace=True)
df.isnull().sum().sum()

0

没有缺失的值,所以我们可以继续了。

4.3
使用一热编码将分类变量转换为数值格式

df = pd.get_dummies(df, columns=['brand', 'model', 'fuel_type', 'transmission', 'ext_col', 'int_col', 'accident','engine' ], drop_first=True)

五、数据预测

5.1 数据样本和标签分离

X = df.drop('price', axis=1)
y = df['price']

5.2 切分数据集

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

5.3 模型训练和评估
5.3.1 Xgboost回归模型

xgb_model = xgb.XGBRegressor(n_estimators=100,      max_depth=5,           learning_rate=0.1,     subsample=0.8,        random_state=42        
)xgb_model.fit(X_train, y_train)y_pred_xgb = xgb_model.predict(X_test)rmse_xgb = np.sqrt(mean_squared_error(y_test, y_pred_xgb))
print(f'XGBoost Root Mean Squared Error: {rmse_xgb}')

XGBoost Root Mean Squared Error: 67003.09126576487

5.3.2 Random Forest回归模型

rf_model = RandomForestRegressor(n_estimators=100,     max_depth=10,         min_samples_split=2,min_samples_leaf=1,    random_state=42      
)rf_model.fit(X_train, y_train)y_pred_rf = rf_model.predict(X_test)rmse_rf = np.sqrt(mean_squared_error(y_test, y_pred_rf))
print(f'Random Forest Root Mean Squared Error: {rmse_rf}')

Random Forest Root Mean Squared Error: 68418.85393408517

参考文献:
1 https://www.kaggle.com/code/muhammaadmuzammil008/eda-random-forest-xgboost


http://www.ppmy.cn/news/1534095.html

相关文章

【Web】Electron:第一个桌面程序

Electron 是一个开源框架&#xff0c;使开发者能够使用 HTML、CSS 和 JavaScript 构建跨平台的桌面应用程序。通过 Electron&#xff0c;开发者可以将网页技术应用于桌面软件开发&#xff0c;从而利用现有的网页技术栈构建功能强大的桌面应用。 下载 Electron 虽然 Electron …

【架构】NewSQL

文章目录 NewSQLTiDBTiDB 主要组件特点使用场景安装与部署 推荐阅读 NewSQL NewSQL是一种数据库管理系统(DBMS)的类别&#xff0c;它结合了NoSQL数据库的可扩展性和传统SQL数据库的事务一致性。具体来说&#xff0c;NewSQL数据库旨在解决传统关系型数据库在处理大规模并发事务…

Leecode SQL 184. Department Highest Salary 找出tie

Department Highest Salary 注意&#xff01;要找出 tie 的 highest salary&#xff01; Write a solution to find employees who have the highest salary in each of the departments. Return the result table in any order. The result format is in the following ex…

从 Kafka 到 WarpStream: 用 MinIO 简化数据流

虽然 Apache Kafka 长期以来一直是流数据的行业标准&#xff0c;但新的创新替代方案正在重塑生态系统。其中之一是 WarpStream&#xff0c;它最近在 Confluent 的所有权下进入了新的篇章。此次收购进一步增强了 WarpStream 提供高性能、云原生数据流的能力&#xff0c;巩固了其…

02SQLite

文章目录 索引创建索引删除索引索引优点及缺点&#xff1f;避免使用索引 视图创建视图删除视图 事务事务控制命令通过事务方式对数据库进行访问优势&#xff1a; 索引 创建索引 索引&#xff08;Index&#xff09;是一种特殊查找表&#xff0c;数据库搜索引擎用来加速数据检索…

基于微信小程序爱心领养小程序设计与实现(源码+定制+开发)

博主介绍&#xff1a; ✌我是阿龙&#xff0c;一名专注于Java技术领域的程序员&#xff0c;全网拥有10W粉丝。作为CSDN特邀作者、博客专家、新星计划导师&#xff0c;我在计算机毕业设计开发方面积累了丰富的经验。同时&#xff0c;我也是掘金、华为云、阿里云、InfoQ等平台…

C语言的内存结构

在电脑中C语言编译器也像其他软件一样占用一块内存空间。 为了更好的利用好这块内存&#xff0c;C语言将他们分为 在C语言中&#xff0c;变量定义的位置不一样&#xff0c;那么在内存中所处的位置也是不一样的。&#xff08;变量在函数内部是存储在栈里&#xff0c;而在函数外部…

Android Camera2 与 Camera API技术探究和RAW数据采集

Android Camera2 Android Camera2 是 Android 系统中用于相机操作的一套高级应用程序接口&#xff08;API&#xff09;&#xff0c;它取代了之前的 Camera API。以下是关于 Android Camera2 的一些主要信息&#xff1a; 主要特点&#xff1a; 强大的控制能力&#xff1a;提供…