您提供的代码中可能存在以下问题,导致寻找每个点的索引值结果为空:

  1. 变量名混淆: 代码第二行使用变量名 i 代表当前迭代的簇索引,而在第三行又将 i 用作迭代的数据点索引,这会导致代码错误。

  2. 数据比较错误: 第三行代码使用 np.abs(dataset - i) 试图通过将整个数据集减去一个整数来寻找相等的数据点,这不是正确的做法。

  3. 索引查找方法问题: 第三行代码使用 np.where((np.abs(dataset - i) < 1e-10).all(axis=1))[0] 来查找数据点索引。在实际数据中,数据点的值可能不完全相等,使用 == 来比较两个值更可靠。

解决方案:

为了解决这些问题,您可以尝试以下代码:

customer_index = [[] for _ in range(len(final_clusters))]
for i, cluster in enumerate(final_clusters):
    for j in final_clusters[i]:
        index = np.where((dataset == j).all(axis=1))[0]
        if len(index) > 0:
            customer_index[i].append(index[0])

这段代码将遍历每个簇和每个数据点,通过比较数据点的值来查找其在数据集中的索引值。如果找到索引值,则将其添加到相应的 customer_index 列表中。

代码解析:

  • customer_index = [[] for _ in range(len(final_clusters))]: 初始化一个嵌套列表,用于存储每个簇对应的索引值。
  • for i, cluster in enumerate(final_clusters): 遍历每个簇。
  • for j in final_clusters[i]: 遍历当前簇中的每个数据点。
  • index = np.where((dataset == j).all(axis=1))[0]: 使用 np.where() 函数查找与当前数据点 j 相等的索引值。
  • if len(index) > 0: 检查是否找到了索引值,如果有,则将其添加到 customer_index 中。
  • customer_index[i].append(index[0]): 将找到的索引值添加到对应簇的 customer_index 列表中。

通过这些修正,您的代码能够准确地找到每个数据点的索引值,并避免出现空结果的情况。

Python 代码调试:寻找每个点的索引值为空的解决方法

原文地址: https://www.cveoy.top/t/topic/n1z4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录