Это означает, что алгоритм всегда сходится сразу? - PullRequest
0 голосов
/ 17 мая 2019

Я новичок в области ML, и я хочу сам реализовать алгоритм k средних с использованием python. Но мой алгоритм всегда имеет тенденцию сходиться в несколько раундов, интересно, разумно ли это или что-то не так в моем коде. Вот мой код, и любая помощь будет оценена.

    # using Euclidean distance to determine the similarity
    def getDistance(vector1, vector2):
        return np.linalg.norm(vector1-vector2, ord=2)

    def k_means(k):
        samples = np.random.random((50, 16))
        temp = random.sample(list(samples), k)
        centers = {}
        for i in range(len(temp)):
            centers[chr(ord('A')+i)] = temp[i]
        j, rounds = 0, 10
        while j < rounds:
            bags = {}

            print("-------round {}----------".format(j+1))
            print("The center is: ")
            print(centers)
            for feat in samples:
                minVal = -1
                kind = None
                for bag, center in centers.items():
                    tempVal = getDistance(center, feat)
                    if bag not in bags:
                        bags[bag] = []
                    if minVal < 0:
                        minVal = tempVal
                    if tempVal <= minVal:
                        kind = bag
                        minVal = tempVal
                if kind:
                    bags[kind].append(feat)
            # update the center point in next round
            for i in range(k):
                total = np.zeros(16, dtype=float)
                count = len(bags[chr(ord('A')+i)])
                for feat in bags[chr(ord('A')+i)]:
                    total = np.add(total, feat)
                centers[chr(ord('A')+i)] = total/count if count != 0 else centers[chr(ord('A')+i)]
            j += 1
            print("-----------------")


...