Я пытаюсь реализовать алгоритм K-средних в Python (я знаю, что для этого есть библиотеки, но я хочу научиться реализовывать его сам.) Вот функция, с которой у меня проблема:
def AssignPoints(points, centroids):
"""
Takes two arguments:
points is a numpy array such that points.shape = m , n where m is number of examples,
and n is number of dimensions.
centroids is numpy array such that centroids.shape = k , n where k is number of centroids.
k < m should hold.
Returns:
numpy array A such that A.shape = (m,) and A[i] is index of the centroid which points[i] is assigned to.
"""
m ,n = points.shape
temp = []
for i in xrange(n):
temp.append(np.subtract.outer(points[:,i],centroids[:,i]))
distances = np.hypot(*temp)
return distances.argmin(axis=1)
Назначение этой функции, учитывая m точек в n-мерном пространстве и k центроидов в n-мерном пространстве, формирует массив Numpy (x1 x2 x3 x4 ... xm), где x1 - индекс центроидаближе всего к первой точке.Это работало нормально, пока я не попробовал это на четырехмерных примерах.Когда я пытаюсь поместить 4-мерные примеры, я получаю эту ошибку:
File "/path/to/the/kmeans.py", line 28, in AssignPoints
distances = np.hypot(*temp)
ValueError: invalid number of arguments
Как я могу это исправить или, если я не могу, как вы предлагаете мне рассчитать то, что я пытаюсь вычислить здесь?
Мой ответ
def AssignPoints(points, centroids):
m ,n = points.shape
temp = []
for i in xrange(n):
temp.append(np.subtract.outer(points[:,i],centroids[:,i]))
for i in xrange(len(temp)):
temp[i] = temp[i] ** 2
distances = np.add.reduce(temp) ** 0.5
return distances.argmin(axis=1)