中国小黄车的惨败,激起了我对共享单车的兴趣。国外的这一行业要早于中国,这个数据是来自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')
我们看到:转换过后,图形的分布倾斜没有那么严重了,差异也变小了。
为了方便清洗数据,我们将训练集和测试集合并。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