问题遇到的现象和发生背景
从excel中导入数据进行层次聚类分析,导入数据类型不对,无法进行计算
问题相关代码,请勿粘贴截图
#描述: 基于组平均的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 math
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, 3)]
#计算欧几里得距离,a,b分别为两个元组
def dist(a, b):
t = 0
n=44
for i in range(n):
t = t + math.pow(a[i]-b[i], 2)
return math.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, 3)
draw(C)
运行结果及报错内容
Traceback (most recent call last):
File "C:/各种东西练习/1/4.py", line 92, in <module>
C = AGNES(dataset, dist_avg, 3)
File "C:/各种东西练习/1/4.py", line 62, in AGNES
Mi.append(dist(i, j))
File "C:/各种东西练习/1/4.py", line 39, 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 39, 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 28, in dist
t = t + math.pow(a[i]-b[i], 2)
TypeError: must be real number, not DataFrame
我的解答思路和尝试过的方法
我想要达到的结果
能帮我看一看代码中是否有其他问题
并实现层次聚类Agnes算法
能够从excel表格中读取数据,并以每一行为单位,进行层次聚类
数据样式如图