绘制单个集群
Plot a single cluster
我正在使用 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()
我正在使用 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()