如何在 Torch 的 GPU 上 limit/round 张量的元素到小数点后 4 位?

How to limit/round elements of a tensor to 4 decimal places on GPU in Torch?

我想知道,如何将 GPU 上张量的精度截断到所需的小数位?我想将张量中的元素限制为小数点后 4 位,但似乎 Torch 中没有内置函数可以高效且有效地执行此操作。有谁知道如何做到这一点?

将张量中的数字四舍五入仍然不是直接的,但一个简单的解决方案(适合我的目的)是将张量转换为半精度,如下所示:

require 'cutorch'

temp = torch.rand(3, 3)
temp = temp:cuda()
temp = temp:cudaHalf()

更好的解决方案肯定是先将张量转换为numpy,然后使用numpy的round函数。例如:

import torch
import numpy as np

x = torch.randn(size = (30, 10, 10)).numpy()
print(x)
x = np.round(x, 4)
print(x)

比较一下x四舍五入前和四舍五入后的打印语句。