【发布时间】:2021-10-29 14:12:58
【问题描述】:
我有两个代理,每个代理的路径由 x 和 y 坐标定义 100 个时间步长。换句话说,单个路径的形状为(100,2)。现在代理 A 和 B 都有 1000 个唯一路径。我想在每个时间步计算所有路径组合之间的距离。换句话说,我的最终输出应该具有(1000,1000,100) 的形状。目前我使用以下方法:
import numpy as np
import time
np.random.seed(0)
N = 1000
A = np.random.rand(N,100,2)
B = np.random.rand(N,100,2)
t0 = time.time()
combinations = np.array(np.meshgrid(np.arange(N), np.arange(N)))
combinations = combinations.T.reshape(-1,2)
# Calculate distances
diff = A[combinations[:,0],:] - B[combinations[:,1],:] # Differences
distances = np.sqrt(np.einsum('ijk,ijk->ij',diff,diff)) # A bit faster than linalg norm
distances = np.reshape(distances, (N,N,100))
print('Time:', time.time() - t0)
但是,我不得不说这种方法很慢(在我的机器上大约 1.2 秒)。有没有更快的方法来做到这一点?
【问题讨论】:
-
我不清楚所提供代码的目的。除此之外,代码似乎很公平,因为
A和B是np.float64大小为(1_000_000, 100, 2)的数组,每个需要1.6 GiB。这是相当大的。 -
@JérômeRichard 它们每个只有 (1000,100,2),所以它们几乎不占用一兆字节。输出确实很大
-
抱歉,我的意思是
A[combinations[:,0],:]和B[combinations[:,1],:]。
标签: python numpy matrix combinations