我知道这里还有很多其他的问题,比如问什么聚类算法可以用于一维数据,但是我的问题是如何计算平衡的集群呢?
我有一份清单
l = [46, 48, 68, 46, 48, 68, 63, 62, 63, 63, 69, 54, 64, 61, 66, 54, 64, 67, 46, 48]我知道我需要3组。但是使用KMeans聚类会给我
l = np.array(l, dtype=np.int16)
l = np.expand_dims(l, axis=1)
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=3)
labels = kmeans.fit_predict(l)
print(labels)
> array([0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 0, 0])显然,集群是完全不平衡的:
print(np.unique(labels, return_counts=True))
> (array([0, 1, 2]), array([ 6, 12, 2], dtype=int64))那么,是否有一种方法可以在Python中对一维数据进行集群,并有或多或少的平衡的集群?
发布于 2021-04-09 13:20:16
您可以通过将数组划分为3个分位数来实现这一点。在pandas中,您可以使用来自pandas的qcut,如下面的示例所示。
l = [46, 48, 68, 46, 48, 68, 63, 62, 63, 63, 69, 54, 64, 61, 66, 54, 64, 67, 46, 48]
a = pd.qcut(l, 3, labels=[0, 1, 2])
print(a.to_numpy())
[0 0 2 0 0 2 1 1 1 1 2 0 2 1 2 0 2 2 0 0]或者,您只需使用numpy中的np.quantile来手动计算分位数值,然后就可以用来为新的观测分配集群标签。
l = np.array([46, 48, 68, 46, 48, 68, 63, 62, 63, 63, 69, 54, 64, 61, 66, 54, 64, 67, 46, 48])
lower_q = np.quantile(l, 1/3)
upper_q = np.quantile(l, 2/3)
cl = []
for v in l:
if v <= lower_q:
cl.append(0)
elif v > lower_q and v <= upper_q:
cl.append(1)
else:
cl.append(2)
cl = np.array(cl)
print(cl)https://stackoverflow.com/questions/67021257
复制相似问题