如何仅将字典中的值选择/格式化为列表或numpy数组? [英] How I select/format only the values from a dictionary into a list or numpy array?
问题描述
如何获取仅打印平均值的列表? 我只需要它与我的np完全相同的格式 数组,以便我可以比较它们是否相同.
How do I get it to print just a list of the averages? I just need it to be the exact same format as my np arrays so I can compare them to see if they are the same or not.
代码:
import numpy as np
from pprint import pprint
centroids = np.array([[3,44],[4,15],[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):
lists = [[distance(vector1, vector2) for vector2 in array2] for vector1 in array1]
#print lists.index(min, zip(*lists))
smallest = [min(zip(l,range(len(l)))) for l in zip(*lists)]
clusters = {}
for j, (_, i) in enumerate(smallest):
clusters.setdefault(i,[]).append(dataPoints[j])
pprint (clusters)
print'\nAverage of Each Point'
avgDict = {}
for k,v in clusters.iteritems():
avgDict[k] = sum(v)/ (len(v))
avgList = np.asarray(avgDict)
pprint (avgList)
distances(centroids,dataPoints)
当前输出:
{0: [array([16, 32]), array([20, 56])],
1: [array([2, 4])],
2: [array([17, 4]),
array([45, 2]),
array([45, 7]),
array([32, 14]),
array([68, 33])]}
Average of Each Point
array({0: array([18, 44]), 1: array([2, 4]), 2: array([41, 12])}, dtype=object)
所需的输出:
[[18,44],[2,4],[41,12]]
或者是比较我的阵列/列表的最佳格式.我知道我应该只使用一种数据类型.
Or whatever the best format to compare my arrays/lists. I am aware I should have just stuck with one data type.
推荐答案
您是否尝试通过最接近的centroids
的索引对dataPoints
进行聚类,并找出聚类点的平均位置?如果是这样,我建议您使用一些numpy广播规则来获取所需的输出.
Do you try to cluster the dataPoints
by the index of the nearest centroids
, and find out the average position of the clustered points? If it is, I advise to use some broadcast rules of numpy to get the output you need.
考虑这个
np.linalg.norm(centroids[None, :, :] - dataPoints[:, None, :], axis=-1)
它创建一个矩阵,显示dataPoints
和centroids
之间的所有距离,
It creates a matrix showing all distances between dataPoints
and centroids
,
array([[ 40.01249805, 11.18033989, 11.40175425],
[ 42.3792402 , 17.02938637, 16.2788206 ],
[ 59.39696962, 43.01162634, 42.05948169],
[ 55.97320788, 41.77319715, 40.79215611],
[ 17.69180601, 20.80865205, 20.24845673],
[ 41.72529209, 28.01785145, 27.01851217],
[ 20.80865205, 44.01136217, 43.65775991],
[ 65.9241989 , 66.48308055, 65.520989 ]])
您可以通过此技巧计算最接近的质心的索引(为了便于阅读,它们分为3行),
And you can compute the indices of the nearest centroids by this trick (they are split into 3 lines for readability),
In: t0 = centroids[None, :, :] - dataPoints[:, None, :]
In: t1 = np.linalg.norm(t0, axis=-1)
In: t2 = np.argmin(t1, axis=-1)
现在t2
具有索引,
array([1, 2, 2, 2, 0, 2, 0, 2])
要找到#1群集,请使用布尔掩码t2 == 0
To find the #1 cluster, use the boolean mask t2 == 0
,
In: dataPoints[t2 == 0]
Out: array([[16, 32],
[20, 56]])
In: dataPoints[t2 == 1]
Out: array([[2, 4]])
In: dataPoints[t2 == 2]
Out: array([[17, 4],
[45, 2],
[45, 7],
[32, 14],
[68, 33]])
或者只是根据您的情况计算平均值,
Or just calculate the average in your case,
In: np.mean(dataPoints[t2 == 0], axis=0)
Out: array([ 18., 44.])
In: np.mean(dataPoints[t2 == 1], axis=0)
Out: array([ 2., 4.])
In: np.mean(dataPoints[t2 == 2], axis=0)
Out: array([ 41.4, 12. ])
当然,如果需要,可以在for循环中重写后面的块.
Of course, the latter blocks can be rewritten in for-loop if you want.
在我看来,按照numpy的惯例来制定解决方案可能是一个好习惯.
It might be a good practice to formulate the solution by numpy's conventions in my opinion.
这篇关于如何仅将字典中的值选择/格式化为列表或numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!