開始使用免費開始

目標均值編碼(Mean target encoding)

首先,你會實作一個函式來完成目標均值編碼。記得需要完成以下兩個步驟:

  1. 在訓練集上計算平均值,並套用到測試集。
  2. 將訓練集切成 K 個摺。對每個摺計算 out-of-fold 的平均值,並套用到該摺。

這兩個步驟將分別在 test_mean_target_encoding()train_mean_target_encoding() 兩個函式中實作。

最終的 mean_target_encoding() 函式會接收以下參數:訓練與測試的 DataFrame、需要編碼的類別欄位名稱、目標欄位名稱,以及平滑參數 alpha。它會回傳兩個值:分別是訓練集與測試集的新特徵。

本練習屬於課程

用 Python 拿下 Kaggle 競賽

檢視課程

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def test_mean_target_encoding(train, test, target, categorical, alpha=5):
    # Calculate global mean on the train data
    global_mean = train[target].mean()
    
    # Group by the categorical feature and calculate its properties
    train_groups = train.groupby(categorical)
    category_sum = train_groups[target].sum()
    category_size = train_groups.size()
    
    # Calculate smoothed mean target statistics
    train_statistics = (category_sum + global_mean * alpha) / (category_size + ____)
    
    # Apply statistics to the test data and fill new categories
    test_feature = test[categorical].map(train_statistics).fillna(____)
    return test_feature.values
編輯並執行程式碼