【发布时间】:2018-06-18 23:04:17
【问题描述】:
我得到了这段代码,其中距离是一个下三角矩阵,定义如下:
distance = np.tril(scipy.spatial.distance.cdist(points, points))
def make_them_touch(distance):
"""
Return the every distance where two points touched each other. See example below.
"""
thresholds = np.unique(distance)[1:] # to avoid 0 at the beginning, not taking a lot of time at all
result = dict()
for t in thresholds:
x, y = np.where(distance == t)
result[t] = [i for i in zip(x,y)]
return result
我的问题是 np.where 对于大矩阵(例如 2000*100)非常慢。
如何通过改进 np.where 或更改算法来加速此代码?
编辑:正如MaxU 指出的那样,这里最好的优化不是生成方阵并使用迭代器。
示例:
points = np.array([
...: [0,0,0,0],
...: [1,1,1,1],
...: [3,3,3,3],
...: [6,6,6,6]
...: ])
In [106]: distance = np.tril(scipy.spatial.distance.cdist(points, points))
In [107]: distance
Out[107]:
array([[ 0., 0., 0., 0.],
[ 2., 0., 0., 0.],
[ 6., 4., 0., 0.],
[12., 10., 6., 0.]])
In [108]: make_them_touch(distance)
Out[108]:
{2.0: [(1, 0)],
4.0: [(2, 1)],
6.0: [(2, 0), (3, 2)],
10.0: [(3, 1)],
12.0: [(3, 0)]}
【问题讨论】:
标签: python numpy scipy itertools