【发布时间】:2021-01-16 01:42:33
【问题描述】:
我最近一直在处理图像转换,遇到了一个情况,我有一个大数组(形状为 100,000 x 3),其中每一行代表 3D 空间中的一个点,例如:
pnt = [x y z]
我要做的只是遍历每个点和矩阵,将每个点与称为 T(形状 = 3 X 3)的矩阵相乘。
用 Numpy 测试:
def transform(pnt_cloud, T):
i = 0
for pnt in pnt_cloud:
xyz_pnt = np.dot(T, pnt)
if xyz_pnt[0] > 0:
arr[i] = xyz_pnt[0]
i += 1
return arr
调用以下代码并计算运行时间(使用 %time)给出输出:
Out[190]: CPU times: user 670 ms, sys: 7.91 ms, total: 678 ms
Wall time: 674 ms
使用 Pytorch 张量进行测试:
import torch
tensor_cld = torch.tensor(pnt_cloud)
tensor_T = torch.tensor(T)
def transform(pnt_cloud, T):
depth_array = torch.tensor(np.zeros(pnt_cloud.shape[0]))
i = 0
for pnt in pnt_cloud:
xyz_pnt = torch.matmul(T, pnt)
if xyz_pnt[0] > 0:
depth_array[i] = xyz_pnt[0]
i += 1
return depth_array
调用以下代码并计算运行时间(使用 %time)给出输出:
Out[199]: CPU times: user 6.15 s, sys: 28.1 ms, total: 6.18 s
Wall time: 6.09 s
注意:对 torch.jit 执行相同操作只会减少 2 秒
我原以为 PyTorch 张量计算会更快,因为 PyTorch 在编译阶段分解其代码的方式。我在这里错过了什么?
除了使用 Numba 之外,还有其他更快的方法吗?
【问题讨论】:
-
Quibble:如何将形状 (3,) 的点与形状 (4,4) 的矩阵相乘?尺寸不兼容吗?
-
pytorch 是否有可能为此操作累积梯度?
-
哦,是的,我删除了第四个术语以使问题更易于理解和通用,并且忘记减小另一个矩阵的大小。我已经编辑了问题,感谢您指出 Natchiket
标签: python numpy pytorch tensor