【问题标题】:Visualizing 3D clustering using matplotlib使用 matplotlib 可视化 3D 聚类
【发布时间】:2017-09-14 12:31:18
【问题描述】:

我已经对 3 个特征 Feature1、Feature2 和 Feature3 进行了聚类,并提出了 2 个聚类。 我正在尝试使用 matplotlib 可视化 3D 集群。

在下表中,执行聚类的三个特征。簇数为 2。

    Feature1        Feature2    Feature3    ClusterIndex
  0 1.349656e-09    1.000000    1.090542e-09    0
  1 1.029752e-07    1.000000    6.040669e-08    0
  2 2.311729e-07    1.000000    1.568289e-11    0
  3 1.455860e-08    6.05e-08    1.000000        1
  4 3.095807e-07    2.07e-07    1.000000        1

试过这段代码:

   fig = plt.figure()
   ax = fig.add_subplot(111, projection='3d')
   x = np.array(df['Feature1'])
   y = np.array(df['Feature2'])
   z = np.array(df['Feature3'])
   ax.scatter(x,y,z, marker=colormap[kmeans.labels_], s=40)

但是,我收到错误 "ValueError: could not convert string to float: red"。因此,标记部分是我得到错误的地方。

通过在散点图中绘制点并使用集群标签进行区分,集群的 2D 可视化非常简单。

只是想知道有没有办法对集群进行 3D 可视化。

任何建议将不胜感激!!

【问题讨论】:

  • 我收到错误“ValueError:无法将字符串转换为浮点数:红色”。标记部分是我得到错误的地方。它无法将字符串转换为浮点数。类型转换没有帮助。在 2D 绘图中,它可以工作,但不确定为什么它不适用于 3D 绘图。
  • 那么,colormap 是什么,kmeans.labels_ 是什么?
  • @ ImportanceOfBeingErnest :kmeans.labels 是集群索引,如 0 和 1(因为我有 2 个集群)。颜色图将标签转换为颜色。

标签: matplotlib cluster-analysis visualization


【解决方案1】:

原则上,问题中的代码应该可以工作。然而,尚不清楚marker=colormap[kmeans.labels_] 会做什么以及为什么需要它。

3D 散点图的工作原理与它的 2D 版本完全相同。

标记参数需要一个标记字符串,如"s""o" 来确定标记形状。
可以使用c 参数设置颜色。您可以提供一种颜色或一个数组/颜色列表。在下面的示例中,我们只是将集群索引提供给c 并使用颜色图。

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import numpy as np

v = np.random.rand(10,4)
v[:,3] = np.random.randint(0,2,size=10)
df = pd.DataFrame(v, columns=['Feature1', 'Feature2','Feature3',"Cluster"])
print (df)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.array(df['Feature1'])
y = np.array(df['Feature2'])
z = np.array(df['Feature3'])

ax.scatter(x,y,z, marker="s", c=df["Cluster"], s=40, cmap="RdBu")

plt.show()

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 2021-10-04
    • 2018-10-23
    • 1970-01-01
    • 2020-03-15
    • 2021-12-19
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多