通过 KMeans 聚类确定双峰分布的阈值
Determining a threshold value for a bimodal distribution via KMeans clustering
我想找到双峰分布的阈值。例如,双峰分布可能如下所示:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(45)
n = 1000; b = n//10; i = np.random.randint(0,2,n)
x = i*np.random.normal(-2.0,0.8,n) + (1-i)*np.random.normal(2.0,0.8,n)
_ = plt.hist(x,bins=b)
寻找聚类中心的尝试没有成功,因为我不确定矩阵 h 应该如何格式化:
from sklearn.cluster import KMeans
h = np.histogram(x,bins=b)
h = np.vstack((0.5*(h[1][:-1]+h[1][1:]),h[0])).T # because h[0] and h[1] have different sizes.
kmeans = KMeans(n_clusters=2).fit(h)
我希望能够找到围绕 -2 和 2 的聚类中心。阈值将是两个聚类中心的中点。
你的问题让我有点困惑,所以如果我对它的解释有误,请告诉我。我认为你基本上是在尝试做一维 kmeans,并尝试引入频率作为第二个维度来让 KMeans
工作,但真的会很高兴 [-2,2]
作为中心的输出而不是[(-2,y1), (2,y2)]
.
要执行 1D kmeans,您只需将数据重塑为 n
个长度为 1 的向量(类似问题:)
代码:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(45)
n = 1000;
b = n//10;
i = np.random.randint(0,2,n)
x = i*np.random.normal(-2.0,0.8,n) + (1-i)*np.random.normal(2.0,0.8,n)
_ = plt.hist(x,bins=b)
from sklearn.cluster import KMeans
h = np.histogram(x,bins=b)
h = np.vstack((0.5*(h[1][:-1]+h[1][1:]),h[0])).T # because h[0] and h[1] have different sizes.
kmeans = KMeans(n_clusters=2).fit(x.reshape(n,1))
print kmeans.cluster_centers_
输出:
[[-1.9896414]
[ 2.0176039]]
我想找到双峰分布的阈值。例如,双峰分布可能如下所示:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(45)
n = 1000; b = n//10; i = np.random.randint(0,2,n)
x = i*np.random.normal(-2.0,0.8,n) + (1-i)*np.random.normal(2.0,0.8,n)
_ = plt.hist(x,bins=b)
寻找聚类中心的尝试没有成功,因为我不确定矩阵 h 应该如何格式化:
from sklearn.cluster import KMeans
h = np.histogram(x,bins=b)
h = np.vstack((0.5*(h[1][:-1]+h[1][1:]),h[0])).T # because h[0] and h[1] have different sizes.
kmeans = KMeans(n_clusters=2).fit(h)
我希望能够找到围绕 -2 和 2 的聚类中心。阈值将是两个聚类中心的中点。
你的问题让我有点困惑,所以如果我对它的解释有误,请告诉我。我认为你基本上是在尝试做一维 kmeans,并尝试引入频率作为第二个维度来让 KMeans
工作,但真的会很高兴 [-2,2]
作为中心的输出而不是[(-2,y1), (2,y2)]
.
要执行 1D kmeans,您只需将数据重塑为 n
个长度为 1 的向量(类似问题:
代码:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(45)
n = 1000;
b = n//10;
i = np.random.randint(0,2,n)
x = i*np.random.normal(-2.0,0.8,n) + (1-i)*np.random.normal(2.0,0.8,n)
_ = plt.hist(x,bins=b)
from sklearn.cluster import KMeans
h = np.histogram(x,bins=b)
h = np.vstack((0.5*(h[1][:-1]+h[1][1:]),h[0])).T # because h[0] and h[1] have different sizes.
kmeans = KMeans(n_clusters=2).fit(x.reshape(n,1))
print kmeans.cluster_centers_
输出:
[[-1.9896414]
[ 2.0176039]]