朴素处理缺失值与分类值
随机森林回归足够稳健,通常可以忽略许多耗时又繁琐的数据准备步骤。虽然有些随机森林的实现会自动处理缺失值和分类值,但 PySpark 的实现并不会。不过其底层数学原理相同,因此我们可以采用一些朴素的数值替换方式。
对于缺失值,由于本数据严格为正数,我们将其设为 -1。随机森林会在该取值处进行划分,从而将其与同一特征中的其他取值区分对待。
对于分类值,我们可以将文本取值映射为数字。随机森林同样会通过在这些取值上划分来进行恰当处理。在这个示例中,我们会重温 Introduction to PySpark 中的 pipelines,以更简洁地编写代码。请注意,本练习开始时会显示数据框中各列的 dtypes,请在本练习结束时对比查看结果。
注意:Pipeline 和 StringIndexer 已为您导入。列表 categorical_cols 也已提供。
本练习是课程的一部分
使用 PySpark 进行特征工程
练习说明
- 使用
fillna()并配合subset参数,将WALKSCORE和BIKESCORE中的缺失值替换为 -1。 - 使用列表推导,对
categorical_cols中的每一列创建一个StringIndexer列表。 - 对管道
indexer_pipeline调用fit()并执行transform()。 - 使用
drop()删除categorical_cols,因为它们已不再需要。使用dtypes检查结果的数据类型。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Replace missing values
df = df.____(____, ____=[____, ____])
# Create list of StringIndexers using list comprehension
indexers = [____(inputCol=____, outputCol=____+"_IDX")\
.setHandleInvalid("keep") for ____ in ____]
# Create pipeline of indexers
indexer_pipeline = Pipeline(stages=indexers)
# Fit and Transform the pipeline to the original data
df_indexed = ____.____(df).____(df)
# Clean up redundant columns
df_indexed = df_indexed.____(*____)
# Inspect data transformations
print(df_indexed.dtypes)