如何使用Python高效地收集相似向量?

2024-03-29 02:00:25 发布

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

我有一大组三维向量,每个向量都与一个权重相关联。也就是说,集合的形式是

{[[0.707,0.5,0.5],0.3],[[0.6,0.8,0],0.2]....}

我想收集彼此接近的向量,并将它们的权重相加。现在我的想法是:如果一个向量a和另一个向量B很接近,那么我将把它们当作同一个向量,把a的权重加到B的权重上。Python代码是

def gathervecs(vecs):
    gathers = []
    for vec in vecs: #in each vec, there are two elements, the first one is the normalized vector, and the second is the norm**2.
        index = 0
        for i,avec in enumerate(gathers):
            if sum(abs(vec[0] - avec[0])) < 10**(-10):
                (gathers[i])[1] = avec[1]+vec[1]
                index = 1
                break
                if index==0:
                gathers.append(vec)
                return gathers

但是这个代码的时间是原始集合大小的多项式。因此,问题是如何设计一个更有效的算法

PS:请随机生成测试算法效率的原始集合


Tags: the代码in算法forindexifis