?完整代碼下載:https://download.csdn.net/download/andrew_extra/88612623
1. 項目背景
共享單車系統(tǒng)在大城市越來越流行,通過提供價格合理的自行車租賃,讓人們可以享受在城市里騎自行車的樂趣,而無需為自己購買自行車。本項目利用 Nice Ride MN 在雙子城(明尼蘇達州明尼阿波利斯市/圣保羅市)提供的歷史數(shù)據(jù)。我們將通過查看不同站點的自行車需求、每個站點的自行車流量、季節(jié)性和天氣對騎行模式的影響,以及會員和非會員之間騎行模式的差異,來探索共享單車騎行數(shù)據(jù)。
2. 功能組成
基于數(shù)據(jù)挖掘的共享單車騎行數(shù)據(jù)分析與預測系統(tǒng)的主要功能包括:
3. 數(shù)據(jù)讀取與預處理
stations = pd.read_csv('data/Nice_Ride_2017_Station_Locations.csv')
trips = pd.read_csv('data/Nice_ride_trip_history_2017_season.csv')
Stations 和 trips 基本信息:
stations.info()
trips.info()
?stations 和 trips 數(shù)據(jù)集看起來非常干凈——沒有丟失值,緯度、經(jīng)度和加載的碼頭數(shù)量與預期一致。
????????轉換時間字段的數(shù)據(jù)格式:
# Convert start and end times to datetime
for col in ['End date', 'Start date']:
trips[col] = pd.to_datetime(trips[col],
format='%m/%d/%Y %H:%M')
4. 數(shù)據(jù)探索式可視化分析
4.1 車站位置 Station Locations 的分析
# On hover, show Station name
tooltips = [("Station", stations['Name'])]
# Plot the stations
p, _ = MapPoints(stations.Latitude, stations.Longitude,
title="Nice Ride Station Locations",
tooltips=tooltips,
height=fig_height, width=fig_width)
show(p)
????????可以看出,大多數(shù)車站都分散在明尼阿波利斯周圍,但圣保羅市中心也有一個集群,以及沿大學大道和格蘭德大道的幾個車站,它們連接明尼阿波利斯和圣保羅。
4.2?每個車站的自行車??空緮?shù)量
# Plot histogram of # docks at each station
plt.figure(figsize=(16, 5))
plt.hist(stations['Total docks'],)
plt.ylabel('Number of Stations')
plt.xlabel('Number of Docks')
plt.title('Number of Docks Distribution')
plt.show()
?????????可以看出,每個車站大部分???5輛共享單車。
# 顯示車站名稱和??孔孕熊嚁?shù)量
tooltips = [("Station", stations['Name']),
("Docks", stations['Total docks'])]
# Plot the stations
p, _ = MapPoints(stations.Latitude, stations.Longitude,
tooltips=tooltips, color=stations['Total docks'],
size=4*np.sqrt(stations['Total docks']/np.pi),
title="Number of Docks at each Station",
height=fig_height, width=fig_width)
show(p)
?4.3?車站需求分析 Station Demand
demand_df = pd.DataFrame({'Outbound trips': trips.groupby('Start station').size(),
'Inbound trips': trips.groupby('End station').size()
})
demand_df['Name'] = demand_df.index
sdf = stations.merge(demand_df, on='Name')
plt.figure(figsize=(16, 5))
plt.hist(sdf['Outbound trips'], bins=20)
plt.ylabel('Number of Stations')
plt.xlabel('Number of outbound rentals')
plt.title('Outbound trip distribution')
plt.show()
# Plot num trips started from each station
plt.figure(figsize=(16, 5))
plt.hist(sdf['Inbound trips'], bins=20)
plt.ylabel('Number of Stations')
plt.xlabel('Number of inbound rentals')
plt.title('Inbound trip distribution')
plt.show()
? ? ? ? ?可以看出,Nice Ride MN 必須將自行車從有多余自行車的車站重新分配到?jīng)]有足夠自行車的車站。在該站結束的騎乘次數(shù)比在該站開始的騎乘次數(shù)多的車站最終會有額外的自行車,而 Nice Ride MN 將不得不將這些額外的自行車重新分配給更空的車站!分析哪些車站的終點車次比起點車次多。
????????大多數(shù)車站的終點車次和起點車次差不多。然而,肯定有幾個站是不平衡的!也就是說,有些車站的入站乘車次數(shù)多于出站乘車次數(shù),反之亦然。
????????我們可以把這些分布繪制在地圖上,看看哪些是不平衡的站。我們將使用Bokeh在三個單獨的選項卡中繪制出出境旅行次數(shù)、入境旅行次數(shù)和需求差異。圓圈的顏色和區(qū)域表示相應選項卡中的vaue(出境旅行次數(shù)、入境旅行次數(shù)或差異)。對于“差異”,圓圈的大小表示“絕對”差異(因此我們可以看到哪些站點最不平衡,顏色告訴我們它們在哪個方向不平衡)。單擊繪圖頂部的每個選項卡,查看出站行程、入站行程的數(shù)量或兩者之間的差異。
????????有些車站結束行程的人數(shù)遠遠多于開始行程的人數(shù)(例如,位于圣諾克斯湖大道Lake St & Knox Ave、Bde Maka Ska東北角的車站,或Minnehaha Park車站)。還有一些車站,開始旅行的人比結束旅行的人多得多(例如,明尼蘇達大學校園的科夫曼聯(lián)合車站和威利大廳車站)。但大多數(shù)車站的入站和出站數(shù)量差不多。
????????還可以看出,更多的車從明尼阿波利斯市中心或密歇根大學校園出發(fā),離開市中心。請注意,明尼阿波利斯市中心聚集了許多大型藍色圓圈(出站次數(shù)較多的車站),但大多數(shù)大型紅色圓圈(出站次數(shù)較多的車站)遠離市中心,往往是“目的地”和公園(如明尼哈公園、Bde Maka Ska、洛根公園和北密西西比區(qū)域公園))
4.4?需求差異性分析
?????????理想情況下,“Nice Ride”希望在進站和出站車次差異較大的車站有更多的碼頭。這是因為,如果在一個特定的車站開始的騎乘次數(shù)多于在該車站結束的騎乘次數(shù),那么隨著時間的推移,該車站的自行車數(shù)量將會減少。所以,車站需要有足夠的碼頭來容納足夠的自行車,這樣車站在一天結束時就不會空無一人了!另一方面,如果在一個車站結束的車程比在那里開始的車程多,那么該車站的所有碼頭都會擠滿,人們將無法在那里結束他們的車程!因此,這些車站必須有足夠的碼頭來吸收一天中的交通量。
sdf['abs_diff'] = sdf['demand_diff'].abs()
sdf['Docks'] = sdf['Total docks']/sdf['Total docks'].sum()
sdf['DemandDiff'] = sdf['abs_diff']/sdf['abs_diff'].sum()
sdf['demand_dir'] = sdf['Name']
sdf.loc[sdf['demand_diff']<0, 'demand_dir'] = 'More Outgoing'
sdf.loc[sdf['demand_diff']>0, 'demand_dir'] = 'More Incoming'
sdf.loc[sdf['demand_diff']==0, 'demand_dir'] = 'Balanced'
tidied = (
sdf[['Name', 'Docks', 'DemandDiff']]
.set_index('Name')
.stack()
.reset_index()
.rename(columns={'level_1': 'Distribution', 0: 'Proportion'})
)
plt.figure(figsize=(4.5, 35))
station_list = sdf.sort_values('DemandDiff', ascending=False)['Name'].tolist()
sns.barplot(y='Name', x='Proportion', hue='Distribution',
data=tidied, order=station_list)
plt.title('Proportion Docks vs Demand Difference')
locs, labels = plt.yticks()
plt.yticks(locs, tuple([s[:15] for s in station_list]))
plt.show()
????????每個車站的碼頭數(shù)量與總體需求差異之間并沒有很好的匹配。需求的差異可能會隨著時間的推移而變化。例如,一些車站可能在早上有更多的出站行程,在晚上有更多的入站行程,反之亦然。
4.5?需求隨時間變化的差異
????????駛入和駛出車站之間的平衡并不是一成不變的——它會隨著時間而變化!在早上8點左右,有更多的人在車站結束他們的租車,可能是通勤上班的人。但在一天結束時,大約下午5點,人們通常會從該車站開始租車,可能是為了上下班回家。?
4.6 需求的累積差異分析
# 計算需求的累積差異
cdiff = trips_hp['Difference'].apply(np.cumsum, axis=1)
????????從累積的需求差異來看,很明顯早上有很多自行車被從這個車站帶走,晚上又被帶回來。所以,如果尼斯騎行不把自行車重新分配給這個車站,在上午9點到下午4點之間,這里的自行車會比晚上少很多。
4.7 單車從??奎c的流轉情況分析
????????乘站的位置、每個車站的碼頭數(shù)量、每個車站的需求以及需求隨時間的變化。然而,自行車是如何從每個車站流向另一個車站的?也就是說,旅行的分布是什么樣的?每個車站最常見和最不常見的目的地是什么?
# 計算從每個車站到另一個車站的行程數(shù)
flow = (
trips.groupby(['Start station', 'End station'])['Start date']
.count().to_frame().reset_index()
.rename(columns={"Start date": "Trips"})
.pivot(index='Start station', columns='End station')
.fillna(value=0)
)
# Plot trips to and from each station
sns.set_style("dark")
plt.figure(figsize=(10, 8))
plt.imshow(np.log10(flow.values+0.1),
aspect='auto',
interpolation="nearest")
plt.set_cmap('plasma')
cbar = plt.colorbar(ticks=[-1,0,1,2,3])
cbar.set_label('Number of trips')
cbar.ax.set_yticklabels(['0','1','10','100','1000'])
plt.ylabel('Station Number FROM')
plt.xlabel('Station Number TO')
plt.title('Number of trips to and from each station')
plt.show()
# 最終??吭诔霭l(fā)時候的同一車站的數(shù)量
sns.set()
plt.figure()
plt.bar([0, 1],
[np.trace(flow.values),
flow.values.sum()-np.trace(flow.values)],
tick_label=['Same as start', 'Other'])
plt.xlabel('End station')
plt.ylabel('Number of trips')
plt.title('Number of trips which end\n'+
'at same station they started from')
plt.show()
????????可以看出,大多數(shù)旅行實際上不會回到他們出發(fā)的車站。
4.8 騎行時長分析
# 超過24小時的,可能為異常情況
Ntd = np.count_nonzero(trips['Total duration (Seconds)']>(24*60*60))
print("Number of trips longer than 24 hours: %d ( %0.2g %% )"
% (Ntd, 100*Ntd/float(len(trips))))
# 騎行時長不超過1小時的
Ntd = np.count_nonzero(trips['Total duration (Seconds)']<(24*60))
print("Number of trips shorter than 1 hour: %d ( %0.2g %% )"
% (Ntd, 100*Ntd/float(len(trips))))
# Plot histogram of ride durations
plt.figure()
sns.distplot(trips.loc[trips['Total duration (Seconds)']<(4*60*60),
'Total duration (Seconds)']/3600)
plt.xlabel('Ride duration (hrs)')
plt.ylabel('Number of Trips')
plt.title('Ride durations')
plt.show()
4.9?每個月騎行時長分布情況
????????最受歡迎的單車騎行月份是7月,盡管在非黃金月份仍有很多單車騎行,但4月和10月的數(shù)量幾乎是7月的一半。
?4.9?一年中每天騎行分布情況
trips.groupby(trips['Start date'].dt.dayofyear)['Start date'].count().plot()
plt.xlabel('Day of the year')
plt.ylabel('Number of rentals')
plt.title('Number of rentals by day of the year in 2017')
holidays = [("Mother's day", 134),
("Memorial day", 149),
("4th of July", 185),
("Labor day", 247),
("Oct 27", 300)]
for name, day in holidays:
plt.plot([day,day], [0,6000],
'k--', linewidth=0.2)
plt.text(day, 6000, name, fontsize=8,
rotation=90, ha='right', va='top')
plt.show()
?4.10 每周騎行分布情況
plt.figure()
sns.countplot(trips['Start date'].dt.weekday)
plt.xlabel('Day')
plt.ylabel('Number of Trips')
plt.title('Number of rentals by day of the week in 2017')
plt.xticks(np.arange(7),
['M', 'T', 'W', 'Th', 'F', 'Sa', 'Su'])
plt.show()
?4.11 天氣因素影響騎行情況
weather = pd.read_csv('data/WeatherDailyMinneapolis2017.csv')
weather['DATE'] = pd.to_datetime(weather['DATE'],
format='%Y-%m-%d')
# Plot daily min + max temperature
plt.plot(weather.DATE.dt.dayofyear,
weather.TMAX, 'C2')
plt.plot(weather.DATE.dt.dayofyear,
weather.TMIN, 'C1')
plt.legend(['Max', 'Min'])
plt.xlabel('Day of year')
plt.ylabel('Temperature (degrees F)')
plt.title('Daily temperatures in Minneapolis for 2017')
plt.show()
????????氣溫與單車騎行數(shù)量分布情況:
????????降水量與騎行次數(shù)分布情況:
?????????降水量與騎行時長的分布情況:
????????降水量和騎行持續(xù)時間之間可能存在一定的負相關。這在比較有雨和無雨的騎行時間時更為明顯。
4.12 會員用戶分析
????????會員與非會員用戶每日騎行次數(shù)差異性分析:?
????????會員與非會員用戶每小時騎行次數(shù)差異性分析:?
????????會員與非會員用戶騎行時長差異性分析:
?5.?基于天氣數(shù)據(jù)和歷史騎行數(shù)據(jù)預測每日騎行數(shù)據(jù)
????????建立一個模型來預測每天的乘車次數(shù),包括季節(jié)、天氣和其他因素,利用二階多項式來模擬季節(jié)效應:
?????????然而,季節(jié)將與溫度高度相關!這意味著,如果我們試著將兩者都放在同一個模型中,溫度對乘坐次數(shù)的一些影響可能歸因于季節(jié)。因此,我們來擬合一個模型,它包含了我們所關心的一切除了季節(jié)的預測因子,然后將該模型的殘差視為季節(jié)的函數(shù)?;旧?,我們將要做的是“消除”天氣對乘車次數(shù)的影響,然后研究剩余信息如何隨季節(jié)變化。
????????首先,讓我們擬合一個普通的最小二乘回歸模型,從一周中的某一天開始預測每天的乘車次數(shù)、每日最高溫度和每日降水量。
5.1?OLS 回歸分析
df = pd.DataFrame()
df['Trips'] = weather.trips
df['Date'] = weather.DATE
df['Day'] = weather.DATE.dt.dayofweek
df['Temp'] = weather.TMAX
df['Precip'] = weather.PRCP + 0.001
# Only fit model on days with trips
df = df.loc[~np.isnan(df.Trips), :]
df.reset_index(inplace=True, drop=True)
# Fit the linear regression model
olsfit = smf.ols('Trips ~ Temp + log(Precip) + C(Day)', data=df).fit()
# Show a summary of the fit
print(olsfit.summary())
?????????我們的模型確實捕捉到了天氣的影響。在上面的匯總表中,coef列包含最左側列中變量的系數(shù)。溫度系數(shù)為≈39.9,這意味著溫度每升高10度,就可以獲得良好的乘坐體驗≈每天還有400次騎乘!但不可能再多坐400次。最右邊的兩列顯示了95%的置信區(qū)間,這表明該模型95%確定溫度系數(shù)在33.6和46.2之間。因此,該模型非常確定每天的乘車次數(shù)會隨著溫度的升高而增加(因為95%的置信區(qū)間完全高于0),但這種關系到底有多強還不確定。
????????同樣,降水量系數(shù)顯著為負值,這意味著降水量越多,每天的乘車次數(shù)就越少。這是有道理的,符合我們之前的天氣分析。
5.2 預測每天騎行次數(shù)
# Predict num rides and compute residual
y_pred = olsfit.predict(df)
resid = df.Trips-y_pred
# Plot Predicted vs actual
plt.figure(figsize=(12, 6))
sns.set_style("darkgrid")
plt.plot(df.Date.dt.dayofyear, y_pred)
plt.plot(df.Date.dt.dayofyear, df.Trips)
plt.legend(['Predicted', 'Actual'])
plt.xlabel('Day of the Year')
plt.ylabel('Number Daily Rentals')
plt.title('Actual vs Predicted Rides Per Day')
plt.show()
6. 總結
????????本項目利用 Nice Ride MN 在雙子城(明尼蘇達州明尼阿波利斯市/圣保羅市)提供的歷史數(shù)據(jù)。我們將通過查看不同站點的自行車需求、每個站點的自行車流量、季節(jié)性和天氣對騎行模式的影響,以及會員和非會員之間騎行模式的差異,來探索共享單車騎行數(shù)據(jù)。
??完整代碼下載:https://download.csdn.net/download/andrew_extra/88612623
歡迎大家點贊、收藏、關注、評論啦 ,由于篇幅有限,只展示了部分核心代碼。
精彩專欄推薦訂閱:文章來源:http://www.zghlxwxcb.cn/news/detail-513000.html
1. Python 畢設精品實戰(zhàn)案例
2. 自然語言處理 NLP 精品實戰(zhàn)案例
3. 計算機視覺 CV 精品實戰(zhàn)案例文章來源地址http://www.zghlxwxcb.cn/news/detail-513000.html
到了這里,關于基于數(shù)據(jù)挖掘的共享單車騎行數(shù)據(jù)分析與預測的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!