【问题标题】:clustering 1D data and representing clusters on matplotlib histogram聚类一维数据并在 matplotlib 直方图上表示聚类
【发布时间】:2021-05-25 07:32:52
【问题描述】:

我有以下格式的一维数据:

areas = ...
plt.figure(figsize=(10, 10))
plt.hist(areas, bins=80)
plt.show()

这个情节看起来有点像这样:

现在我希望能够对这些数据进行聚类。我知道我可以选择Kernel Density Estimation 或 K-Means。但是一旦我有了这些值,我如何在直方图上表示这些集群?

【问题讨论】:

  • 你想在histogram上绘制KDE,对吗?
  • @JayPatel 我想要如上所示的直方图,但颜色表示它们来自这些数据点的集群。显示每种颜色的聚类中心的图例也非常好。

标签: python-3.x matplotlib scikit-learn histogram cluster-analysis


【解决方案1】:

您只需要弄清楚您的集群分配,然后分别绘制数据的每个子集,同时注意每次的 bin 都相同。

import numpy as np
import matplotlib.pyplot as plt

from sklearn.cluster import KMeans

import matplotlib as mpl
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.right'] = False

# simulate some fake data
n = 10000
mu1, sigma1 = 0, 1
mu2, sigma2 = 6, 2
a = mu1 + sigma1 * np.random.randn(n)
b = mu2 + sigma2 * np.random.randn(n)
data = np.concatenate([a, b])

# determine which K-Means cluster each point belongs to
cluster_id = KMeans(2).fit_predict(data.reshape(-1, 1))

# determine densities by cluster assignment and plot
fig, ax = plt.subplots()
bins = np.linspace(data.min(), data.max(), 40)
for ii in np.unique(cluster_id):
    subset = data[cluster_id==ii]
    ax.hist(subset, bins=bins, alpha=0.5, label=f"Cluster {ii}")
ax.legend()
plt.show()

【讨论】:

    猜你喜欢
    • 2014-10-28
    • 2021-08-24
    • 1970-01-01
    • 2021-08-02
    • 2013-05-17
    • 2012-01-02
    • 1970-01-01
    • 2012-07-15
    • 2020-06-28
    相关资源
    最近更新 更多