Pytorch 初学者:tensor.new 方法

Pytorch beginner : tensor.new method

各位,我有一个小问题。

Pytorch中tensor.new(..)方法的作用是什么,我在文档中没有找到任何内容。看起来它创建了一个新的张量(顾名思义),但为什么我们不只使用 torch.Tensor 构造函数而不是使用需要现有张量的这种新方法。

提前致谢。

我找到了答案。它用于创建一个新的相同类型的张量。

正如 tensor.new() 的文档所说:

Constructs a new tensor of the same data type as self tensor.

另请注意:

For CUDA tensors, this method will create new tensor on the same device as this tensor.

这是一个使用 new() 的简单用例和示例,因为如果没有这个,这个函数的实用性不是很清楚。

假设您想在不知道先验数据类型的情况下将高斯噪声添加到张量(或变量)。

这将创建一个高斯噪声张量,其形状和数据类型与变量相同X:

 noise_like_grad = X.data.new(X.size()).normal_(0,0.01)

这个例子也说明了new(size)的用法,这样我们就得到了和X.

同类型同大小的tensor

似乎在较新版本的 PyTorch 中有许多不同的 new_* 方法旨在取代此 "legacy" new 方法。

因此,如果您有一些张量 t = torch.randn((3, 4)),那么您可以根据您的目标,使用以下方法之一构造一个具有相同类型和设备的新张量:

t = torch.randn((3, 4))
a = t.new_tensor([1, 2, 3])  # same type, device, new data
b = t.new_empty((3, 4))      # same type, device, non-initialized
c = t.new_zeros((2, 3))      # same type, device, filled with zeros
... 
for x in (t, a, b, c):
    print(x.type(), x.device, x.size())
# torch.FloatTensor cpu torch.Size([3, 4])
# torch.FloatTensor cpu torch.Size([3])
# torch.FloatTensor cpu torch.Size([3, 4])
# torch.FloatTensor cpu torch.Size([2, 3])