有一个input_df
,它有stiring索引而不是整数。索引可以是任何类似"1234a"、"abcd"等的内容。
我已经用k = 100
对输入df执行了k均值,并且已经接收到centroid
和labels
作为输出。
如果我没有错,
-
centroid
具有100个值,对应于100个这样的聚类的聚类内所有点的平均值。 -
labels
的大小与input_df
的大小相同,后者显示该点/行属于哪个集群。
我现在必须按照以下伪代码执行一个过程来识别k-means聚类中的异常值。
c_x : corresponding centroid of sample point x where x ∈ X
1. Compute the l2 distance of every point to its corresponding centroid.
2. t = the 0.05 or 95% percentile of the l2 distances.
3. for each sample point x in X do
4. if || x - c_x ||2 > t then
5. mark x as outlier
注:第4行中的2
是一个下标。
现在,我还不完全理解第4行中提到的情况。
有人能为上述算法提供一个等效的Python代码吗?
这是代码的结构。
def remove_outliers(input_df, centroids, labels):
pass
kmeans = KMeans(n_clusters=100)
kmeans.fit(input_df)
centroids = kmeans.cluster_centers_
labels = kmeans.labels_
filtered_centroids, filtered_labels = remove_outliers(input_df, centroids, labels)
这个算法写得很差,很难理解。然而,我认为这很可能是该算法的意思:
- 计算X中每个点与其对应质心c_X之间的欧几里得距离
- 计算在步骤1中获得的欧几里得距离的第95个百分位数。这将作为阈值来确定X中的哪些点将是异常值
- 对于X中的每个点,如果在步骤1中获得的对应欧几里得距离大于在步骤2中获得的阈值,则将该点标记为异常值
该算法希望您再次计算步骤3-5的欧几里得距离,即使在步骤1中已经完成了。你可能不想那样做。如果您使用Pandas DataFrame,也许您可以将X、c_X和欧几里得距离计算存储在同一个DataFrame中,并循环使用。
我将让您在Python中实现这一点。
附言:我假设符号L₂
距离和||x||₂
都表示欧几里得距离,正如这里提到的。