Python集群模块类方法

2024-03-28 13:35:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为集群编写一个模块,但是类方法对我来说有点混乱

import numpy as np

class SingleLinkage:

    def __init__(self, x, k):
        self.data = x
        n=x.shape[0]
        self.clusters={i : [i] for i in range(n)}
        self.k=k
        self.y=None

    def euc(self,x,y):
        self.x=x
        if self.y==None:
            self.y=y 
        return np.sqrt(np.sum((x-y)**2))

    def clustDist(self, i, j):
        cd=np.Inf
        for idx in self.clusters[i]:
            for idy in self.clusters[j]:
                cd=min(cd,self.euc(self.data[idx], self.data[idy]))
        return cd

    def findClothest(self):
        cd=np.Inf
        for i in self.clusters:
            for j in self.clusters:
                if i!=j and clustDist(i,j)<cd:
                    cc=(i,j)
                    cd=clustDist(i,j)
    def merge(self,i,j):
        self.clusters[i]+=self.clusters[j]
        self.clusters.pop(j)

当我运行它时,它会给我:

>>> x = np.array ([[0 , 0] , [0 , 0.1] , [1 , 1]])
>>> hc = lc.SingleLinkage (x , 2)
>>> hc.clusters
{0: [0], 1: [1], 2: [2]}

但应该有所不同:

>>> hc.clusters
{0: [0 , 1] , 1: [2]}

我知道可能是init函数出错了。我该怎么改呢


Tags: inhcselfnonefordataifinit