gpt4 book ai didi

machine-learning - 如何在 scikit learn 中使用核密度估计作为一维聚类方法?

转载 作者:行者123 更新时间:2023-11-30 08:21:18 26 4
gpt4 key购买 nike

我需要将一个简单的单变量数据集聚类为预设数量的聚类。从技术上讲,它更接近于对数据进行分箱或排序,因为它只是一维的,但我的老板称之为聚类,所以我将坚持使用这个名称。我所在的系统当前使用的方法是 K-means,但这似乎有点矫枉过正。

是否有更好的方法来执行此任务?

其他一些帖子的答案提到了 KDE(核密度估计),但这是一种密度估计方法,它是如何工作的?

我看到 KDE 如何返回密度,但我如何告诉它将数据拆分到容器中?

如何拥有独立于数据的固定数量的垃圾箱(这是我的要求之一)?

更具体地说,如何使用 scikit learn 来实现这一目标?

我的输入文件如下所示:

 str ID     sls
1 10
2 11
3 9
4 23
5 21
6 11
7 45
8 20
9 11
10 12

我想将 sls 编号分组到簇或箱中,这样:

Cluster 1: [10 11 9 11 11 12] 
Cluster 2: [23 21 20]
Cluster 3: [45]

我的输出文件将如下所示:

 str ID     sls    Cluster ID  Cluster centroid
1 10 1 10.66
2 11 1 10.66
3 9 1 10.66
4 23 2 21.33
5 21 2 21.33
6 11 1 10.66
7 45 3 45
8 20 2 21.33
9 11 1 10.66
10 12 1 10.66

最佳答案

自己编写代码。那么它最适合您的问题!

样板文件:永远不要假设从网上下载的代码是正确的或最佳的...确保在使用它之前完全理解它。

%matplotlib inline

from numpy import array, linspace
from sklearn.neighbors import KernelDensity
from matplotlib.pyplot import plot

a = array([10,11,9,23,21,11,45,20,11,12]).reshape(-1, 1)
kde = KernelDensity(kernel='gaussian', bandwidth=3).fit(a)
s = linspace(0,50)
e = kde.score_samples(s.reshape(-1,1))
plot(s, e)

enter image description here

from scipy.signal import argrelextrema
mi, ma = argrelextrema(e, np.less)[0], argrelextrema(e, np.greater)[0]
print "Minima:", s[mi]
print "Maxima:", s[ma]
> Minima: [ 17.34693878 33.67346939]
> Maxima: [ 10.20408163 21.42857143 44.89795918]

因此,您的集群是

print a[a < mi[0]], a[(a >= mi[0]) * (a <= mi[1])], a[a >= mi[1]]
> [10 11 9 11 11 12] [23 21 20] [45]

从视觉上看,我们做了这样的分割:

plot(s[:mi[0]+1], e[:mi[0]+1], 'r',
s[mi[0]:mi[1]+1], e[mi[0]:mi[1]+1], 'g',
s[mi[1]:], e[mi[1]:], 'b',
s[ma], e[ma], 'go',
s[mi], e[mi], 'ro')

enter image description here

我们剪切红色标记。绿色标记是我们对聚类中心的最佳估计。

关于machine-learning - 如何在 scikit learn 中使用核密度估计作为一维聚类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35094454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com