介绍 共享单车需求分析是指研究影响共享单车服务使用的因素以及不同时间、地点对自行车的需求。此分析的目的是了解自行车使用的模式和趋势,并对未来需求做出预测。这篇文章将研究统计机器学习方法如何分析给定的数据。
本文将使用该数据集的一小部分,并仅关注其功能。请注意,对于如此小的数据集子集,出现不准确的可能性很高。你可以使用完整的数据集进行分析。
学习目标:
根据历史数据和其他相关因素,准确预测给定时间段和地点的自行车租赁数量。
识别并分析影响自行车租赁需求的关键因素,例如天气条件、假期和活动。
使用回归分析、时间序列分析和机器学习算法等技术开发和评估可有效预测自行车租赁需求的预测模型。
利用预测结果优化自行车库存和资源,确保共享单车公司能够满足客户需求并最大化收入。
持续监测和评估预测准确性,完善模型,提高准确性和可靠性。
Kaggle 上的数据集:https://www.kaggle.com/c/bike-sharing-demand
目录 介绍
什么是共享单车需求预测?
为什么选择自行车共享系统?
问题陈述
阅读和理解数据
可视化数据
可视化分类变量
数据准备
将数据拆分为训练集和测试集
建立线性模型
训练数据的残差分析
使用最终模型 lr5 进行预测
模型评估
结论
经常问的问题
什么是共享单车需求预测? 共享单车需求预测旨在为共享单车公司提供做出数据驱动决策和有效管理运营所需的见解和工具。
共享单车需求分析中经常考虑的因素包括天气条件、季节性、星期几、节假日和活动。有关用户的人口统计信息,例如年龄、性别和收入。它可用于了解使用模式。
共享单车需求分析采用的方法包括时间序列分析、回归分析、机器学习算法等统计模型。自行车共享公司可以利用分析结果来优化其运营、分销、定价策略和营销活动。此外,研究结果可以为城市规划者制定自行车相关基础设施和政策提供信息。
为什么选择自行车共享系统? 近年来,自行车共享系统因其许多优点而变得越来越受欢迎,其中包括:
经济实惠且可持续的交通: 自行车共享系统提供了一种经济实惠且可持续的交通方式,特别是对于短途旅行。它们是拥有私人自行车的低成本替代方案,有助于减少对私家车和共享汽车的依赖,从而对环境产生积极影响。
健康和舒适: 自行车共享系统促进身体活动和锻炼,对健康和舒适产生积极影响。定期骑自行车有助于降低患心脏病、中风和其他慢性疾病的风险。
便利性: 共享单车系统往往位于人口密集的城市地区,成为短途出行的便捷交通方式。它们交通便利,对于通勤者和游客来说都是灵活便捷的选择。
减少交通拥堵: 自行车共享系统可以为短途出行提供替代交通方式,从而有助于减少交通拥堵。这会对城镇流动性产生积极影响。
总之,自行车共享系统提供了多种好处,包括负担得起和可持续的交通、健康和舒适、便利、减少交通拥堵以及旅游业和经济发展。这些好处促进了自行车共享系统在全球许多城市的普及。
问题陈述 自行车共享需求的问题陈述是根据天气、星期几和一天中的时间等因素预测给定时间从自行车共享系统租用的自行车数量。目的是建立一个预测模型,可以准确预测自行车租赁需求,以优化自行车配置,提高共享单车系统的整体效率。
问题陈述可能涉及回答具体问题,例如:
高峰时段、工作日或周末对自行车的预期需求是多少?
天气(例如风、温度、降水)如何影响自行车租赁需求?
是否存在对自行车需求较高或较低的特定地点或路线?
我们如何优化共享单车系统以满足不断变化的需求,并最大限度地降低运营成本?
共享单车系统能否扩展或改进,以更好地满足用户需求并促进可持续交通?
共享单车需求分析的问题陈述通常涉及预测自行车租赁需求和优化自行车分配,以提高共享单车系统的效率和可持续性。
公司管理层希望:
使用可用的自变量创建共享单车的需求模型。
使用所建立的模型了解市场的需求动态。
阅读和理解数据 要构建共享单车需求预测模型,首先要阅读和理解数据。此过程涉及的关键步骤是加载、探索、清理、预处理和可视化数据。通过遵循这些步骤,数据分析师可以更深入地了解数据,并在构建共享单车需求预测模型之前确定需要解决的任何问题。这有助于确保模型准确可靠,这对于优化自行车共享运营至关重要。
import pandas as pd bikeshare_df = pd.read_csv("day.csv" ) print(bikeshare_df.head())
bike_sharing.info()
bike_sharing.describe()
可视化数据 数据可视化是共享单车需求预测过程中的重要一步。它可以帮助识别原始数据中可能无法立即显现的模式和趋势。
import matplotlib.pyplot as pltimport seaborn as sns
#Plotting pairplot of all the numeric variables sns.pairplot(bike_sharing[["temp" ,"atemp" ,"hum" ,"windspeed" ,"casual" ,"registered" ,"cnt" ]]) plt.show()
#Plotting box plot of continuous variables plt.figure(figsize=(20 , 12 )) plt.subplot(2 ,3 ,1 ) plt.boxplot(bike_sharing["temp" ]) plt.subplot(2 ,3 ,2 ) plt.boxplot(bike_sharing["atemp" ]) plt.subplot(2 ,3 ,3 ) plt.boxplot(bike_sharing["hum" ]) plt.subplot(2 ,3 ,4 ) plt.boxplot(bike_sharing["windspeed" ]) plt.subplot(2 ,3 ,5 ) plt.boxplot(bike_sharing["casual" ]) plt.subplot(2 ,3 ,6 ) plt.boxplot(bike_sharing["registered" ]) plt.show()
可视化分类变量 #Plotting box plot of categorical variables plt.figure(figsize=(20 , 12 )) plt.subplot(3 ,3 ,1 ) sns.boxplot(x = 'season' , y = 'cnt' , data = bike_sharing) plt.subplot(3
,3 ,2 ) sns.boxplot(x = 'yr' , y = 'cnt' , data = bike_sharing) plt.subplot(3 ,3 ,3 ) sns.boxplot(x = 'mnth' , y = 'cnt' , data = bike_sharing) plt.subplot(3 ,3 ,4 ) sns.boxplot(x = 'holiday' , y = 'cnt' , data = bike_sharing) plt.subplot(3 ,3 ,5 ) sns.boxplot(x = 'weekday' , y = 'cnt' , data = bike_sharing) plt.subplot(3 ,3 ,6 ) sns.boxplot(x = 'workingday' , y = 'cnt' , data = bike_sharing) plt.subplot(3 ,3 ,7 ) sns.boxplot(x = 'weathersit' , y = 'cnt' , data = bike_sharing) plt.show()
数据准备 数据准备是共享单车需求预测的关键步骤,因为它涉及清理、转换和组织数据以使其适合分析。通过以这种方式准备数据,分析师可以确保数据适合用来分析,并且数据中的任何偏差或错误都能得到解决。这可以带来更准确、更可靠的预测模型,帮助共享单车公司优化运营并更好地满足客户需求。
删除不必要的列:instant、dteday、casual和registered
instant– 行的序列号
dteday – 不需要,因为年和月的列已经存在
casual – 该变量无法预测。
registered – 该变量无法预测。
bike_sharing.drop(columns=["instant" ,"dteday" ,"casual" ,"registered" ],axis=1 ,inplace =True ) bike_sharing.head()
虚拟变量
season_type = pd.get_dummies(bike_sharing['season' ], drop_first = True ) season_type.rename(columns={2 :"season_summer" , 3 :"season_fall" , 4 :"season_winter" },inplace=True ) season_type.head()
weather_type = pd.get_dummies(bike_sharing['weathersit' ], drop_first = True ) weather_type.rename(columns={2 :"weather_mist_cloud" , 3 :"weather_light_snow_rain" },inplace=True ) weather_type.head()
#Concatenating new dummy variables to the main dataframe bike_sharing = pd.concat([bike_sharing, season_type, weather_type], axis = 1 )#Dropping columns season & weathersit since we have already created dummies for them bike_sharing.drop(columns=["season" , "weathersit" ],axis=1 ,inplace =True )#Analysing dataframe after dropping columns bike_sharing.info()
为分类变量月份创建派生变量
#Creating year_quarter derived columns from month columns. #Note that last quarter has not been created since we need only 3 columns to define the four quarters. bike_sharing["Quarter_JanFebMar" ] = bike_sharing["mnth" ].apply(lambda x: 1 if x<=3 else
0 ) bike_sharing["Quarter_AprMayJun" ] = bike_sharing["mnth" ].apply(lambda x: 1 if 4 <=x<=6 else 0 ) bike_sharing["Quarter_JulAugSep" ] = bike_sharing["mnth" ].apply(lambda x: 1 if 7 <=x<=9 else 0 )#Dropping column mnth since we have already created dummies. bike_sharing.drop(columns=["mnth" ],axis=1 ,inplace =True ) bike_sharing["weekend" ] = bike_sharing["weekday" ].apply(lambda x: 0 if 1 <=x<=5 else 1 ) bike_sharing.drop(columns=["weekday" ],axis=1 ,inplace =True ) bike_sharing.drop(columns=["workingday" ],axis=1 ,inplace =True ) bike_sharing.head()
#Analysing dataframe after dropping columns weekday & workingday bike_sharing.info()
#Plotting correlation heatmap to analyze the linearity between the variables in the dataframe plt.figure(figsize = (16 , 10 )) sns.heatmap(bike_sharing.corr(), annot = True , cmap="Greens" ) plt.show()
#Dropping column temp since it is very highly collinear with the column atemp. #Further,the column atemp is more appropriate for modelling compared to column temp from human perspective. bike_sharing.drop(columns=["temp" ],axis=1 ,inplace =True ) bike_sharing.head()
将数据拆分为训练集和测试集 将数据拆分为训练集和测试集是共享单车需求预测的关键步骤。它使分析师能够评估其预测模型对未见数据的性能。一般方法是使用历史数据来训练模型,然后在单独的保留数据集上测试模型的性能。
#Importing library from sklearn.model_selection import train_test_split# We specify this so that the train and test data set always have the same rows, respectively np.random.seed(0 ) bike_sharing_train, bike_sharing_test = train_test_split(bike_sharing, train_size = 0.7 , test_size = 0.3 , random_state = 100 )
分割后使用 MinMax 缩放函数重新缩放训练数据帧,以实现所有特征的最佳 beta 系数。
#importing library from sklearn.preprocessing import MinMaxScaler#assigning variable to scaler scaler = MinMaxScaler()# Applying scaler to all the columns except the derived and 'dummy' variables that are already in 0 & 1. numeric_var = ['atemp' ,'hum' ,'windspeed' ,'cnt' ] bike_sharing_train[numeric_var] = scaler.fit_transform(bike_sharing_train[numeric_var])# Analysing the train dataframe after scaling bike_sharing_train.head()
通过将数据分为训练集和测试集,分析师可以评估其预测模型在未见过的数据上的性能,并确保模型稳健可靠。这可以帮助共享单车公司优化运营并更好地满足客户需求。
y_train = bike_sharing_train.pop('cnt' ) X_train = bike_sharing_trainprint (y_train.head())print (X_train.head())
建立线性模型 构建共享单车需求预测的线性模型涉及创建一个模型,该模型使用线性回归根据一组输入变量来预测自行车租赁需求。
使用训练集训练线性回归模型,输入变量用于预测目标变量(自行车租赁需求)。该模型经过优化,可以最大限度地减少训练集中的预测需求和实际需求之间的误差。
使用 SciKit Learn 中的 LinearRegression 函数和递归特征消除 (RFE):
# Importing RFE and LinearRegression from sklearn.feature_selection import RFEfrom sklearn.linear_model import LinearRegression# Running RFE with the output number of the variable equal to 12 lm = LinearRegression() lm.fit(X_train, y_train) rfe = RFE(lm, 12 ) # running RFE rfe = rfe.fit(X_train, y_train) list(zip(X_train.columns,rfe.support_,rfe.ranking_))
通过构建共享单车需求预测的线性模型,分析师可以开发一个简单而有效的预测系统,以优化共享单车运营并提高客户满意度。
然而,值得注意的是,线性模型在捕获数据中更复杂的模式和关系方面可能存在局限性,因此其他建模技术(例如决策树或神经网络)可以进行更准确的预测。
# Creating X_test dataframe with RFE selected variables X_train_rfe = X_train[columns_rfe] X_train_rfe
训练数据的残差分析 残差分析是评估共享单车需求预测线性模型性能的重要步骤。残差是预测需求与实际需求之间的差异,分析这些残差可以帮助识别模型预测中的任何模式或偏差。
#using the final model lr5 on train data to predict y_train_cnt values y_train_cnt = lr5.predict(X_train_lr5)# Plotting the histogram of the error terms fig = plt.figure() sns.distplot((y_train - y_train_cnt), bins = 20 ) fig.suptitle('Error Terms' , fontsize = 20 ) plt.xlabel('Errors' , fontsize = 18 )
plt.scatter(y_train,(y_train - y_train_cnt)) plt.show()
使用最终模型 lr5 进行预测 要使用自行车共享需求预测 (lr5) 的最终线性模型进行预测,你需要提供输入变量的值,并使用该模型生成目标变量(自行车租赁需求)的预测。
#Applying the scaling on the test sets numeric_vars = ['atemp' ,'hum' ,'windspeed' ,'cnt' ] bike_sharing_test[numeric_vars] = scaler.transform(bike_sharing_test[numeric_vars]) bike_sharing_test.describe()
分为X_test和y_test
y_test = bike_sharing_test.pop('cnt' ) X_test = bike_sharing_test# Adding constant variable to test dataframe X_test_lr5 = sm.add_constant(X_test)# Updating X_test_lr5 dataframe by dropping the variables as analyzed from the above models X_test_lr5 =X_test_lr5.drop(["atemp" , "hum" , "season_fall" , "Quarter_AprMayJun" , "weekend" ,"Quarter_JanFebMar" ], axis = 1 )# Making predictions using the fifth model y_pred = lr5.predict(X_test_lr5)
模型评估 模型评估是评估共享单车需求预测模型性能的关键步骤。使用各种指标来评估模型的性能,包括平均绝对误差 (MAE)、均方根误差 (RMSE) 和决定系数 (R 平方)。
# Plotting y_test and y_pred to understand the spread fig = plt.figure() plt.scatter(y_test, y_pred) fig.suptitle('y_test vs y_pred' , fontsize = 20 ) plt.xlabel('y_test' , fontsize = 18 ) plt.ylabel('y_pred' , fontsize = 16 )
你应该使用 MAE、RMSE 和 R 平方等指标来评估模型的性能。MAE 和 RMSE 测量预测值和实际值之间的平均误差大小。R 平方衡量目标变量中由输入变量解释的方差比例。
#importing library and checking mean squared error from sklearn.metrics import mean_squared_error mse = mean_squared_error(y_test, y_pred) print('Mean_Squared_Error :' ,mse)#importing library and checking R2 from sklearn.metrics import r2_score r2_score(y_test, y_pred)
结论 本研究旨在改善 Capital Bikeshare 的自行车共享活动,并支持城市交通系统的重塑。对公开数据进行的全面探索性数据分析,帮助我们了解和分析共享单车网络的基本模式和特征,并利用这些数据来实现数据驱动的结果。
我们对 2011 年至 2012 年两年间共享单车受欢迎程度的增长情况以及季节和日期因素对骑行模式的影响进行了分析。研究季节和天气参数的影响是为了了解华盛顿特区的客流量模式。对行程数据的分析有助于了解车站所在地区的特征。
牢记这些推论,我们可以提出以下建议:
大部分单车租金用于日常通勤到公司和大学。因此,CaBi 应该在这些地标附近开设更多车站,以覆盖其主要客户。
规划更多的共享单车站点必须考虑租赁高峰时段,即上午 7 点至 9 点和下午 5 点至 6 点。
报价不应是固定价格。相反,应该根据季节变化来促进秋冬季节的自行车使用。
有关最常用路线的数据可以帮助修建专门用于自行车的道路/车道。
由于夜间自行车使用率较低,所以最好在夜间进行自行车保养。夜间从街上移走一些自行车不会给顾客带来麻烦。
通过向注册客户提供折扣和优惠券,将周末的注册客户转变为休闲客户。
经常问的问题 Q1. 什么是共享单车需求预测?
A. 共享单车需求预测是指预测特定时间段内共享单车的租赁数量,辅助资源配置和系统优化的过程。
Q2. 共享单车的趋势是什么?
答:共享单车的趋势在全球范围内稳步增长,越来越多的城市实施自行车共享计划,以促进可持续交通并减少交通拥堵。
Q3. 共享单车能赚钱吗?
答:共享单车系统的盈利能力可能会因用户需求、运营成本、定价策略以及与当地企业的合作伙伴关系等因素而有所不同。仔细的规划和有效的管理对于长期盈利至关重要。
Q4. 共享单车为何如此受欢迎?
答:共享单车之所以流行有几个原因。它提供了便捷灵活的交通方式,促进身体活动和健康发展,减少碳排放,缓解停车拥堵,为城市短途出行提供了一种经济实惠的替代方案。
✄----------------------------------------------- 看到这里,说明你喜欢这篇文章,请点击「 在看 」或顺手「 转发 」「 点赞 」。
欢迎微信搜索「 panchuangxx 」,添加小编 磐小小仙 微信,每日朋友圈更新一篇高质量推文(无广告),为您提供更多精彩内容。