kaggel-汽车价格预测项目

1.读取数据,查看数据基本概况

import pandas  as pd
data=pd.read_csv(r'./car_price_prediction.csv')

#查看前5行数据
print(data.head(5))

output:
             ID  Price  Levy  ...             Wheel   Color  Airbags
0  45654403  13328  1399  ...        Left wheel  Silver       12
1  44731507  16621  1018  ...        Left wheel   Black        8
2  45774419   8467     -  ...  Right-hand drive   Black        2
3  45769185   3607   862  ...        Left wheel   White        0
4  45809263  11726   446  ...        Left wheel  Silver        4

[5 rows x 18 columns]

print(data.info)

output:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 19237 entries, 0 to 19236
Data columns (total 18 columns):
 #   Column            Non-Null Count  Dtype  
---  ------            --------------  -----  
 0   ID                19237 non-null  int64  
 1   Price             19237 non-null  int64  
 2   Levy              19237 non-null  object 
 3   Manufacturer      19237 non-null  object 
 4   Model             19237 non-null  object 
 5   Prod. year        19237 non-null  int64  
 6   Category          19237 non-null  object 
 7   Leather interior  19237 non-null  object 
 8   Fuel type         19237 non-null  object 
 9   Engine volume     19237 non-null  object 
 10  Mileage           19237 non-null  object 
 11  Cylinders         19237 non-null  float64
 12  Gear box type     19237 non-null  object 
 13  Drive wheels      19237 non-null  object 
 14  Doors             19237 non-null  object 
 15  Wheel             19237 non-null  object 
 16  Color             19237 non-null  object 
 17  Airbags           19237 non-null  int64  
dtypes: float64(1), int64(4), object(13)

#可以看到数据有19237行,有18列,其中没有缺失值

#查看重复的数据
print(data.duplicated().sum())

output:
    313
#去除重复列
data.drop_duplicates(inplace=True)

#查看每一列数据的取值情况
for col in  data.columns:
    print(col)
    print(data[col].value_counts())

output:
    ID
45815365    8
45815361    8
45815363    7
45815368    7
45723475    7
           ..
45774312    1
45732621    1
45773011    1
45774019    1
45813273    1
Name: ID, Length: 18924, dtype: int64
------------------------------
Price
15681    280
470      274
14113    244
392      242
314      235
        ... 
42601      1
149        1
54349      1
54954      1
22075      1
Name: Price, Length: 2315, dtype: int64
------------------------------
Levy
-       5819
765      486
891      461
639      410
640      405
        ... 
3156       1
2908       1
1279       1
1719       1
1901       1
Name: Levy, Length: 559, dtype: int64
------------------------------
Manufacturer
HYUNDAI          3769
TOYOTA           3662
MERCEDES-BENZ    2076
FORD             1111
CHEVROLET        1069
                 ... 
TESLA               1
PONTIAC             1
SATURN              1
ASTON MARTIN        1
GREATWALL           1
Name: Manufacturer, Length: 65, dtype: int64
------------------------------
Model
Prius                    1083
Sonata                   1079
Camry                     938
Elantra                   922
E 350                     542
                         ... 
Feroza                      1
C-MAX C-MAX                 1
X1 4X4                      1
Land Cruiser Prado RX       1
Prius C aqua                1
Name: Model, Length: 1590, dtype: int64
------------------------------
Prod. year
2012    2155
2014    2124
2013    1963
2011    1612
2015    1549
2010    1483
2016    1476
2017     959
2008     737
2009     601
2018     500
2007     464
2005     402
2003     367
2004     364
2006     317
2019     306
2002     296
2000     279
2001     254
1998     213
1999     207
1997     151
1996     114
1995     105
2020      47
1994      42
1992      30
1993      23
1990      18
1988      12
1991      10
1986       6
1989       6
1987       5
1984       5
1985       5
1953       4
1983       3
1939       3
1978       2
1980       2
1965       2
1977       2
1974       2
1964       2
1943       1
1976       1
1957       1
1968       1
1947       1
1982       1
1981       1
1973       1
Name: Prod. year, dtype: int64
------------------------------
Category
Sedan          8736
Jeep           5473
Hatchback      2847
Minivan         647
Coupe           532
Universal       364
Microbus        306
Goods wagon     233
Pickup           52
Cabriolet        36
Limousine        11
Name: Category, dtype: int64
------------------------------
Leather interior
Yes    13954
No      5283
Name: Leather interior, dtype: int64
------------------------------
Fuel type
Petrol            10150
Diesel             4036
Hybrid             3578
LPG                 892
CNG                 494
Plug-in Hybrid       86
Hydrogen              1
Name: Fuel type, dtype: int64
------------------------------
Engine volume
2            3916
2.5          2277
1.8          1760
1.6          1462
1.5          1321
             ... 
6.8             1
6.7             1
3.1             1
0.8 Turbo       1
1.1 Turbo       1
Name: Engine volume, Length: 107, dtype: int64
------------------------------
Mileage
0 km         721
200000 km    183
150000 km    161
160000 km    120
100000 km    119
            ... 
63083 km       1
28750 km       1
25077 km       1
77452 km       1
186923 km      1
Name: Mileage, Length: 7687, dtype: int64
------------------------------
Cylinders
4.0     14367
6.0      3462
8.0       991
5.0       169
3.0       107
2.0        42
1.0        38
12.0       38
10.0       12
16.0        5
7.0         4
9.0         1
14.0        1
Name: Cylinders, dtype: int64
------------------------------
Gear box type
Automatic    13514
Tiptronic     3102
Manual        1875
Variator       746
Name: Gear box type, dtype: int64
------------------------------
Drive wheels
Front    12874
4x4       4058
Rear      2305
Name: Drive wheels, dtype: int64
------------------------------
Doors
04-May    18332
02-Mar      777
>5          128
Name: Doors, dtype: int64
------------------------------
Wheel
Left wheel          17753
Right-hand drive     1484
Name: Wheel, dtype: int64
------------------------------
Color
Black            5033
White            4489
Silver           3792
Grey             2375
Blue             1396
Red               639
Green             322
Orange            253
Brown             187
Carnelian red     179
Golden            145
Beige             134
Sky blue          122
Yellow            106
Purple             39
Pink               26
Name: Color, dtype: int64
------------------------------
Airbags
4     5823
12    5654
0     2405
8     1608
6     1311
2     1066
10     849
5      104
16      93
7       86
1       76
9       63
3       37
11      33
14      20
15       7
13       2
Name: Airbags, dtype: int64
------------------------------

        可以看到在Levy中‘-’有5819条记录,Engine volume这个特征有些带有单位Turbo,Doors特征带有特殊英文和大于号,Mileage特征带有km单位,Prod. year 特征代表的是汽车是哪一年生产的,需要根据这个计算汽车的已经使用了多少年 。我们将在接下来的数据清洗步骤,解决这些问题。

2.数据清洗

#数据清洗
#Levy是税的意思,'-'应该表示的是没有税,所以应该将'-'替换为0

data['Levy']=data['Levy'].apply(lambda x:x.replace('-','0')).astype(int)

#除去单位km
data['Mileage']= data['Mileage'].str.replace('km','').astype(float)

#提取正确的车门数
data["Doors"]=data["Doors"].apply(lambda x: x.split("-")[0] if "-" in x else x.replace(">", "")).astype(int)

#新增加1列特征表示是否为turbo
data['is_turbo']=data['Engine volume'].apply(lambda x:1 if 'Turbo' in x else 0)
#将Engine volume中带有的turbo单位去掉
data['Engine volume']=data['Engine volume'].str.replace('Turbo','').astype(float)
#查看特征中不同取值的个数
print(data.nunique())
output:
ID                  18924
Price                2315
Levy                  559
Manufacturer           65
Model                1590
Prod. year             54
Category               11
Leather interior        2
Fuel type               7
Engine volume         107
Mileage              7687
Cylinders              13
Gear box type           4
Drive wheels            3
Doors                   3
Wheel                   2
Color                  16
Airbags                17
is_turbo                2

from date_time import date_time

years_now=datetime.now().year

data[age']=years_now-data['Prod. year']

print(data[['Prod. year','age']].head(5))

output:
       Prod. year  age
0        2010       14
1        2011       13
2        2006       18
3        2011       13
4        2014       10

#可以看到在数据中有许多特征是类别,需要进行编码转换

category_col=['Manufacturer','Model','Category','Leather interior','Fuel type',
         'Gear box type','Drive wheels','Wheel','Color']

from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
for col in category_col:
    data[col]=le.fit_transform(data[col])

#去掉没用的特征
data.drop(columns=['ID','Prod. year'],inplace=True)

#查看是否有异常值,并且删除异常值

num_col=['Price','Levy','age','Engine volume','Mileage','Airbags']

for col in num_col:
    q1 = data[col].quantile(0.25)
    q3 = data[col].quantile(0.75)
    iqr = q3 - q1
    low = q1 - 1.5*iqr
    high = q3 + 1.5*iqr
    outlier = ((data[col] > high) | (data[col] < low)).sum()
    total_outliers = data[col].shape[0]
    print(f"Total Outliars in {col} are : {outlier} : {round(100*(outlier)/total_outliers,2)}%")
    if outlier>0:
        data=data.loc[(data[col]<=high) & (data[col]>=low)]
output:

Total Outliars in Price are : 1055 : 5.57%
Total Outliars in Levy are : 161 : 0.9%
Total Outliars in age are : 1468 : 8.29%
Total Outliars in Engine volume are : 951 : 5.86%
Total Outliars in Mileage are : 623 : 4.07%
Total Outliars in Airbags are : 0 : 0.0%

3.数据标准化

from sklearn.preprocessing import  StandardScaler

scaler=StandardScaler()
data.dropna(inplace=True)
scaled_df = scaler.fit_transform(data.drop(["Price"],axis=1))

4.建模

X=scaled_df
y=data["Price"]
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.1, random_state=42)
print("X_train shape: ", X_train.shape)
print("y_train shape: ", y_train.shape)

print("X_val shape: ", X_val.shape)
print("y_val shape: ", y_val.shape)

print("X_test shape: ", X_test.shape)
print("y_test shape: ", y_test.shape)

output:

X_train shape:  (10558, 17)
y_train shape:  (10558,)
X_val shape:  (1174, 17)
y_val shape:  (1174,)
X_test shape:  (2934, 17)
y_test shape:  (2934,)

from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.svm import SVR
from xgboost import XGBRegressor
from sklearn.model_selection import train_test_split,GridSearchCV

from sklearn.metrics import r2_score,mean_squared_error

def models(model):
    model.fit(X_train,y_train)
    pre=model.predict(X_test)
    r2=r2_score(y_test,pre)
    R2.append(r2)
    rmse=np.sqrt(mean_squared_error(y_test,pre))
    RMSE.append(rmse)
    score=model.score(X_test,y_test)
    #print(f"the score of the model is : {score}")

Algorithms=['LinearRegression','DecisionTreeRegressor','RandomForestRegressor','GradientBoostingClassifier','XGBRegressor','SVR']
R2=[]
RMSE=[]
model1=LinearRegression()
model2=DecisionTreeRegressor(random_state=42)
model3=RandomForestRegressor()
model4=GradientBoostingRegressor()
model5=XGBRegressor()
model6=SVR()
models(model1)
models(model2)
models(model3)
models(model4)
models(model5)
models(model6)
df1=pd.DataFrame({'Algorithms':Algorithms,'R2_score':R2,'RMSE':RMSE})

output:

                   Algorithms  R2_score          RMSE
0            LinearRegression  0.233513  10128.813642
1       DecisionTreeRegressor  0.582993   7470.986717
2       RandomForestRegressor  0.772239   5521.352505
3  GradientBoostingClassifier  0.637696   6963.746857
4                XGBRegressor  0.749141   5794.573718
5                         SVR -0.014145  11650.813825
5.深度学习模型
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(64, input_dim=X_train.shape[1], activation="linear"))
model.add(Dense(32, activation="linear"))
model.add(Dense(1, activation="linear"))
model.compile(optimizer="adam", loss="mean_squared_error", metrics=["mean_squared_error"])
result=model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=20, verbose=0)
# print(model.evaluate())
print(np.sqrt(result.history["val_loss"]))

output:
    [18120.89683427 15209.23247943 11820.44869939 10217.87591285
  9988.96333788  9967.14313751  9955.55527899  9952.93869747
  9956.04175707  9956.86708593  9956.54835753  9952.67119581
  9959.13493298  9955.99503163  9955.22404599  9953.39106622
  9955.59464297  9956.9463529   9958.24650314  9957.58592009]

plt.figure(figsize=(15,8))
plt.plot(result.history["loss"])
plt.plot(result.history["val_loss"])
plt.title("Loss Graph")
plt.ylabel("Loss")
plt.xlabel("Epochs")
plt.legend(["Training", "Validation"])
plt.show()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/758675.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

css 滚动词云

css javascript 实现滚动词云效果 // 163css.js var radius 120; var dtr Math.PI / 180; var d 300; var mcList []; var active false; var lasta 1; var lastb 1; var distr true; var tspeed 10; var size 250; var mouseX 0; var mouseY 0; var howElliptic…

宝塔安装rabbitMQ实战

服务器环境说明 阿里云服务器、宝塔、centos7 一、下载erlang 原因&#xff1a;RabbitMQ服务端代码是使用并发式语言Erlang编写的&#xff0c;安装Rabbit MQ的前提是安装Erlang。 下载地址&#xff1a;http://www.erlang.org/downloads 下载对应的版本&…

进程间通信简介-I.MX6U嵌入式Linux C应用编程学习笔记基于正点原子阿尔法开发板

进程间通信简介 进程间通信简介 进程间进程简称IPC(interprocess communication)&#xff0c;进程间通信就是在不同进程之间传递信息或交换信息 进程间通信的目的 数据传输&#xff1a;一个进程需要将它的数据发送给另一个进程 资源共享&#xff1a;多个进程之间共享同样的…

互联网算法备案 | 填报指南

一、填报入口 登陆互联网信息服务算法备案系统&#xff08;以下简称备案系统&#xff09;进行填报&#xff0c;网址为https://beian.cac.gov.cn。系统首页如图1所示。 图1备案系统首页&#xff08;示意图&#xff09; 二、填报流程 填报人员需首先注册并登陆备案系统&#x…

用Roofline模型去分析pytorch和Triton算子

用Roofline模型去分析pytorch和Triton算子 1.参考链接2.测试环境3.安装相关依赖4.锁频5.获取理论算力6.创建测试脚本7.运行测试程序生成Roofline图8.NVIDIA Nsight Compute生成Roofline9.效果图A.nn.LinearB.Triton实现 本文演示了如何用Roofline模型去分析pytorch和Triton算子…

探秘 NTHU-DDD:疲劳与哈欠背后的驾驶安全密码(目标检测)

亲爱的读者们&#xff0c;您是否在寻找某个特定的数据集&#xff0c;用于研究或项目实践&#xff1f;欢迎您在评论区留言&#xff0c;或者通过公众号私信告诉我&#xff0c;您想要的数据集的类型主题。小编会竭尽全力为您寻找&#xff0c;并在找到后第一时间与您分享。 一、引言…

【最新鸿蒙应用开发】——用户信息封装

用户管理工具封装 1. 为什么要封装 在进行如下登录功能时&#xff0c; 通常需要将一些用户信息以及token进行持久化保存&#xff0c;以方便下次进行数据请求时携带这些用户信息来进行访问后端数据。下面分享一下鸿蒙当中实用的持久化封装操作。 2. 步骤 封装用户信息管理工具…

Django 配置静态文件

1&#xff0c;DebugTrue 调试模式 Test/Test/settings.py DEBUG True...STATICFILES_DIRS [os.path.join(BASE_DIR, static),] STATIC_URL /static/ 1.1 创建静态文件 Test/static/6/images/Sni1.png 1.2 添加视图函数 Test/app6/views.py from django.shortcuts impor…

【D3.js in Action 3 精译】1.2.2 可缩放矢量图形(二)

当前内容所在位置 第一部分 D3.js 基础知识 第一章 D3.js 简介 1.1 何为 D3.js&#xff1f;1.2 D3 生态系统——入门须知 1.2.1 HTML 与 DOM1.2.2 SVG - 可缩放矢量图形 ✔️ 第一部分【第二部分】✔️第三部分&#xff08;精译中 ⏳&#xff09; 1.2.3 Canvas 与 WebGL&#x…

互联网大厂核心知识总结PDF资料

我们要敢于追求卓越&#xff0c;也能承认自己平庸&#xff0c;不要低估3&#xff0c;5&#xff0c;10年沉淀的威力 hi 大家好&#xff0c;我是大师兄&#xff0c;大厂工作特点是需要多方面的知识和技能。这种学习和积累一般人需要一段的时间&#xff0c;不太可能一蹴而就&…

获取 url 地址栏 ? 后面的查询字符串,并以键值对形式放到对象里面

写在前面 在前端面试当中&#xff0c;关于 url 相关的问题很常见&#xff0c;而对于 url 请求参数的问题也很常见&#xff0c;大部分以笔试题常见&#xff0c;今天就根据这道面试题一起来看一下。 问题 获取 url 地址栏?后面的查询字符串&#xff0c;并以键值对形式放到对象…

【图解大数据技术】Hadoop、HDFS、MapReduce、Yarn

【图解大数据技术】Hadoop、HDFS、MapReduce、Yarn HadoopHDFSHDFS架构写文件流程读文件流程 MapReduceMapReduce简介MapReduce整体流程 Yarn Hadoop Hadoop是Apache开源的分布式大数据存储与计算框架&#xff0c;由HDFS、MapReduce、Yarn三部分组成。广义上的Hadoop其实是指H…

Ubuntu网络管理命令:netstat

安装Ubuntu桌面系统&#xff08;虚拟机&#xff09;_虚拟机安装ubuntu桌面版-CSDN博客 顾名思义&#xff0c;netstat命令不是用来配置网络的&#xff0c;而是用来查看各种网络信息的&#xff0c;包括网络连接、路由表以及网络接口的各种统计数据等。 netstat命令的基本语法如…

Sora DiT图解【文生视频】

“在古老的迪萨罗斯大陆&#xff0c;曾经住着一位传奇人物&#xff0c;名叫索拉&#xff08;Sora&#xff09;。这个传奇人物体现了无限潜力的本质&#xff0c;包括天空的浩瀚和壮丽。 当它飞得很高&#xff0c;彩虹色的翅膀横跨广阔的空间&#xff0c;光线从它引人注目的身体…

QTreeView第一列自适应

通过setStretchLastSection(bool stretch)可以设置最后一列自适应,对于QTreeView,stretch默认为true。但有时候我们需要设置第一列自适应,比如文件浏览器,共有名称、大小和修改日期三列,大小和日期的宽度几乎是固定的,但名称却可长可短,此时我们希望在窗口大小变化时,第…

【算法专题--栈】用栈实现队列 -- 高频面试题(图文详解,小白一看就懂!!)

目录 一、前言 二、题目描述 三、解题方法 ⭐双栈 模拟 队列 &#x1f95d;栈 和 队列 的特性 &#x1f34d;具体思路 &#x1f34d;案例图解 四、总结与提炼 五、共勉 一、前言 用栈实现队列 这道题&#xff0c;可以说是--栈专题--&#xff0c;最经典的一道题&…

Python数据分析-股票分析和可视化(深证指数)

一、内容简介 股市指数作为衡量股市整体表现的重要工具&#xff0c;不仅反映了市场的即时状态&#xff0c;也提供了经济健康状况的关键信号。在全球经济体系中&#xff0c;股市指数被广泛用于预测经济活动&#xff0c;评估投资环境&#xff0c;以及制定财政和货币政策。在中国…

【入门】5分钟了解卷积神经网络CNN是什么

本文来自《老饼讲解-BP神经网络》https://www.bbbdata.com/ 目录 一、卷积神经网络的结构1.1.卷积与池化的作用2.2.全连接层的作用 二、卷积神经网络的运算2.1.卷积层的运算2.2.池化的运算2.3.全连接层运算 三、pytorch实现一个CNN例子3.1.模型的搭建3.2.CNN完整训练代码 CNN神…

几种热管的构造

1、超薄热管构造形式 在实际应用中&#xff0c;超薄热管通常定义为厚度小于2.0mm的平板热管。超薄热管很薄&#xff0c;可紧贴电子元件表面散热&#xff0c;故被广泛应用于移动和可携带电子设备&#xff0c;如智能手机、笔记本电脑和智能手表。用于笔记本电脑和平板电脑的超薄…
最新文章