偵測離群值
在接下來的練習中,你將使用 K-means 演算法來預測詐欺,並把這些預測與已儲存的實際標籤做比較,以檢核結果的合理性。
詐欺交易通常會被標記為那些距離群心最遠的觀測值。你會在本練習中學到如何這麼做,以及如何決定臨界值(cut-off)。下一個練習中,你會檢查結果。
可用的資料包含已縮放的觀測值 X_scaled,以及儲存在變數 y 中的標籤。
本練習屬於課程
Fraud Detection in Python
練習說明
- 將縮放後的資料與標籤
y切分為訓練集與測試集。 - 定義具有 3 個群集的 MiniBatch K-means 模型,並以訓練資料進行訓練。
- 由測試資料取得群集預測,並取得群心位置。
- 將詐欺與非詐欺的分界定義為距離分佈的 95% 與以上。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Split the data into training and test set
X_train, X_test, y_train, y_test = ____(____, ____, test_size=0.3, random_state=0)
# Define K-means model
kmeans = ____(n_clusters=____, random_state=42).fit(____)
# Obtain predictions and calculate distance from cluster centroid
X_test_clusters = ____.____(X_test)
X_test_clusters_centers = ____.____
dist = [np.linalg.norm(x-y) for x, y in zip(X_test, X_test_clusters_centers[X_test_clusters])]
# Create fraud predictions based on outliers on clusters
km_y_pred = np.array(dist)
km_y_pred[dist >= np.percentile(dist, ____)] = 1
km_y_pred[dist < np.percentile(dist, ____)] = 0