无监督学习聚类一维数组

Unsupervised learning clustering 1D array

我面临以下数组:

y = [1,2,4,7,9,5,4,7,9,56,57,54,60,200,297,275,243]

我想做的是提取得分最高的集群。那将是

best_cluster = [200,297,275,243]

我在堆栈上查了很多关于这个主题的问题,其中大多数建议使用 kmeans。尽管其他一些人提到 kmeans 可能对一维数组聚类来说有点矫枉过正。 然而,kmeans 是一种监督学习算法,因此这意味着我必须传入质心的数量。由于我需要将此问题推广到其他数组,因此我无法传递每个数组的质心数。因此,我正在考虑实施某种无监督学习算法,该算法能够自行找出集群,select 最高的一个。 在数组 y 中,我会看到 3 个簇 [1,2,4,7,9,5,4,7,9],[56,57,54,60],[200,297,275,243]。 考虑到计算成本和准确性,哪种算法最适合我的需求?我该如何为我的问题实施它?

尝试 MeanShift. From the sklean user guide 的 MeanShift:

The algorithm automatically sets the number of clusters, ...

修改后的演示代码:

import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth

# #############################################################################
# Generate sample data
X = [1,2,4,7,9,5,4,7,9,56,57,54,60,200,297,275,243]
X = np.reshape(X, (-1, 1))

# #############################################################################
# Compute clustering with MeanShift

# The following bandwidth can be automatically detected using
# bandwidth = estimate_bandwidth(X, quantile=0.2, n_samples=100)

ms = MeanShift(bandwidth=None, bin_seeding=True)
ms.fit(X)
labels = ms.labels_
cluster_centers = ms.cluster_centers_

labels_unique = np.unique(labels)
n_clusters_ = len(labels_unique)

print("number of estimated clusters : %d" % n_clusters_)
print(labels)

输出:

number of estimated clusters : 2
[0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1]

请注意,MeanShift 不能随样本数量扩展。建议上限为 10,000。


顺便说一句,正如 rahlf23 已经提到的,K-mean 是一种 无监督 学习算法。事实上,你必须指定集群的数量并不意味着它是有监督的。

另请参阅:

HDBSCAN 是最好的聚类算法,您应该经常使用它。

基本上您需要做的就是提供一个合理的min_cluster_size、一个有效的距离metric就可以了。

对于 min_cluster_size 我建议使用 3,因为 2 的集群是蹩脚的,对于 metric 默认的 euclidean 效果很好,所以你甚至不需要提及它。

不要忘记距离度量适用于向量,这里我们有标量,因此需要进行一些丑陋的重塑。

将它们放在一起并假设 "cluster with the highest scores" 你的意思是包含我们得到的最大值的集群:

from hdbscan import HDBSCAN
import numpy as np

y = [1,2,4,7,9,5,4,7,9,56,57,54,60,200,297,275,243]
y = np.reshape(y, (-1, 1))

clusterer = HDBSCAN(min_cluster_size=3)
cluster_labels = clusterer.fit_predict(y)

best_cluster = clusterer.exemplars_[cluster_labels[y.argmax()]].ravel()
print(best_cluster)

输出为[297 200 275 243]。不保留原始订单。 人生至此.

聚类 在这里有点矫枉过正

只需计算后续元素的差异。 IE。看看 x[i]-x[i-1].

选择k个最大的差异作为分割点。或者定义何时拆分的阈值。例如。 20. 取决于你的数据知识。

这是 O(n),比提到的所有其他方法快得多。也非常容易理解和预测。

在一维有序数据上,任何不使用顺序的方法都会比必要的慢。