特征工程——共享单车之租赁需求预估

第1关:数据探索与可视化

任务描述

本关任务:编写python代码,完成一天中不同时间段的平均租赁数量的可视化功能。

相关知识

为了完成本关任务,你需要掌握:

  • 读取数据
  • 数据探索与可视化
读取数据

数据保存在./step1/bike_train.csv中,共享单车的训练集数据总共有8709个训练样本,训练样本中有12个特征(其中count为标签)。特征说明如下:

  • datetime:时间。年月日小时格式
  • season:季节。1:春天;2:夏天;3:秋天;4:冬天
  • holiday:是否节假日。0:否;1:是
  • workingday:是否工作日。0:否;1:是
  • weather:天气。1:晴天;2:阴天;3:小雨或小雪;4:恶劣天气
  • temp:实际温度
  • atemp:体感温度
  • humidity:湿度
  • windspeed:风速
  • casual:未注册用户租车数量
  • registered:注册用户租车数量
  • count:总租车数量

想要读取数据很简单,使用pandas即可,代码如下:

 
  1. import pandas as pd
  2. train_df = pd.read_csv('./step1/bike_train.csv')
  3. # 打印数据中的前5行
  4. print(train_df.head(5))

输出如下图所示:

数据探索与可视化

一般拿到数据之后都需要做数据探索(EDA),因为我们需要看看数据到底长什么样子,有什么特性是可以挖掘出来的。假设我们需要看看数据的大概分布是什么样的。可以用pandas提供的describe()函数。输出如下:

此时我们能看到count的标准差很大,我们可以将count的数据分布可视化出来,代码如下:

 
  1. import matplotlib.pyplot as plt
  2. plt.figure(figsize=(10,10))
  3. # 画count的直方图
  4. plt.hist(train_df['count'],bins=20)
  5. plt.title('count histgram')
  6. plt.xlabel('count')

可视化结果如下:

从可视化结果可以看出,count的整体的分布倾斜比较严重,需要处理一下,不然可能过拟合会有点严重。此时我们可以考虑将count的数值在3个标准差之外的样本给扔掉,减少训练集中的噪声,并对countlog变换。代码如下:

 
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import seaborn as sns
  4. # 筛选3个标准差以内的数据
  5. train_df=train_df[np.abs(train_df['count']-train_df['count'].mean())<=3*train_df['count'].std()]
  6. # log变换
  7. y=train_df['count'].values
  8. y_log=np.log(y)
  9. # 可视化
  10. sns.distplot(y_log)
  11. plt.title('distribution of count after log')

处理后可视化结果如下:

可以从可视化结果看出,转换过后,count的分布倾斜没有那么严重了,差异也变小了。

接下来我们看看其他的一些特征对于共享单车租赁量的影响。

首先来看看季节对于租赁量的影响,代码如下:

 
  1. day_df=train_df.groupby('date').agg({'season':'mean',
  2. 'casual':'sum', 'registered':'sum',
  3. 'count':'sum','temp':'mean',
  4. 'atemp':'mean','workingday':'mean','holiday':'mean'})
  5. season_day_mean=day_df.groupby(['season'],as_index=True).agg({'casual':'mean', 'registered':'mean','count':'mean'})
  6. temp_df = day_df.groupby(['season'], as_index=True).agg({'temp':'mean', 'atemp':'mean'})
  7. season_day_mean.plot(figsize=(15,9),xticks=range(1,4))
  8. plt.title('count in different season')

可视化结果如下:

从可视化结果可以看出,临时用户和注册用户用车数量变化趋势大体一致,且两年间都在秋季左右达到了比较高的用车辆,说明美国人也都比较喜欢在这段时间外出游玩。这是符合常理的。

接下来看看天气对租赁数量的影响,代码如下:

 
  1. weather_group=train_df.groupby(['weather'])
  2. weather_count=weather_group[['count','registered','casual']].count()
  3. weather_mean=weather_group[['count','registered','casual']].mean()
  4. # 不同天气的每小时平均租赁数量
  5. weather_mean.plot.bar(stacked=True,title='count per hour in different weather')

可视化结果如下:

讲道理,天气比较好的时侯,骑共享单车的人才比较多。但上图中像4(恶劣天气)这种天气的租赁数量也比较高,这是不是有点反常呢?我们可以从数据集中找出对应的数据看看,代码如下:

 
  1. print(train_df.loc[train_df.weather==4])

数据结果如下:

数据的时间是下午6点,刚好是下班的高峰期,所以能够理解为什么这条数据对应的租赁量均值那么高了,这也是符合常理的。

那么一天中不同时间段对于租赁数量有什么样的影响呢?这个就留给你做练习吧。

编程要求

根据提示,在右侧编辑器Begin-End处补充代码,将./step1/bike_train.csv中的数据按照hour这个特征分组,然后求每一组的count的平均值。并使用matplotlib.pyplot绘制折线图,并保存到./step1/result/plot.png

测试说明

平台会对你生成的折线图与正确答案进行比对,因此请按照以下要求可视化:

  • 折线图的figsize(10, 10)
  • 折线图的标题为average count per hour

测试输入: 预期输出:你的答案与正确答案一致

import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

#********* Begin *********#
import pandas as pd

import matplotlib.pyplot as plt

train_df = pd.read_csv('./step1/bike_train.csv')

train_df['hour'] = train_df.datetime.apply(lambda x:x.split()[1].split(':')[0]).astype('int')

group_hour=train_df.groupby(train_df.hour)

hour_mean=group_hour[['count','registered','casual']].mean()

fig=plt.figure(figsize=(10,10))

plt.plot(hour_mean['count'])

plt.title('average count per hour')

plt.savefig('./step1/result/plot.png')

#********* End *********#

第2关:特征工程

任务描述

本关任务:编写python代码,完成时间细化的功能。

相关知识

为了完成本关任务,你需要掌握:

  • 相关性分析
  • 特征选择
相关性分析

在选择特征之前,我们可以看看各个特征相关性的强弱。代码如下:

 
  1. # 计算特征对的相关性
  2. corr_df=train_df.corr()
  3. corr_df1=abs(corr_df)
  4. # 画热力图
  5. fig=plt.gcf()
  6. fig.set_size_inches(30,12)
  7. sns.heatmap(data=corr_df1,square=True,annot=True,cbar=True)

相关性热力图如下(其中颜色越亮,代表线性相关性越高):

选择特征

在使用相关性这一指标来选择特征时,通常选择相关性较低,也就是颜色较暗的特征。因为如果选择相关性较高的,比如tempatemp。从图可以看出这两个特征的相关性很高,也就是说在训练模型的时候,这两个特征所对应的权重是成比例的。既然成比例,那么之选其中一个就行了。

根据热力图我们暂且可以选择时段(hour)、温度(temp)、湿度(humidity)、季节(season)、天气(weather)、风速(windspeed)、是否工作日(workingday)、是否假日(holiday 、注册用户租赁数量(registered)作为特征。

编程要求

现在可能觉得datetime这个字段有必要再细化挖掘一下,比如细化成年份、月份、日期、星期几等。

根据提示,在右侧编辑器Begin-End处补充代码,实现transform_data函数。该函数需要你将train_df中的datetime字段进行细化,细化成year(年份)、month(月份)、date(日期)、weekdat(星期几)、hour(小时)。并返回细化后的DataFrame

例如,原始数据如下:

细化后数据如下:

测试说明

平台会对你返回的DataFrame与答案进行比对,您只需实现transform_data即可。

测试输入: 预期输出:你的答案与正确答案一致。

import pandas as pd
import numpy as np
from datetime import datetime

def transform_data(train_df):
    '''
    将train_df中的datetime划分成year、month、date、weekday、hour
    :param train_df:从bike_train.csv中读取的DataFrame
    :return:无
    '''

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

    #********* End **********#

第3关:租赁需求预估

任务描述

本关任务:编写python代码,实现租赁需求预估。

相关知识

为了完成本关任务,你需要掌握:

  • 独热编码
  • sklearn机器学习算法的使用
  • 生成预测结果
独热编码

一般来说,代表类型型的特征我们需要对其进行独热编码。像数据中季节这种类别型的特征,应该使用独热编码。因为如果使用原始的1、2、3、4的话,机器学习算法可能会认为4这个季节更重要。为了防止这种偏见,我们就需要对其进行独热编码。

独热编码其实很简单,就是将待编码的特征的所有可能的取值列出来,然后再在对应的位置上填1,其他位置填0。可以看成是二进制的一种变形。

比如有4个样本的season分别为2、2、2、1。如下图所示:

那么将其独热编码后,如下图所示(第1行到第3行的season=2,所以编码后,每行的season_2这一列为1,其他列为0。而第4行的season=1,所以编码后,season_1这一列为1,其他列为0):

代码如下:

 
  1. import pandas as pd
  2. # 将train_df中的season这一列进行独热编码
  3. dummies_season = pd.get_dummies(train_df['season'], prefix='season')
  4. # 打印
  5. print(dummies_season)
sklearn机器学习算法的使用

sklearn中提供了非常多的机器学习算法的接口,例如逻辑回归、弹性网络、随机森林等等。而且使用起来非常简单,只需要fitpredict二连即可。而本关是对共享单车的租赁需求量做预测,所以这是一个回归问题。在这里给出sklearn解决回归问题的示例代码:

 
  1. from sklearn.linear_model import Ridge
  2. # 实例化Ridge回归对象
  3. ridge = Ridge(alpha=1.0)
  4. # 使用训练集的数据和标签训练
  5. ridge.fit(train_df, train_label)
  6. # 对测试集数据进行预测
  7. pred_result = ridge.predict(test_df)
生成预测结果

想要将预测结果保存到文件中,可以使用pandas来实现,示例代码如下:

 
  1. import pandas as pd
  2. # 构建DataFrame,pred_result为机器学习算法的预测结果
  3. result = pd.DataFrame({'count':pred_result})
  4. # 将DataFrame保存成result.csv,并且保存时不保留index
  5. result.to_csv('./result.csv', index=False)
编程要求

根据提示,在右侧编辑器补充代码。代码主要任务如下:

  • 读取./step3/bike_train.csv中的数据作为训练集,读取./step3/bike_test.csv中的数据作为测试集
  • 将数据处理成你想要的样子
  • 使用sklearn对训练集数据进行训练,并对测试集进行预测
  • 将预测结果保存至./step3/result.csv
测试说明

平台会计算你保存的./step3/result.csvr2 score。若r2 score高于0.95视为过关。

测试输入: 预期输出:你的预测结果的r2 score高于0.95

PS:./step3/result.csv中需要两列。一列为datetime,另一列为count。其中datetime./step3/bike_test.csv中的datetimecount为你的预测结果。如:

#********* Begin *********#  
import pandas as pd  
import numpy as np  
from datetime import datetime  
from sklearn.linear_model import Ridge
train_df = pd.read_csv('./step3/bike_train.csv')
# 舍弃掉异常count  
train_df=train_df[np.abs(train_df['count']-train_df['count'].mean())<=3*train_df['count'].std()]
# 训练集的时间数据处理
train_df['date']=train_df.datetime.apply(lambda x:x.split()[0])  
train_df['hour']=train_df.datetime.apply(lambda x:x.split()[1].split(':')[0]).astype('int')  
train_df['year']=train_df.datetime.apply(lambda x:x.split()[0].split('-')[0]).astype('int')  
train_df['month']=train_df.datetime.apply(lambda x:x.split()[0].split('-')[1]).astype('int')  
train_df['weekday']=train_df.date.apply( lambda x : datetime.strptime(x,'%Y-%m-%d').isoweekday())
# 独热编码  
train_df_back=train_df  
dummies_month = pd.get_dummies(train_df['month'], prefix='month')  
dummies_year = pd.get_dummies(train_df['year'], prefix='year')  
dummies_season = pd.get_dummies(train_df['season'], prefix='season')  
dummies_weather = pd.get_dummies(train_df['weather'], prefix='weather')
train_df_back = pd.concat([train_df, dummies_month,dummies_year, dummies_season,dummies_weather], axis = 1)
train_label = train_df_back['count']  
train_df_back = train_df_back.drop(['datetime', 'season', 'weather', 'atemp', 'date', 'month', 'count'], axis=1)
test_df = pd.read_csv('./step3/bike_test.csv')
# 测试集的时间数据处理  
test_df['date']=test_df.datetime.apply(lambda x:x.split()[0])  
test_df['hour']=test_df.datetime.apply(lambda x:x.split()[1].split(':')[0]).astype('int')  
test_df['year']=test_df.datetime.apply(lambda x:x.split()[0].split('-')[0]).astype('int')  
test_df['month']=test_df.datetime.apply(lambda x:x.split()[0].split('-')[1]).astype('int')  
test_df['weekday']=test_df.date.apply( lambda x : datetime.strptime(x,'%Y-%m-%d').isoweekday())
# 独热编码
test_df_back=test_df  
dummies_month = pd.get_dummies(test_df['month'], prefix='month')  
dummies_year = pd.get_dummies(test_df['year'], prefix='year')  
dummies_season = pd.get_dummies(test_df['season'], prefix='season')  
dummies_weather = pd.get_dummies(test_df['weather'], prefix='weather')
test_df_back = pd.concat([test_df, dummies_month,dummies_year, dummies_season,dummies_weather], axis = 1)  
test_df_back = test_df_back.drop(['datetime', 'season', 'weather', 'atemp', 'date', 'month'], axis=1)
clf = Ridge(alpha=1.0)
# 训练  
clf.fit(train_df_back, train_label)  
# 预测  
count = clf.predict(test_df_back)
# 保存结果  
result = pd.DataFrame({'datetime':test_df['datetime'], 'count':count})  
result.to_csv('./step3/result.csv', index=False)  
#********* End *********#  

  • 23
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值