You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何访问Python中Kmeans返回的Cluster对象值以实现绘图

解决Kmeans聚类结果提取数据点并绘图的问题

核心问题

你得到的clusters是Cluster对象列表,无法直接获取数据点的原因是没找到Cluster类中存储数据的入口——要么调用类的公开方法,要么访问其内部属性。

解决步骤

1. 优先尝试Cluster类的公开方法

从提供的kmeans代码可知,Cluster有getCentroid()和update()方法,大概率存在获取数据点的方法。直接测试:

# 取第一个聚类对象
first_cluster = clusters[0]
# 尝试调用常见的获取数据方法
print(first_cluster.getExamples())  # 最可能的命名
# 或者直接访问公开属性
print(first_cluster.examples)

如果Cluster类实现了getExamples()这类方法,就能直接拿到该聚类下的所有数据点。

2. 查看Cluster对象的内部结构

如果上述方法无效,用dir()函数列出对象的所有属性和方法,找到存储数据的字段:

# 查看第一个聚类对象的所有成员
print(dir(clusters[0]))

从输出里找类似examples、_examples(私有属性)的名称,直接访问:

# 假设内部数据存在_examples属性中
cluster_points = clusters[0]._examples

3. 提取数据并可视化

拿到每个聚类的数据点后,转成numpy数组,用matplotlib分颜色和标记绘图:

import matplotlib.pyplot as plt
import numpy as np

# 定义不同聚类的颜色和标记(可根据k值调整)
colors = ['#FF5733', '#33FF57', '#3357FF', '#FF33A6']
markers = ['o', 's', '^', 'D']

plt.figure(figsize=(8, 6))
for idx, cluster in enumerate(clusters):
    # 提取当前聚类的数据点(替换成你找到的方法/属性)
    points = cluster.getExamples()
    # 转换为numpy数组(假设每个数据点是二维坐标)
    points_np = np.array([np.array(p) for p in points])
    # 绘制散点图
    plt.scatter(points_np[:, 0], points_np[:, 1], 
                c=colors[idx % len(colors)],
                marker=markers[idx % len(markers)],
                label=f'Cluster {idx + 1}')

plt.legend()
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('Kmeans Clustering Result')
plt.show()

检索方向建议

  • 关键词:Python 自定义类 访问内部数据、Cluster类 获取成员属性、matplotlib 多组散点图绘制
  • 重点参考:Python类属性访问规则、matplotlib散点图参数说明、自定义类实例的属性查看方法

内容的提问来源于stack exchange,提问作者Jesse Garcia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:47:36