m0_65018173
2022-02-11 21:14
采纳率: 100%
浏览 23

python运行层次聚类Agnes算法报错

问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
#描述: 基于组平均的AGNES算法,支持多维数组,距离用欧式距离


import numpy as np
import pandas as pd
from scipy.cluster.hierarchy import dendrogram,linkage
from scipy.spatial.distance import squareform
import matplotlib.pyplot as plt
import pylab as pl


#从excel中读取数据并转换为矩阵
datA=pd.read_excel(r'C:\Users\49175\Desktop\jzgb.xlsx')
data=np.array(datA,dtype=np.int64)


#数据处理 dataset是样本的列表
a = np.array_split(datA,78,axis=0)
dataset = [(a[i], a[i+1]) for i in range(1, len(a)-1, 44)]


#计算欧几里得距离,a,b分别为两个元组
def dist(a, b):
    t = 0
    n=44
    for i in range(n):
        t = t + np.power(a[i]-b[i], 2)
    return np.sqrt(t)

#dist_min
def dist_min(Ci, Cj):
    return min(dist(i, j) for i in Ci for j in Cj)
#dist_max
def dist_max(Ci, Cj):
    return max(dist(i, j) for i in Ci for j in Cj)
#dist_avg
def dist_avg(Ci, Cj):
    return sum(dist(i, j) for i in Ci for j in Cj)/(len(Ci)*len(Cj))

#找到距离最小的下标
def find_Min(M):
    min = 1000
    x = 0; y = 0
    for i in range(len(M)):
        for j in range(len(M[i])):
            if i != j and M[i][j] < min:
                min = M[i][j];x = i; y = j
    return (x, y, min)

#算法模型
def AGNES(dataset, dist, k):
    #初始化C和M
    C = [];M = []
    for i in dataset:
        Ci = []
        Ci.append(i)
        C.append(Ci)
    for i in C:
        Mi = []
        for j in C:
            Mi.append(dist(i, j))
        M.append(Mi)
    q = len(dataset)
    #合并更新
    while q > k:
        x, y, min = find_Min(M)
        C[x].extend(C[y])
        C.remove(C[y])
        M = []
        for i in C:
            Mi = []
            for j in C:
                Mi.append(dist(i, j))
            M.append(Mi)
        q -= 1
    return C
#画图
def draw(C):
    colValue = ['r', 'y', 'g', 'b', 'c', 'k', 'm']
    for i in range(len(C)):
        coo_X = []    #x坐标列表
        coo_Y = []    #y坐标列表
        for j in range(len(C[i])):
            coo_X.append(C[i][j][0])
            coo_Y.append(C[i][j][1])
        pl.scatter(coo_X, coo_Y, marker='x', color=colValue[i%len(colValue)], label=i)

    pl.legend(loc='upper right')
    pl.show()

C = AGNES(dataset, dist_avg, 8)
draw(C)




运行结果及报错内容
Traceback (most recent call last):
  File "C:/各种东西练习/1/4.py", line 91, in <module>
    C = AGNES(dataset, dist_avg, 8)
  File "C:/各种东西练习/1/4.py", line 61, in AGNES
    Mi.append(dist(i, j))
  File "C:/各种东西练习/1/4.py", line 38, in dist_avg
    return sum(dist(i, j) for i in Ci for j in Cj)/(len(Ci)*len(Cj))
  File "C:/各种东西练习/1/4.py", line 38, in <genexpr>
    return sum(dist(i, j) for i in Ci for j in Cj)/(len(Ci)*len(Cj))
  File "C:/各种东西练习/1/4.py", line 27, in dist
    t = t + np.power(a[i]-b[i], 2)
IndexError: tuple index out of range

我的解答思路和尝试过的方法
我想要达到的结果

2条回答 默认 最新

相关推荐 更多相似问题