篩除高度相關的特徵
你要在 ANSUR 的數值型資料集中,自動移除高度相關的特徵。你會先計算相關係數矩陣,並篩掉相關係數大於 0.95 或小於 -0.95 的欄位。
由於每個相關係數在矩陣中會出現兩次(A 對 B 的相關等於 B 對 A 的相關),你需要忽略相關矩陣的一半,這樣只會移除其中一個高度相關的特徵。請用遮罩(mask)的小技巧來達成這個目的。
本練習屬於課程
Python 的降維
練習說明
- 計算
ansur_df的相關矩陣,並取其絕對值。 - 建立一個在右上三角為
True的布林遮罩,並把它套用到相關矩陣。 - 將相關係數門檻設為
0.95。 - 從 DataFrame 中刪除
to_drop中列出的所有欄位。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Calculate the correlation matrix and take the absolute value
corr_df = ansur_df.____().____()
# Create a True/False mask and apply it
mask = np.____(np.____(corr_df, dtype=____))
tri_df = corr_df.____(mask)
# List column names of highly correlated features (r > 0.95)
to_drop = [c for c in tri_df.columns if any(tri_df[c] > ____)]
# Drop the features in the to_drop list
reduced_df = ansur_df.____(____, axis=1)
print(f"The reduced_df DataFrame has {reduced_df.shape[1]} columns.")