这适用于K-Means算法。这是作业,所以我不想用 内置Kmeans功能。 我有2个numpy数组。一个是质心。另一个是数据点。 我试图找到每个质心到每个数据点的距离。 我不知道如何将数组传递给我的函数以便打印。我想结束 与质心一样多的距离数组。然后我可以比较阵列中的每个距离,选择最小的距离 距离并将该点指定给其中一个群集。然后找出每个聚类的平均值 数字成为我的新质心。
import numpy as np
centroids = np.array([[3,44],[5,15]])
dataPoints = np.array([[2,4],[17,4],[45,2],[45,7],[16,32],[32,14],[20,56],[68,33]])
def distance(a,b):
for x in a: #for each point in centroids array
for y in b:#for each point in the dataPoints array
print np.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)#print the distance
distance (randPoints, dataPoints)#call the function with the data
我得到的输出:
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
[ 12.04159458 41.48493703]
我在做什么,这显然是错的?我应该最终得到2个不同的阵列,每个阵列有8个距离。
答案 0 :(得分:1)
import numpy as np
centroids = np.array([[3,44],[5,15]])
dataPoints = np.array([[2,4],[17,4],[45,2],[45,7],[16,32],[32,14],[20,56],[68,33]])
def size(vector):
return np.sqrt(sum(x**2 for x in vector))
def distance(vector1, vector2):
return size(vector1 - vector2)
def distances(array1, array2):
return [[distance(vector1, vector2) for vector2 in array2] for vector1 in array1]
print(distances(centroids, dataPoints))
答案 1 :(得分:1)
我厌倦了为1,2和3d数组进行距离计算的化身,所以我拼凑了一个模仿来自scipy的pdist和cdist的函数,但使用了很多人在这个网站上使用的einsum。至少在我的脑海里很容易理解,而且einsum用于其他目的。请考虑以下内容。如果你需要提取最接近的x值等,你可以使用然后使用排序(sort,argsort等)。希望你发现它有用
a = np.array([[1, 2], [3, 4], [5, 6]])
b = np.array([[6, 5], [4, 3], [2, 1]])
def e_dist(a, b, metric='euclidean'):
"""Distance calculation for 1D, 2D and 3D points using einsum
: a, b - list, tuple, array in 1,2 or 3D form
: metric - euclidean ('e','eu'...), sqeuclidean ('s','sq'...),
:-----------------------------------------------------------------------
"""
a = np.asarray(a)
b = np.atleast_2d(b)
a_dim = a.ndim
b_dim = b.ndim
if a_dim == 1:
a = a.reshape(1, 1, a.shape[0])
if a_dim >= 2:
a = a.reshape(np.prod(a.shape[:-1]), 1, a.shape[-1])
if b_dim > 2:
b = b.reshape(np.prod(b.shape[:-1]), b.shape[-1])
diff = a - b
dist_arr = np.einsum('ijk,ijk->ij', diff, diff)
if metric[:1] == 'e':
dist_arr = np.sqrt(dist_arr)
dist_arr = np.squeeze(dist_arr)
return dist_arr
e_dist(a, b)
array([[ 5.8, 3.2, 1.4],
[ 3.2, 1.4, 3.2],
[ 1.4, 3.2, 5.8]])
e_dist(a[0], b)
array([ 5.8, 3.2, 1.4])
e_dist(a[:2], b)
array([[ 5.8, 3.2, 1.4],
[ 3.2, 1.4, 3.2]])