2017-02-10 52 views
0

我想找到雙峯分佈的閾值。例如,雙峯分佈可能看起來像下面這樣:通過KMeans聚類確定雙峯分佈的閾值

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) 

bimodal_histogram

試圖找到聚類中心沒有工作,因爲我不知道如何矩陣,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的閾值,然後將兩個聚類中心的中點。

回答

1

您的問題對我有點困惑,所以請讓我知道,如果我不正確地解釋它。我認爲你基本上是在嘗試做一維kmeans,並嘗試將頻率作爲第二維來獲得KMeans的工作效果,但實際上只是將[-2,2]作爲中心的輸出而不是[(-2,y1), (2,y2)]而感到滿意。

要做到一維k均值你可以重塑你的數據是1長度矢量n(類似的問題:Scikit-learn: How to run KMeans on a one-dimensional array?

代碼:

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]]