开始使用免费开始使用

删除观测数较少的列

在进行了大量特征工程之后,退一步审视您已经构建的内容是个好主意。如果您对分类特征使用了自动化方法(例如 explode 或 OneHot Encoding),可能会发现现在多了数百个二进制特征。特征选择本身可以单开一门课程,但您可以先做一些快速处理,降低数据集的维度。

在本练习中,我们将删除观测数少于 30 的列。30 通常被视为统计显著性的最小观测数。少于这个阈值,其关系很可能只是碰巧出现,从而导致过拟合!

注意:数据已在数据框 df 中可用。

本练习是课程的一部分

使用 PySpark 进行特征工程

查看课程

练习说明

  • 使用提供的 for 循环遍历二进制列列表,利用 agg 函数计算该列取值的 sum。使用 collect() 立即执行计算,并将结果保存到 obs_count
  • obs_countobs_threshold 比较:当 obs_count 小于或等于 obs_threshold 时,if 语句应为真。
  • 使用 drop() 删除已追加到 cols_to_remove 列表中的列。回顾一下,* 可以将列表解包。
  • 分别打印 PySpark 数据框的起始与结束形状:使用 count() 获取记录数,使用 len() 作用于 df.columnsnew_df.columns 获取列数。

交互式实操练习

通过完成这段示例代码来试试这个练习。

obs_threshold = 30
cols_to_remove = list()
# Inspect first 10 binary columns in list
for col in binary_cols[0:10]:
  # Count the number of 1 values in the binary column
  obs_count = df.____({col: ____}).____()[0][0]
  # If less than our observation threshold, remove
  if ____ ____ ____:
    cols_to_remove.append(col)
    
# Drop columns and print starting and ending dataframe shapes
new_df = df.____(*____)

print('Rows: ' + str(df.____()) + ' Columns: ' + str(____(df.____)))
print('Rows: ' + str(new_df.____()) + ' Columns: ' + str(____(new_df.____)))
编辑并运行代码