特徵轉換
你正在和銀行經理討論信用資料集。她指出,最安全的貸款申請通常要求中等區間的信用金額。金額過低或過高都可能代表較高風險。這表示此變數與類別之間可能存在非線性關係。你想要檢驗這個假設。你將對該特徵做非線性轉換,接著使用已預先載入的 SelectKBest() 與 chi2() 指標來評估兩個特徵中哪一個較能預測類別。
資料以名為 credit 的 pandas DataFrame 提供,類別在欄位 class。你也已經將 pandas 預先載入為 pd,numpy 預先載入為 np。
本練習屬於課程
在 Python 設計機器學習工作流程
練習說明
- 定義一個函式,將數值向量轉換為每個值與該向量平均值之絕對差。
- 將此轉換套用到資料集的
credit_amount欄位,並將結果儲存到名為diff的新欄位。 - 建立一個
SelectKBest()特徵選擇器,使用chi2()指標,從credit_amount與diff這兩個欄位中選出 1 個。 - 檢視結果。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Function computing absolute difference from column mean
def abs_diff(x):
return ____(x-____)
# Apply it to the credit amount and store to new column
credit['diff'] = ____
# Create a feature selector with chi2 that picks one feature
sk = ____(chi2, ____)
# Use the selector to pick between credit_amount and diff
sk.fit(____, credit['class'])
# Inspect the results
sk.____()