起飞时间分箱
一天中的时间对回归模型是个挑战,同时也非常适合做分箱处理。
在本练习中,您将把航班起飞时间从 0(对应 00:00)到 24(对应 24:00)之间的数值转换为分箱后的取值。然后再对这些分箱结果进行独热编码。
本练习是课程的一部分
使用 PySpark 进行机器学习
练习说明
- 创建一个分箱器对象,分箱边界为 0、3、6、…、24,对应的时间为 0:00、03:00、06:00、…、24:00。将输入列设为
depart,输出列设为depart_bucket。 - 对
flights数据中的起飞时间进行分箱。展示depart和depart_bucket的前 5 个值。 - 创建一个独热编码器对象,将
depart_bucket设为输入列,将depart_dummy设为输出列。 - 先在分箱后的数据上拟合编码器,然后将其用于将数据转换为哑变量。展示
depart、depart_bucket和depart_dummy的前 5 个值。
交互式实操练习
通过完成这段示例代码来试试这个练习。
from pyspark.ml.feature import Bucketizer, OneHotEncoder
# Create buckets at 3 hour intervals through the day
buckets = ____(splits=[____], inputCol='____', outputCol='____')
# Bucket the departure times
bucketed = buckets.____(____)
bucketed.____('____', '____').____(____)
# Create a one-hot encoder
onehot = ____(inputCols=['____'], outputCols=['____'])
# One-hot encode the bucketed departure times
flights_onehot = ____.____(____).____(____)
flights_onehot.____('____', '____', '____').____(____)