机器学习 Bike Sharing Demand 实例详解-V1.2

数据集来自 Bike Sharing Demand

代码实例来自 EDA & Ensemble Model (Top 10 Percentile)

1.数据观察与处理

1.1 观察

shape
data.head(2)
data type

1.2 feature engineering

1.2.1 create new features from "DateTime"

将 datetime 分成日期、小时、工作日、月份
示例如下:

    dailyData["hour"] = dailyData.datetime.apply(lambda x : x.split()[1].split(":")[0])
    dailyData["weekday"] = dailyData.date.apply(lambda dateString : calendar.day_name[datetime.strptime(dateString,"%Y-%m-%d").weekday()]) 

strptime - date and time conversion,str to time
weekday: 0–6 意味着周一到周日
calendar.day_name: 通过 weekday 得到具体的 Monday/Tuesday/...

Difference between apply, map, applymap: These are techniques to apply function to element, column or dataframe.

Map: It iterates over each element of a series.
df[‘column1’].map(lambda x: 10+x), this will add 10 to each element of column1.
df[‘column2’].map(lambda x: ‘AV’+x), this will concatenate “AV“ at the beginning of each element of column2 (column format is string).

Apply: As the name suggests, applies a function along any axis of the DataFrame.
df[[‘column1’,’column2’]].apply(sum), it will returns the sum of all the values of column1 and column2.

ApplyMap: This helps to apply a function to each element of dataframe.
func = lambda x: x+2
df.applymap(func), it will add 2 to each element of dataframe (all columns of dataframe must be numeric type)

1.2.2.将本应为 categorical 的 features 如季节、是否为街价值、是否为工作日改为 categorical

    categoryVariableList = ["hour","weekday","month","season","weather","holiday","workingday"]
    for var in categoryVariableList:
        dailyData[var] = dailyData[var].astype("category")

1.2.3.缺失值处理

使用的工具包是 missingno,a quiet handy library to quickly visualize variables for missing values.

msno.matrix(dailyData,figsize=(12,5))

1.2.4.通过去除 outliers 进行偏度处理 skewness

画盒图

fig, axes = plt.subplots(nrows=2,ncols=2) #两行两列的图
fig.set_size_inches(12, 10)
sn.boxplot(data=dailyData,y="count",orient="v",ax=axes[0][0])
sn.boxplot(data=dailyData,y="count",x="season",orient="v",ax=axes[0][1]) 
#orient : “v” | “h”, optional, Orientation of the plot (vertical or horizontal). 

去除 outliers

dailyDataWithoutOutliers = dailyData[np.abs(dailyData["count"]-dailyData["count"].mean())<=(3*dailyData["count"].std())]

这个语句有点意思,也很有借鉴意义,如上语句只保留了在数据列 count 的平均值上下各三个标准差范围的数据。事实上,在做完该操作之后,仍应画盒图看偏度。

如上这一步的操作应该是和采用 log transform 为同一目标,可后续继续检验哪种方式更佳。

1.2.5. 相关度分析

corrMatt = dailyData[["temp","atemp","casual","registered","humidity","windspeed","count"]].corr()
mask = np.array(corrMatt)
mask[np.tril_indices_from(mask)] = False
fig,ax= plt.subplots()
fig.set_size_inches(20,10)
sn.heatmap(corrMatt, mask=mask,vmax=.8, square=True,annot=True)

有如下几个问题:

  • 为什么计算 corrMatt 时 dailyData[[XX]] 要用双层括号?
  • mask[np.tril_indices_from(mask)] = False 设对角线左下方都为 0, 为何?
  • heatmap 函数具体使用?
  • "Casual" and "Registered" are also not taken into account since they are leakage variables in nature and need to dropped during model building. Why?

画相关度图可以得到一些结论:

  • temp and humidity features has got positive and negative correlation with count respectively.Although the correlation between them are not very prominent still the count variable has got little dependency on "temp" and "humidity".
  • windspeed is not gonna be really useful numerical feature and it is visible from it correlation value with "count"
  • "atemp" is variable is not taken into since "atemp" and "temp" has got strong correlation with each other. During model building any one of the variable has to be dropped since they will exhibit multicollinearity in the data.

1.2.6. regression plot

1.2.7 Visualizing Count Vs (Month,Season,Hour,Weekday,Usertype)

柱状图

monthAggregated = pd.DataFrame(dailyData.groupby("month")["count"].mean()).reset_index()
monthSorted = monthAggregated.sort_values(by="count",ascending=False)
sn.barplot(data=monthSorted,x="month",y="count",ax=ax1,order=sortOrder)
ax1.set(xlabel='Month', ylabel='Avearage Count',title="Average Count By Month")

点图

hourAggregated = pd.DataFrame(dailyData.groupby(["hour","season"],sort=True)["count"].mean()).reset_index()
sn.pointplot(x=hourAggregated["hour"], y=hourAggregated["count"],hue=hourAggregated["season"], data=hourAggregated, join=True,ax=ax2)
ax2.set(xlabel='Hour Of The Day', ylabel='Users Count',title="Average Users Count By Hour Of The Day Across Season",label='big')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 8,543评论 0 23
  • 每天早上地铁上无处不在的吵架,无非就是你挤着我了,我踩着你了,一些琐事。一个内心不强大的人,自然内心做不到平静。不...
    请叫我刘小氓阅读 241评论 0 0
  • 体验: 今天晚上唐总问我这几天怎么没写日精进了?我解释了因为这几天都比较晚回家。后来让我想到了一句话:失败的人找理...
    梁梓晴阅读 277评论 0 0