移除觀測次數偏低的欄位
做了大量特徵工程之後,建議你先停一下,回頭檢視自己建立了什麼。如果你對類別型特徵用了自動化技巧,例如 exploding 或 OneHot Encoding,你可能會得到上百個新的二元特徵。雖然特徵選擇本身可以開一整門課,不過你仍可先用一些快速步驟來降低資料集的維度。
在這個練習中,我們要移除觀測次數少於 30 的欄位。30 是統計上常見的觀測最小值門檻。再少就可能因為純粹巧合而導致關係被過度擬合!
注意:資料已存在名為 df 的 dataframe 中。
本練習屬於課程
使用 PySpark 進行特徵工程
練習說明
- 使用已提供、可遍歷二元欄位清單的
for迴圈,對每個欄位用agg計算該欄位值的sum。使用collect()立刻執行計算,並將結果存到obs_count。 - 將
obs_count與obs_threshold比較;當obs_count小於或等於obs_threshold時,if判斷式應為真。 - 使用
drop()移除已加入cols_to_remove清單中的欄位。記得*可以將清單解包。 - 以
count()取得紀錄數,並對df.columns或new_df.columns使用len()取得欄位數,列印 PySpark dataframe 的起始與結束維度。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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.____)))