【机器学习实战】二、随机森林算法预测出租车车费案例

本文主要是介绍【机器学习实战】二、随机森林算法预测出租车车费案例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

随机森林算法预测出租车车费案例

一、导入第三方库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn
二、加载数据集
train = pd.read_csv('train.csv',nrows=1000000) # 加载前1000000条数据
test = pd.read_csv('test.csv')
三、数据分析、清洗
train.shape # 训练集的形状
# 输出:(1000000,8)
test.shape # 测试集的形状
# 输出:(9914, 7)
train.head() # 显示训练集的前五行数据

在这里插入图片描述

test.head() # 显示前5行测试集数据

在这里插入图片描述

train.describe() # 描述训练集

在这里插入图片描述

test.describe() # 描述测试集

在这里插入图片描述
(1)检查数据中是否有空值

train.isnull().sum().sort_values(ascending=True) # 统计空值的数量,根据数量大小排序

在这里插入图片描述

test.isnull().sum().sort_values(ascending=True) #  统计空值数量

在这里插入图片描述

# 删除train中的空值
train.drop(train[train.isnull().any(1)].index, axis=0,inplace=True)
train.shape # 比原始数据减少10行
# 输出 (999990,8)

(2)检查fare_amount列是否有不合法值

train['fare_amount'].describe() # 描述fare_amount

在这里插入图片描述

# 将fare_amount的值小于0的进行统计
from collections import Counter
Counter(train['fare_amount'] < 0 ) # 共计38行车费小于0的数据
# 输出:Counter({False: 999952, True: 38})
# 将这38行数据删除
train.drop(train[train['fare_amount']<0].index,axis=0,inplace=True)
train['fare_amount'].describe()# 查看车费数据

在这里插入图片描述

# 可视化(直方图):0<票价<100   bins=100 划分为100份 
train[train.fare_amount<100].fare_amount.hist(bins=100,figsize=(14,3)) 
plt.xlabel('fare $')
plt.title('Histogram')

在这里插入图片描述
(3) 检查乘客passenger_count这一列

train['passenger_count'].describe() # 描述passenger_count这一列

在这里插入图片描述

# 查看乘客人数大于6的数据
train[train['passenger_count']>6]

在这里插入图片描述

# 删除离异值
train.drop(train[train['passenger_count']>6].index,axis=0,inplace=True)

(4)检查上车点的经度和纬度
1.纬度范围:-90 ~ 90
2.经度范围:-180 ~ 180

train['pickup_latitude'].describe() # 查看上车点纬度数据(min和max的离异值)

在这里插入图片描述

# 查看纬度小于 -90 的数据
train[train['pickup_latitude']< -90]

在这里插入图片描述

# 查看纬度大于 90 的数据
train[train['pickup_latitude'] > 90]

在这里插入图片描述

# 删除离异值
train.drop(train[(train['pickup_latitude'] > 90) | (train['pickup_latitude'] < -90 )].index, axis= 0 , inplace = True)
train.shape
# 输出:(999939, 8)
train['pickup_longitude'].describe() # 查看上车点的经度数据

在这里插入图片描述

train[train['pickup_longitude'] < - 180]

在这里插入图片描述

# 删除这些数据
train.drop(train[train['pickup_longitude'] < -180 ].index , axis=0 , inplace =True)
train.shape
# 输出:(999928, 8)

(5)检查下车点的经度和纬度

train.drop(train[(train['dropoff_latitude'] < -90 ) | (train['dropoff_latitude'] > 90 )].index, axis=0,inplace=True)
train.drop(train[(train['dropoff_longitude'] < -180 )| (train['dropoff_longitude'] > 180 )].index, axis=0 ,inplace= True)
train.shape
# 输出:(999911, 8)

(6)可视化地图,清理一些离异值

# 在测试集上确定一个区域,删除掉train数据集中不在区域框内的奇异点
# (1)纬度最小值,纬度最大值
min(test.pickup_latitude.min(),test.dropoff_latitude.min()), \
max(test.pickup_latitude.max(),test.dropoff_latitude.max())
# 输出: (40.568973, 41.709555)
# (2)经度最小值,经度最大值
min(test.pickup_longitude.min(), test.dropoff_longitude.min()), \
max(test.pickup_longitude.max(), test.dropoff_longitude.max())
# 输出:(-74.263242, -72.986532)
# (3)根据指定的区域框,删除掉奇异点
def select_within_boundingbox(df,BB):return (df.pickup_longitude >= BB[0]) & (df.pickup_longitude <= BB[1]) & \(df.pickup_latitude >= BB[2]) & (df.pickup_latitude <= BB[3]) & \(df.dropoff_longitude >= BB[0]) & (df.dropoff_longitude <= BB[1]) & \(df.dropoff_latitude >= BB[2]) & (df.dropoff_latitude <= BB[3])
BB = (-74.5,-72.8,40.5,41.8)
# 截图
nyc_map = plt.imread('./nyc_-74.5_-72.8_40.5_41.8.png')
BB_zoom = (-74.3, -73.7, 40.5, 40.9) # 放大后的地图
# 截图(放大)
nyc_map_zoom = plt.imread('./nyc_-74.3_-73.7_40.5_40.9.png')
train = train[select_within_boundingbox(train, BB)]# 删除区域框之外的点
train.shape
# 输出:(979018, 8)
# (4)在地图显示这些点def plot_on_map(df, BB, nyc_map, s=10, alpha=0.2):fig, axs = plt.subplots(1, 2, figsize=(16,10))# 第一个子图axs[0].scatter(df.pickup_longitude, df.pickup_latitude, alpha=alpha, c='r', s=s)axs[0].set_xlim(BB[0], BB[1])axs[0].set_ylim(BB[2], BB[3])axs[0].set_title('PickUp Locations')axs[0].imshow(nyc_map, extent=BB)# 第二个子图axs[1].scatter(df.dropoff_longitude, df.dropoff_latitude, alpha=alpha, c='r', s=s)axs[1].set_xlim((BB[0], BB[1]))axs[1].set_ylim((BB[2], BB[3]))axs[1].set_title('Dropoff locations')axs[1].imshow(nyc_map, extent=BB)
plot_on_map(train, BB, nyc_map, s=1, alpha=0.3)

在这里插入图片描述

plot_on_map(train, BB_zoom, nyc_map_zoom, s=1, alpha=0.3)

在这里插入图片描述
(7) 检查数据类型

train.dtypes

在这里插入图片描述

# 日期类型转换:key, pickup_datetimefor dataset in [train, test]:dataset['key'] = pd.to_datetime(dataset['key'])dataset['pickup_datetime'] = pd.to_datetime(dataset['pickup_datetime'])

(8)日期数据进行分析
将日期分隔为: 1.year 2.month 3.day 4.hour 5.day of week

# 增加5列,分别是:year, month, day, hour, day of weekfor dataset in [train, test]:dataset['year'] = dataset['pickup_datetime'].dt.yeardataset['month'] = dataset['pickup_datetime'].dt.monthdataset['day'] = dataset['pickup_datetime'].dt.daydataset['hour'] = dataset['pickup_datetime'].dt.hourdataset['day of week'] = dataset['pickup_datetime'].dt.dayofweek
train.head()

在这里插入图片描述

test.head()

在这里插入图片描述
(9)根据经纬度计算距离

# 计算公式def distance(lat1, long1, lat2, long2):data = [train, test]for i in data:R = 6371  # 地球半径(单位:千米)phi1 = np.radians(i[lat1])phi2 = np.radians(i[lat2])delta_phi = np.radians(i[lat2]-i[lat1])delta_lambda = np.radians(i[long2]-i[long1])#a = sin²((φB - φA)/2) + cos φA . cos φB . sin²((λB - λA)/2)a = np.sin(delta_phi / 2.0) ** 2 + np.cos(phi1) * np.cos(phi2) * np.sin(delta_lambda / 2.0) ** 2#c = 2 * atan2( √a, √(1−a) )c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a))#d = R*cd = (R * c) # 单位:千米i['H_Distance'] = dreturn d
distance('pickup_latitude','pickup_longitude','dropoff_latitude','dropoff_longitude')

在这里插入图片描述

# 统计距离为0,票价为0的数据train[(train['H_Distance']==0) & (train['fare_amount']==0)]

在这里插入图片描述

# 删除
train.drop(train[(train['H_Distance']==0) & (train['fare_amount']==0)].index, axis=0, inplace=True)
# 统计距离为0,票价不为0的数据# 原因1:司机等待乘客很长时间,乘客最终取消了订单,乘客依然支付了等待的费用;
# 原因2:车辆的经纬度没有被准确录入或缺失;len(train[(train['H_Distance']==0) & (train['fare_amount']!=0)])
# 输出:10478
# 删除
train.drop(train[(train['H_Distance']==0) & (train['fare_amount']!=0)].index, axis=0, inplace=True)

(10)新的字段:每公里车费:根据距离、车费,计算每公里的车费

train['fare_per_mile'] = train.fare_amount / train.H_Distancetrain.fare_per_mile.describe()

在这里插入图片描述

train.head()

在这里插入图片描述

# 统计每一年的不同时间段的每小时车费train.pivot_table('fare_per_mile', index='hour', columns='year').plot(figsize=(14, 6))
plt.ylabel('Fare $/mile')

在这里插入图片描述

四、模型训练和数据预测
train.columns

在这里插入图片描述

test.columns

在这里插入图片描述

X_train = train.iloc[:,[3,4,5,6,7,8,9,10,11,12,13]]
y_train = train.iloc[:,[1]] # fare_amount 车费
X_train.shape
# 输出:(968537, 11)
y_train.shape
# 输出:(968537, 1)
五、随机森林算法实现
from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor()
rf.fit(X_train,y_train)

在这里插入图片描述

test.columns

在这里插入图片描述

rf_predict = rf.predict(test.iloc[:, [2,3,4,5,6,7,8,9,10,11,12]])
submission = pd.read_csv("sample_submission.csv")submission.head()

在这里插入图片描述

# 提交submission = pd.read_csv("sample_submission.csv")submission['fare_amount'] = rf_predictsubmission.to_csv("submission_1.csv", index=False)submission.head()

在这里插入图片描述

这篇关于【机器学习实战】二、随机森林算法预测出租车车费案例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/307286

相关文章

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

在Spring Boot中浅尝内存泄漏的实战记录

《在SpringBoot中浅尝内存泄漏的实战记录》本文给大家分享在SpringBoot中浅尝内存泄漏的实战记录,结合实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录使用静态集合持有对象引用,阻止GC回收关键点:可执行代码:验证:1,运行程序(启动时添加JVM参数限制堆大小):2,访问 htt

openCV中KNN算法的实现

《openCV中KNN算法的实现》KNN算法是一种简单且常用的分类算法,本文主要介绍了openCV中KNN算法的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录KNN算法流程使用OpenCV实现KNNOpenCV 是一个开源的跨平台计算机视觉库,它提供了各

Python中使用正则表达式精准匹配IP地址的案例

《Python中使用正则表达式精准匹配IP地址的案例》Python的正则表达式(re模块)是完成这个任务的利器,但你知道怎么写才能准确匹配各种合法的IP地址吗,今天我们就来详细探讨这个问题,感兴趣的朋... 目录为什么需要IP正则表达式?IP地址的基本结构基础正则表达式写法精确匹配0-255的数字验证IP地

MySQL高级查询之JOIN、子查询、窗口函数实际案例

《MySQL高级查询之JOIN、子查询、窗口函数实际案例》:本文主要介绍MySQL高级查询之JOIN、子查询、窗口函数实际案例的相关资料,JOIN用于多表关联查询,子查询用于数据筛选和过滤,窗口函... 目录前言1. JOIN(连接查询)1.1 内连接(INNER JOIN)1.2 左连接(LEFT JOI

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

springboot+dubbo实现时间轮算法

《springboot+dubbo实现时间轮算法》时间轮是一种高效利用线程资源进行批量化调度的算法,本文主要介绍了springboot+dubbo实现时间轮算法,文中通过示例代码介绍的非常详细,对大家... 目录前言一、参数说明二、具体实现1、HashedwheelTimer2、createWheel3、n

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

MyBatis 动态 SQL 优化之标签的实战与技巧(常见用法)

《MyBatis动态SQL优化之标签的实战与技巧(常见用法)》本文通过详细的示例和实际应用场景,介绍了如何有效利用这些标签来优化MyBatis配置,提升开发效率,确保SQL的高效执行和安全性,感... 目录动态SQL详解一、动态SQL的核心概念1.1 什么是动态SQL?1.2 动态SQL的优点1.3 动态S