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

如何编写for循环简化重复的NumPy聚类质心计算代码?

解决方案

你之前的写法报错主要有两个问题:

  • 变量拼写错误:你写的for labele in labeles存在拼写问题,正确的变量名应该对应你代码里的labels,同时遍历的单个值建议命名为label避免混淆
  • 遍历逻辑错误:直接遍历labels数组会重复处理同一个聚类的编号,应该先取所有唯一的聚类id再遍历

基础实现(逻辑和原代码完全对齐)

import numpy as np

# 先获取所有不重复的聚类编号
unique_cluster_ids = np.unique(labels)
# 用列表存储所有聚类中心,后续可以通过索引直接获取对应聚类的中心
centroid_list = []

for cluster_id in unique_cluster_ids:
    points_of_cluster = X[labels == cluster_id, :]
    centroid_of_cluster = np.mean(points_of_cluster, axis=0)
    centroid_list.append(centroid_of_cluster)
    print(centroid_of_cluster)

调用说明:如果需要获取聚类0的中心,直接使用centroid_list[0]即可,和你原代码中centroid_of_cluster_0的效果完全一致。

高性能简化实现

如果你的数据量较大,可以使用下面的写法,逻辑更简洁执行效率也更高:

import numpy as np

cluster_count = np.max(labels) + 1
centroids = np.zeros((cluster_count, X.shape[1]))

for i in range(cluster_count):
    centroids[i] = X[labels == i].mean(axis=0)

# 批量打印所有聚类中心
for cent in centroids:
    print(cent)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:24:01