我有一个(51266,20,25,3)(N,F,J,C)矩阵,其中N是示例数,F是帧号,J是关节,C是关节的xyz坐标。我想在每个示例中为每个框架计算欧几里得距离矩阵,以具有尺寸矩阵(51266,20,25,25)我的代码是
from sklearn.metrics.pairwise import euclidean_distances as euc
from tqdm import tqdm
import numpy as np
Examples = np.load('allExamples.npy')
theEuclideanMethod = np.zeros((0,20,25,25))
for example in tqdm(range(Examples.shape[0])):
euclideanBox = np.zeros((0,25,25))
for frame in range(20):
euclideanBox = np.concatenate((euclideanBox,euc(Examples[example,frame,:,:])[np.newaxis,...]),axis=0)
euclideanBox = euclideanBox[np.newaxis,...]
theEuclideanMethod = np.concatenate((theEuclideanMethod,euclideanBox))
np.save("Euclidean examples.npy",theEuclideanMethod)
print(theEuclideanMethod.shape,"Euclidean shape")
问题是我正在使用超级慢的循环。还有什么其他方法可以修改代码以使其运行更快?
这应该运行得很快。Float32用于保持较低的内存使用率,但它是可选的。调整batch_size
为更大可以提高速度,而降低则可以减少内存使用。
import numpy as np
# Adjust batch_size depending on your memory
batch_size = 500
# Make some fake data
x = np.random.randn(51266,20,25,3).astype(np.float32)
y = np.random.randn(51266,20,25,3).astype(np.float32)
# distance_matrix
d = np.empty(x.shape[:-1] + (x.shape[-2],), dtype=np.float32)
# Number of batches
N = (x.shape[0]-1) // batch_size + 1
for i in range(N):
d[i*batch_size:(i+1)*batch_size] = np.sqrt(np.sum((
x[i*batch_size:(i+1)*batch_size,:,:,None] - \
y[i*batch_size:(i+1)*batch_size,:,None,:])**2, axis=-1))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句