在Python / PySpark中获取k-means聚类中心和异常值

3

有没有人知道在Python/PySpark中用简单的算法检测K-means聚类中的离群值,并创建一个离群值列表或数据框?我不确定如何获取质心。 我正在使用以下代码:

n_clusters = 10

kmeans = KMeans(k = n_clusters, seed = 0)
model = kmeans.fit(Data.select("features"))
1个回答

5

model.clusterCenters()将给出聚类中心。

获取异常值的一种简单方法是获取大小为1的簇。

示例:

data.show()
+-------------+
|     features|
+-------------+
|    [0.0,0.0]|
|    [1.0,1.0]|
|    [9.0,8.0]|
|    [8.0,9.0]|
|[100.0,100.0]|
+-------------+

from pyspark.ml.clustering import KMeans
kmeans = KMeans()
model = kmeans.fit(data)
model.summary.predictions.show()
+-------------+----------+
|     features|prediction|
+-------------+----------+
|    [0.0,0.0]|         0|
|    [1.0,1.0]|         0|
|    [9.0,8.0]|         0|
|    [8.0,9.0]|         0|
|[100.0,100.0]|         1|
+-------------+----------+

print(model.clusterCenters())
[array([4.5, 4.5]), array([100., 100.])]

print(model.summary.clusterSizes)
[4, 1]

# Get outliers with cluster size = 1
import pyspark.sql.functions as F
model.summary.predictions.filter(
    F.col('prediction').isin(
        [cluster_id for (cluster_id, size) in enumerate(model.summary.clusterSizes) if size == 1]
    )
).show()
+-------------+----------+
|     features|prediction|
+-------------+----------+
|[100.0,100.0]|         1|
+-------------+----------+

1
还要查看scipy的kmeans模块 https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans2.html - Josh Sharkey
@mck 为了确保我理解正确:您定义每个簇的大小为1,然后将在大小为1的簇之外的观测值定义为异常值?而将大小定义为1的步骤是“model.clusterCenters() [array([4.5, 4.5]), array([100., 100.])]”吗? - Johanna
@Johanna 不,群集大小是由kmeans算法确定的。大小为1的群集被定义为异常值。 - mck
2
是的,没错。那些离群值不会成为任何其他簇的一部分,因此它将形成一个大小为1的自己的簇。这样清楚你的疑虑了吗? - mck
3
不,它们不是异常值。如果它们距离质心足够远,它们就不会被分配到那个簇中。 - mck
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接