机器学习 CarRentalData数据集分析和预测

news2025/3/1 1:46:10

介绍数据集

fuelType:燃料类型
rating:评级
renterTripsTaken:租房者出行
reviewCount:审阅计数
location.city:位置.城市
location.country:地点.国家/地区
location.latitude:位置.纬度
location.longitude:位置.长度
location.state:位置状态
owner.id:所有者id
rate.daily:每日费率
vehicle.make:车辆制造
vehicle.model:车辆型号
vehicle.type:车辆类型
vehicle.year:车辆.年

实战演练

数据集展示

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly as py
import plotly_express as px
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')

#导入数据
df = pd.read_csv('C:/CarRentalData.csv',engine='python')
df.head()

#数据集大小
df.shape 
#(5851, 15)

在这里插入图片描述

数据的可视化

fuelType
df_fuelType = pd.DataFrame(df.fuelType.value_counts()).reset_index()
df_fuelType.rename(columns = {'index':'fuelType', 'fuelType':'count'}, inplace=True)

fig = px.pie(df_fuelType, values = 'count', names='fuelType', title = 'Fuel Type',hole=.3, 
             color_discrete_map={'ELECTRIC':'lightcyan',
                                 'HYBRID':'cyan',
                                 'GASOLINE':'royalblue',
                                 'DIESEL':'darkblue'})
                                 
fig.show()

在这里插入图片描述

rating
print("Rating Statistics:")
print(df['rating'].describe())

'''
Rating Statistics:
count    5350.000000
mean        4.920325
std         0.182425
min         1.000000
25%         4.900000
50%         5.000000
75%         5.000000
max         5.000000
Name: rating, dtype: float64
'''

fig = px.histogram(df, x = 'rating', title = 'Histogram of Rental Car Rating')
fig.show()

在这里插入图片描述

renterTripsTaken
print("Renter Trips Taken Statistics:")
print(df['renterTripsTaken'].describe())

'''
Renter Trips Taken Statistics:
count    5851.000000
mean       33.477354
std        41.898954
min         0.000000
25%         5.000000
50%        18.000000
75%        46.000000
max       395.000000
Name: renterTripsTaken, dtype: float64
'''

fig = px.histogram(df, x = 'renterTripsTaken', title = 'Histogram of Renter Trips Taken')
fig.show()

在这里插入图片描述

reviewCount
print("Review Count Statistics:")
print(df['reviewCount'].describe())

'''
Review Count Statistics:
count    5851.000000
mean       28.454794
std        35.136113
min         0.000000
25%         4.000000
50%        16.000000
75%        39.000000
max       321.000000
Name: reviewCount, dtype: float64
'''

fig = px.histogram(df, x = 'reviewCount', title = 'Histogram of Review Count')
fig.show()

在这里插入图片描述

Car Rentals by City
import plotly.graph_objects as go

def get_average_lat_long(city, ltype):
    choices = df[df['location.city'] == city]
    lat = choices['location.latitude'].mean()
    long = choices['location.longitude'].mean()
    if ltype == 0:
        return lat
    else:
        return long
        
df_location = pd.DataFrame(df['location.city'].value_counts()).reset_index()
df_location.rename(columns = {'index':'city', 'location.city':'count'}, inplace=True)
df_location['latitude'] = df_location['city'].apply(lambda x: get_average_lat_long(x, 0))
df_location['longitude'] = df_location['city'].apply(lambda x: get_average_lat_long(x, 1))

df_location['text'] = df_location['city'] + '<br>Car Rentals ' + (df_location['count']).astype(str)
limits = [(0,20),(21,50),(51,150),(151,200),(201,1000),(1001,1500)]
colors = ["royalblue","orange","lightgrey","lightseagreen","red","crimson"]
scale = 0.5
fig = go.Figure()

for i in range(len(limits)):
    lim = limits[i]
    df_sub = df_location[lim[0]:lim[1]]
    fig.add_trace(go.Scattergeo(
        locationmode = 'USA-states',
        lon = df_sub['longitude'],
        lat = df_sub['latitude'],
        text = df_sub['text'],
        marker = dict(
            size = df_sub['count']/scale,
            color = colors[i],
            line_color='rgb(40,40,40)',
            line_width=0.5,
            sizemode = 'area'
        ),
        name = '{0} - {1}'.format(lim[0],lim[1])))

fig.update_layout(
        title_text = 'Car Rentals by City',
        showlegend = True,
        geo = dict(
            scope = 'usa',
            landcolor = 'rgb(217, 217, 217)',
        )
    )

fig.show()

在这里插入图片描述

Car Rentals by State
df_state = pd.DataFrame(df['location.state'].value_counts()).reset_index()
df_state.rename(columns = {'index':'state', 'location.state':'count'}, inplace=True)

fig = go.Figure(data=go.Choropleth(
    locations=df_state['state'], # 空间坐标
    z = df_state['count'].astype(float), # 要进行颜色编码的数据
    locationmode = 'USA-states', # 位置集与locations中的条目匹配
    colorscale = 'Reds',
    colorbar_title = "Number of Cars Rented",
))

fig.update_layout(
    title_text = 'Car Rentals by State',
    geo_scope='usa', 
)

fig.show()

在这里插入图片描述

own.id
df_owner = pd.DataFrame(df['owner.id'].value_counts()).reset_index()
df_owner.rename(columns = {'index':'owner_id', 'owner.id':'number of rental cars'}, inplace=True)

print('Total Number of Unique Rental Cars per Owner Statistics:')
print(df_owner['number of rental cars'].describe())

'''
Total Number of Unique Rental Cars per Owner Statistics:
count    3093.000000
mean        1.891691
std         2.789205
min         1.000000
25%         1.000000
50%         1.000000
75%         2.000000
max        49.000000
Name: number of rental cars, dtype: float64
'''

fig = px.histogram(df_owner, x = 'number of rental cars', title='Total Number of Unique Rental Cars per Owner')
fig.show()

在这里插入图片描述

rate.daily
print('Daily Rate of Car Rental Statistics:')
print(df['rate.daily'].describe())

'''
Daily Rate of Car Rental Statistics:
count    5851.000000
mean       93.691506
std        96.080920
min        20.000000
25%        45.000000
50%        69.000000
75%       110.000000
max      1500.000000
Name: rate.daily, dtype: float64
'''

fig = px.histogram(df, x = 'rate.daily', title='Daily Rate of Car Rental')
fig.show()

在这里插入图片描述

Make and Model of Top 25 Most Rented Cars
df_make_model = df.groupby(['vehicle.make', 'vehicle.model']).size().reset_index()
df_make_model.rename(columns = {0:'count'}, inplace=True)
df_make_model.replace('Mercedes-benz', 'Mercedes-Benz', inplace=True)
df_make_model['make_count'] = df_make_model['vehicle.make'].apply(lambda x : df_make_model[df_make_model['vehicle.make'] == x]['count'].sum())
df_make_model.sort_values(by = 'make_count', ascending=False, inplace=True)

fig = px.bar(df_make_model[df_make_model['make_count'] >45], x = 'vehicle.make', y='count', color = 'vehicle.model', title='Make and Model of Top 25 Most Rented Cars')
fig.update_layout(showlegend = False)
fig.show()

在这里插入图片描述

Vehicle Type of Rented Cars
df_vehicleType = pd.DataFrame(df['vehicle.type'].value_counts()).reset_index()
df_vehicleType.rename(columns = {'index':'vehicle.type', 'vehicle.type':'count'}, inplace=True)

fig = px.pie(df_vehicleType, values = 'count', names='vehicle.type', title = 'Vehicle Type of Rented Cars')
fig.show()

在这里插入图片描述

Year of Vehicle
print('Vehicle Year Statistics:')
print(df['vehicle.year'].describe())

'''
Vehicle Year Statistics:
count    5851.000000
mean     2015.340113
std         4.050813
min      1955.000000
25%      2014.000000
50%      2016.000000
75%      2018.000000
max      2020.000000
Name: vehicle.year, dtype: float64
'''

fig = px.histogram(df, x = 'vehicle.year', title='Year of Vehicle')
fig.show()

在这里插入图片描述

热力图
plt.figure(figsize=(14,7))
sns.heatmap(df.corr(), annot=True)

在这里插入图片描述

数据预处理

#统计缺失值
df.isnull().sum()

'''
fuelType               75
rating                501
renterTripsTaken        0
reviewCount             0
location.city           0
location.country        0
location.latitude       0
location.longitude      0
location.state          0
owner.id                0
rate.daily              0
vehicle.make            0
vehicle.model           0
vehicle.type            0
vehicle.year            0
dtype: int64
'''
#数据集各列的数据类型,是否为空值,内存占用情况
df.info()

'''
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5851 entries, 0 to 5850
Data columns (total 15 columns):
 #   Column              Non-Null Count  Dtype  
---  ------              --------------  -----  
 0   fuelType            5776 non-null   object 
 1   rating              5350 non-null   float64
 2   renterTripsTaken    5851 non-null   int64  
 3   reviewCount         5851 non-null   int64  
 4   location.city       5851 non-null   object 
 5   location.country    5851 non-null   object 
 6   location.latitude   5851 non-null   float64
 7   location.longitude  5851 non-null   float64
 8   location.state      5851 non-null   object 
 9   owner.id            5851 non-null   int64  
 10  rate.daily          5851 non-null   int64  
 11  vehicle.make        5851 non-null   object 
 12  vehicle.model       5851 non-null   object 
 13  vehicle.type        5851 non-null   object 
 14  vehicle.year        5851 non-null   int64  
dtypes: float64(3), int64(5), object(7)
memory usage: 685.8+ KB
'''

df['fuelType'].unique()

'''
array(['ELECTRIC', 'HYBRID', 'GASOLINE', nan, 'DIESEL'], dtype=object)
'''

df['fuelType'].value_counts().reset_index()
'''
	index	fuelType
0	GASOLINE	4810
1	ELECTRIC	622
2	HYBRID	274
3	DIESEL	70
'''
#填补缺失值
df['fuelType'] = df['fuelType'].fillna('GASOLINE',axis=0)
#求众数
mode = df['rating'].mode()
mode = int(mode)
mode
'''
5
'''
df['rating'] = df['rating'].fillna(mode,axis=0)
pd.isnull(df).sum()
'''
fuelType              0
rating                0
renterTripsTaken      0
reviewCount           0
location.city         0
location.country      0
location.latitude     0
location.longitude    0
location.state        0
owner.id              0
rate.daily            0
vehicle.make          0
vehicle.model         0
vehicle.type          0
vehicle.year          0
dtype: int64
'''

可以发现缺失值已经填补完毕,没有缺失值了

df['fuelType'].unique()
'''
array(['ELECTRIC', 'HYBRID', 'GASOLINE', 'DIESEL'], dtype=object)
'''
#映射
fuelType_mapping= {'ELECTRIC':0.0, 'HYBRID':1.0,'GASOLINE':2.0,'DIESEL':3.0}
df['fuelType'] = df['fuelType'].map(fuelType_mapping)
df['location.state'].unique()
'''
array(['WA', 'NM', 'GA', 'SC', 'FL', 'TX', 'NC', 'CT', 'MA', 'ME', 'AL',
       'MT', 'TN', 'KY', 'ID', 'UT', 'MD', 'DC', 'IA', 'OH', 'CO', 'VA',
       'MI', 'NJ', 'IN', 'WI', 'KS', 'MO', 'NV', 'CA', 'LA', 'AR', 'IL',
       'MS', 'NH', 'MN', 'OK', 'NE', 'OR', 'PA', 'DE', 'AZ', 'WV', 'RI',
       'AK', 'HI'], dtype=object)
'''

locationState_mapping= {'WA':0.0, 'NM':1.0, 'GA':2.0, 'SC':3.0, 'FL':4.0, 'TX':5.0, 'NC':6.0, 'CT':7.0, 'MA':8.0, 'ME':9.0, 'AL':10.0,
       'MT':11.0, 'TN':12.0, 'KY':13.0, 'ID':14.0, 'UT':15.0, 'MD':16.0, 'DC':17.0, 'IA':18.0, 'OH':19.0, 'CO':20.0, 'VA':21.0,
       'MI':21.0, 'NJ':22.0, 'IN':23.0, 'WI':24.0, 'KS':25.0, 'MO':26.0, 'NV':27.0, 'CA':28.0, 'LA':29.0, 'AR':30.0, 'IL':31.0,
       'MS':32.0, 'NH':33.0, 'MN':34.0, 'OK':35.0, 'NE':36.0, 'OR':37.0, 'PA':38.0, 'DE':39.0, 'AZ':40.0, 'WV':41.0, 'RI':42.0,
       'AK':43.0, 'HI':44.0}
df['location.state'] = df['location.state'].map(locationState_mapping)
df['vehicle.type'].unique()
'''
array(['suv', 'car', 'truck', 'minivan', 'van'], dtype=object)
'''
vehicleType_mapping= {'suv':0.0, 'car':1.0,'truck':2.0,'minivan':3.0,'van':4.0}
df['vehicle.type'] = df['vehicle.type'].map(vehicleType_mapping)

其他列的值比较繁多,所以不做考虑,删掉它们就可以了

df['vehicle.make'].unique()
df['vehicle.model'].unique()

df = df.drop(labels=['location.city','location.country','vehicle.make','vehicle.model'],axis=1)

检查数据

df.head()

在这里插入图片描述

归一化与切分数据集

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

y = df.pop('vehicle.type')
X = df
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_train, X_valid, y_train, y_valid = train_test_split(X_scaled, y)

数据训练

import sklearn
from sklearn.preprocessing import StandardScaler,PolynomialFeatures
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import  OrdinalEncoder

from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split

from sklearn.metrics import mean_squared_error, r2_score

rfc = RandomForestRegressor()
rfc.fit(X_train, y_train)
# Feature Importances
features = X.columns
feature_imps = rfc.feature_importances_#特征重要性

# 重要特征的可视化
fig = px.bar(x=features, y=feature_imps)
fig.update_layout({'title':{'text':"Feature Importnace", 'x':0.5}})
fig.show()

在这里插入图片描述

#多分类线性模型
from sklearn.svm import  LinearSVC
linear_svm = LinearSVC().fit(X_train,y_train)
print("模型train得分:{:.3f}".format(linear_svm.score(X_train,y_train)))
print("模型test得分:{:.3f}".format(linear_svm.score(X_valid,y_valid)))
'''
模型train得分:0.624
模型test得分:0.643
'''
# Prediction
pred = linear_svm.predict(X_valid)

linear_svm_mse = mean_squared_error(y_valid, pred)
linear_svm_rmse = np.sqrt(linear_svm_mse)
linear_svm_r2 = r2_score(y_valid, pred)

print(linear_svm_mse,linear_svm_rmse,linear_svm_r2)
'''
0.5399863294600137 0.7348376211517845 -0.11486343099011109
'''

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

STM32按键实验中连接按键的GPIO管脚是上拉输入还是下拉输入

一、理解 关于STM32按键实验中连接按键的GPIO管脚是配置为上拉输入还是下拉输入的理解&#xff1a; 以江科大自动协教学视频按键输入实验为例&#xff1a; &#xff08;1&#xff09;按键KEY0<——>PE4 按键另一端接GND &#xff08;2&#xff09;按键KEY1<——&…

入门教学 | 快速了解集简云

集简云是一款超级软件连接器,无需开发,无需代码知识就可以轻松打通数百款软件之间的数据连接,构建自动化与智能化的业务流程。通过自动化业务流程,每月可节省企业数百甚至数万小时的人工成本。 集简云是什么? 集简云是一款超级软件连接器,无需开发,无需代码知识,就可以…

在现成的3D打印机上进行实验理论:一种数据孪生的攻击探测框架

在现成的3D打印机上提供了一种DT中攻击探测框架的DT解决方案的实验演示&#xff0c;作为说明性CPMS资源。通过网络安全DT对打印机正常运行、异常运行和攻击三种情况下的实验数据进行收集和分析&#xff0c;得出攻击检测结果。实验装置概述如下图所示。该实验研究是在现实世界设…

刚刚入职Android开发的应届生,该如何走向架构师

相信有不少从事Android开发的朋友&#xff0c;在工作一两年后会陷入一段迷茫期&#xff0c;有的是在工作中遇到了瓶颈&#xff0c;感觉无法突破&#xff1b;有的是想进阶成为架构师&#xff0c;但不知道如何进阶&#xff0c;因此产生了一些烦恼。为此小编在这里分享Android开发…

安卓开发: Compose 中的 Text 文本控件属性详解

Composable fun Text(text: String,modifier: Modifier Modifier,color: Color Color.Unspecified,fontSize: TextUnit TextUnit.Unspecified,fontStyle: FontStyle? null,fontWeight: FontWeight? null,fontFamily: FontFamily? null,letterSpacing: TextUnit TextU…

wps宏编辑器案例1-自定义函数使用

某公司考情和请假系统是2套独立的系统&#xff0c;人资在月底做考勤统计的时候需要把考勤系统导出的考勤信息表和OA请假流程导出的请假信息表进行合并&#xff0c;得出人员真实的考勤情况。比如员工“忠达”在考勤系统全显示缺勤&#xff0c;实际上请假系统里有4天请假&#xf…

16、Web原生组件注入(Servlet、Filter、Listener)

文章目录 1、使用Servlet API2、使用RegistrationBean 【尚硅谷】SpringBoot2零基础入门教程-讲师&#xff1a;雷丰阳 笔记 路还在继续&#xff0c;梦还在期许 1、使用Servlet API ServletComponentScan(basePackages “com.atguigu.admin”) :指定原生Servlet组件都放在那里…

全景天窗式科普数据仓库

数据仓库是一个面向主题的、集成的、随时间变化但信息本身相对稳定的数据集合&#xff0c;用于支持管理决策过程。其本质就是完成从面向业务过程数据的组织管理到面向业务分析数据的组织和管理的转变过程&#xff0c;也是商业智能BI中数据仓库的主要作用。 数据仓库 - 派可数据…

Spring Boot 定时任务

Spring Boot 提供了方便的注解来实现定时任务。下面是定时任务注解的详细教程&#xff1a; 一、添加依赖 要使用 Spring Boot 的定时任务注解&#xff0c;首先需要在项目中确认已添加过spring-boot-starter的依赖。 <dependency><groupId>org.springframework.b…

【youcans的深度学习 D01】PyTorch例程:从极简线性模型开始

欢迎关注『youcans的深度学习』系列 【youcans的深度学习 D01】PyTorch 例程&#xff1a;从极简线性模型开始 1. PyTorch 建模的基本步骤2. 线性模型的结构3. 建立 PyTorch 线性模型3.1 准备数据集3.2 定义线性模型类3.3 建立一个线性模型3.4 模型训练3.5 模型推断 4. PyTorch …

java-处理xml格式数据

处理xml格式数据 前言一、java处理xml格式数据1、 生成XML格式数据2、 解析XML格式数据 二、问题三、常用类及方法介绍 前言 dom4j是java中的XML API&#xff0c;性能优异、功能强大、开放源代码。 也是所有解析XML文件方法中最常用的&#xff01; 一、java处理xml格式数据 …

榜单发布 新能源乘用车OBC赛道进入转型升级周期

新能源汽车尤其是纯电动汽车市场的快速普及&#xff0c;也带动一批相关核心零部件厂商做大做强。比如&#xff0c;以车载充电机OBC及集成电源行业为例&#xff0c;威迈斯、富特科技等数家公司正在冲刺IPO。 目前&#xff0c;车载电源领域产品主要分为三种&#xff1a;一是单一…

步入AIGC时代,展望人工智能发展

步入AIGC时代&#xff0c;展望人工智能发展 0. 前言1. 步入 AIGC 时代1.1 人工智能简介1.2 AIGC 简介1.3 AIGC 发展与应用 2. CSIG 企业行——走进合合信息2.1 活动介绍2.2 走进合合信息 3. 文档图像处理中的底层视觉技术3.1 什么是底层视觉3.2 智能图像处理技术3.3 智能图像处…

消息中间件RabbitMQ---概述和概念 【一】

1、概述 1、大多应用中&#xff0c;可通过消息服务中间件来提升系统异步通信、扩展解耦能力 2、消息服务中两个重要概念&#xff1a; 消息代理&#xff08;message broker&#xff09;和目的地&#xff08;destination&#xff09; 当消息发送者发送消息以后&#xff0c;将由…

C语言中数据结构——顺序表

&#x1f436;博主主页&#xff1a;ᰔᩚ. 一怀明月ꦿ ❤️‍&#x1f525;专栏系列&#xff1a;线性代数&#xff0c;C初学者入门训练&#xff0c;题解C&#xff0c;C的使用文章&#xff0c;「初学」C &#x1f525;座右铭&#xff1a;“不要等到什么都没有了&#xff0c;才下…

java多线程详细讲解 线程的创建、线程的状态、synchronized锁、Volatile关键字、和cas锁(自旋锁 乐观锁 无锁)

java多线程详细讲解 线程的创建、线程的状态、synchronized锁、Volatile关键字、和cas锁&#xff08;自旋锁 乐观锁 无锁&#xff09; 一、线程的概念二、创建线程的三种方式三、线程方法Sleep、Yield、Join四、线程的执行状态五、synchronized关键字1.为什么要上锁?2.锁定的内…

SDL初识(1)

简介 SDL(Simple DirectMedia Layer) 是一个跨平台开发库&#xff0c;旨在通过 OpenGL 和 Direct3D 提供对音频、键盘、鼠标、操纵杆和图形硬件的低级访问。 SDL 支持 Windows、Mac OS X、Linux、iOS 和 Android。可以在源代码中找到对其他平台的支持。SDL 是用 C 语言编写的…

JavaScript【六】JavaScript中的字符串(String)

文章目录 &#x1f31f;前言&#x1f31f;字符串(String)&#x1f31f;单引号和双引号的区别&#x1f31f;属性&#x1f31f; length :字符串的长度 &#x1f31f; 方法&#x1f31f; str.charAt(index);&#x1f31f; str.charCodeAt(index);&#x1f31f; String.fromCharCod…

死磕“增长”:火山引擎的实用主义

作者 | 曾响铃 文 | 响铃说 在刘慈欣的科幻小说《三体》中&#xff0c;地外文明为了封锁地球科技&#xff0c;在天文台向地球科学家展现了「宇宙闪烁」这一奇观&#xff0c;试图颠覆人类的认知&#xff0c;从而影响科技进步&#xff0c;促使地球科技发展陷入停滞。 如今&…

给你们讲个笑话——低代码会取代程序员

今天是正经男&#xff0c;我们严肃讨论一下一直以来争吵不休的取代问题。 低代码开发平台&#xff0c;低代码技术会取代开发人员么&#xff1f; 一、背景 低代码开发平台的普及&#xff0c;让很多公司对快速生成应用抱有很大期望。甚至有人认为&#xff0c;低代码开发平台未来…