检测离群点
在接下来的练习中,您将使用 K-means 算法来预测欺诈,并将这些预测与已保存的真实标签进行对比,以核查结果的合理性。
欺诈交易通常被标记为那些与聚类质心距离最远的观测。您将学习如何完成这一过程,以及如何确定截断阈值。在下一道练习中,您将验证结果。
您可以使用已缩放的观测 X_scaled,以及保存在变量 y 中的标签。
本练习是课程的一部分
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