kaggle练习-共享单车数据

本文基于kaggle共享单车数据集进行分析,包括数据预处理、特征工程和模型构建。研究了时间特征、天气因素对租赁量的影响,发现温度、湿度和风速与租赁量的相关性。通过随机森林填充风速缺失值,最终模型预测结果的r2超过90%。
摘要由CSDN通过智能技术生成

中国小黄车的惨败,激起了我对共享单车的兴趣。国外的这一行业要早于中国,这个数据是来自kaggle的比赛项目,由美国一家共享单车公司提供。(ps:这个项目当做练习已经做了好久了,今天才整理出来,感觉自己有点拖延症上身了哦)

数据基本结构

1、载入数据

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
import matplotlib
matplotlib.matplotlib_fname()
train=pd.read_csv('train.csv')
test=pd.read_csv('test.csv')

通过shape我们看到:共有10886个训练样本和6493个测试样本,训练集样本特征为12列。
2、特征说明
datetime:时间。年月日小时格式
season:季节。1:春天;2:夏天;3:秋天;4:冬天
holiday:是否节假日。0:否;1:是
workingday:是否工作日。0:否;1:是
weather:天气。1:晴天;2:阴天;3:小鱼或小雪;4:恶劣天气
temp:实际温度
atemp:体感温度
humidity:湿度
windspeed:风速
casual:未注册用户租车数量
registered:注册用户租车数量
count:总租车数量
3、查看数据缺失情况
用命令train.info()test.info(),未发现有数据缺失的情况。
4、检查数据异常值
用命令train.describe()来观察数据的描述性统计的信息,如下:
在这里插入图片描述
从图中我们可以发现,我们最终需要预测的租赁量(count)标准差很大,来看一下它的分布情况:

plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(10,10))
plt.hist(train['count'],bins=20)
plt.title('租赁量分布趋势')
plt.xlabel('租赁量(count)')

在这里插入图片描述
整体的分布倾斜比较严重,需要处理一下,以便于最后不会过拟合。
根据3 σ \sigma σ原则,我们将3个标准差以外的数据排除以后,然后对count做log变换,并查看变换后的分布。

train=train[np.abs(train['count']-train['count'].mean())<=3*train['count'].std()]
fig=plt.figure()
plt.subplot(1,1,1)
sns.distplot(train['count'])
plt.title('移除异常点后的租赁量分布')
plt.xlabel('租赁量(count)')
plt.savefig('1_after.png')
#对数变换
y=train['count'].values
y_log=np.log(y)
sns.distplot(y_log)
plt.title('log变换后的count分布')
plt.savefig('log.png')

1_after
在这里插入图片描述
我们看到:转换过后,图形的分布倾斜没有那么严重了,差异也变小了。
为了方便清洗数据,我们将训练集和测试集合并。combined=pd.concat([train,test],ignore_index=True)
5、与时间有关的变量处理
我们将时间进行拆分,划分到年、月、日、星期、时段。

combined['date']=combined.datetime.apply(lambda x:x.split()[0])
combined['hour']=combined.datetime.apply(lambda x:x.split()[1].split(':')[0]).astype('int')
combined['year']=combined.datetime.apply(lambda x:x.split()[0].split('-')[0]).astype('int')
combined['month']=combined.datetime.apply(lambda x:x.split()[0].split('-')[1]).astype('int')
combined['weekday']=combined.date.apply( lambda x : datetime.strptime(x,'%Y-%m-%d').isoweekday())

6、观察一些重要的特征
在这里,我们先来观察一下温度(temp)、体感温度(atemp)、湿度(humidity)、风速(windspeed)这几个特征的分布。

fig,axes=plt.subplots(2,2)
fig.set_size_inches(12,10)
sns.distplot(combined['temp'],ax=axes[0,0])
sns.distplot(combined['atemp'],ax=axes[0,1])
sns.distplot(combined['humidity'],ax=axes[1,0])
sns.distplot(combined['windspeed'],ax=axes[1,1])
axes[0,0].set(xlabel='temp',title='气温分布')
axes[0,1].s
  • 14
    点赞
  • 144
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值