我正在使用HDBSCAN,我只想绘制数据的一个集群。
这是我当前的代码:
import hdbscan
import pandas as pd
from sklearn.datasets import make_blobs
blobs, labels = make_blobs(n_samples=2000, n_features=10)
clusterer = hdbscan.HDBSCAN(min_cluster_size=15).fit(blobs)
color_palette = sns.color_palette('deep', 8)
cluster_colors = [color_palette[x] if x >= 0
else (0.5, 0.5, 0.5)
for x in clusterer.labels_]
cluster_member_colors = [sns.desaturate(x, p) for x, p in
zip(cluster_colors, clusterer.probabilities_)]
plt.scatter(blobs[:, 2], blobs[:, 5], s=50, linewidth=0, c=cluster_member_colors, alpha=0.25)
plt.show()
我知道数据有3个簇,但我如何只绘制其中一个?
如果我有一个聚类点,我怎么知道pandas数据框的哪一列对应于这个点?
我建议将所有相关信息添加到pandas数据框中。
df = pd.DataFrame(blobs)
clusterer = hdbscan.HDBSCAN(min_cluster_size=15).fit(blobs)
df['cluster'] = clusterer.labels_
df['probability'] = clusterer.probabilities_
color_palette = sns.color_palette('deep', 8)
def get_member_color(row):
if row['cluster'] >= 0:
c = color_palette[int(row['cluster'])]
else:
c = (0.5, 0.5, 0.5)
member_color = sns.desaturate(c, row['probability'])
return member_color
df['member_color'] = df.apply(get_member_color, axis=1)
现在您可以轻松地筛选它们所属的集群之后的行。例如,要绘制属于集群2的所有样本,我们可以这样做:
df2 = df.loc[df['cluster'] == 2]
plt.scatter(df2.iloc[:, 2], df2.iloc[:, 5], s=50, linewidth=0, c=df2['member_color'], alpha=0.25)
plt.show()