PyTorch: new_ones vs ones



在 PyTorch 中,new_ones()ones()有什么区别?例如

x2.new_ones(3,2, dtype=torch.double)

torch.ones(3,2, dtype=torch.double)

为了这个答案,我假设你的x2是先前定义的torch.Tensor。如果我们随后转到 PyTorch 文档,我们可以在new_ones()上阅读以下内容:

返回大小size填充1的张量。默认情况下, 返回的张量具有与此相同的torch.dtypetorch.device张肌。

ones()

返回一个填充标量值为 1 的张量,其形状为 由变量参数大小定义。

因此,从本质上讲,new_ones允许您在与先前存在的张量(带有 1(相同的设备和数据类型上快速创建新torch.Tensor,而ones()的目的是从头开始创建torch.Tensor(填充一个(。

new_ones((

# defining the tensor along with device to run on. (Assuming CUDA hardware is available)
x = torch.rand(5, 3, device="cuda")

new_ones()适用于现有张量。y将从x继承datatype,并将在与x中定义的相同device上运行

y = x.new_ones(2, 2)
print(y)

输出:

tensor([[1., 1.],
[1., 1.]], device='cuda:0')

一((

# defining tensor. By default it will run on CPU.
x = torch.ones(5, 3)
print(x)

输出:

tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])

ones()用于定义具有给定size1.(如示例中所示(的张量,并且不依赖于现有张量,而new_ones()使用现有张量,该张量从现有张量继承datatypedevice等属性,并使用给定size定义tensor

最新更新