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

基于数组列表用Scikit-learn绘制凝聚聚类图报错TypeError的排查

TypeError: only integer scalar arrays can be converted to a scalar index 错误原因及解决

错误原因

  1. 数据类型不兼容:你的X是Python列表而非numpy数组,列表不支持布尔数组索引操作。model.labels_ == l生成的是布尔数组,用它去索引列表X会直接触发该TypeError。
  2. 绘图操作依赖numpy特性:即使AgglomerativeClustering.fit()可以兼容列表输入,后续绘图时的X[model.labels_ == l].T需要numpy数组的转置和布尔索引能力,列表无法支持这种操作。

修正方案

步骤1:将X转换为二维numpy数组

先把包含子数组的列表转成numpy数组,确保所有子数组长度一致(如果长度不一致,需要先做截断/填充处理)。

修正后的完整代码

import numpy as np
from sklearn.cluster import AgglomerativeClustering
import matplotlib.pyplot as plt

colors = ["#f7bd01", "#377eb8", "#f781bf"]
# 转换为numpy二维数组
X = np.array(X)
model = AgglomerativeClustering(n_clusters=3, linkage="average")
model.fit(X)
plt.figure()
plt.axes([0, 0, 1, 1])
for l, color in zip(np.arange(model.n_clusters), colors):
    # 现在可正常使用布尔索引筛选聚类样本
    plt.plot(X[model.labels_ == l].T, c=color, alpha=0.5)
plt.axis("tight")
plt.axis("off")
plt.show()

额外注意

如果子数组长度不一致,转成numpy数组后会变成object类型,仍然无法正常索引。这种情况下需要先统一所有样本的特征长度,比如:

  • 截断过长的样本到最短长度
  • 用均值/0填充过短的样本到最长长度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:25:27