首页 > 解决方案 > DBScan 聚类算法运行缓慢的问题

问题描述

我正在尝试在不使用 sklearn 的情况下构建一种用于进行 DBScan 聚类的算法。我用它来制作图片中具有相似颜色的像素簇。我构建了一个算法来执行它,但需要大量时间才能完成。

这是代码片段:

euclideanDist = lambda a, b: np.linalg.norm(a - b)

def nextVisit(indices):
    for k in range(len(indices)):
        if len(indices[k]) > 0:
            return indices[k].pop(0), k
    return -1, -1


def dbScan2(image, d):
    indexes = [[i for i in range(len(image[k]))] for k in range(len(image))]
    print(np.shape(image))
    width = np.shape(image)[0]
    height = np.shape(image)[1]
    count = 0
    clusters = []
    current_cluster = [(0, 0)]
    nodes_to_visit = []
    currX, currY = indexes[0].pop(0), 0
    while currX >= 0:
        for k in range(len(indexes)):
            for i in indexes[k]:
                if euclideanDist(image[currY][currX], image[k][i]) < d:
                    current_cluster.append((i, k))
                    indexes[k].remove(i)
                    nodes_to_visit.append((i, k))
        if len(nodes_to_visit) > 0:
            (currX, currY) = nodes_to_visit.pop()
        else:
            currX, currY = nextVisit(indexes)
            clusters.append(current_cluster)
            current_cluster = [(currX, currY)]
        count += 1
        print(currX, currY, "remaining px to check:", str(width * height - count))
    clusters.append(current_cluster)
    return clusters

我试图通过删除已经检查过的像素来优化功能,但它仍然很慢。

对优化我的算法的任何帮助将不胜感激!

标签: pythonnumpydbscan

解决方案


推荐阅读