PyTorch:new_ones与1

时间:2018-10-18 02:58:15

标签: pytorch

在PyTorch中,new_ones()ones()之间有什么区别。例如,

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

vs

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

2 个答案:

答案 0 :(得分:7)

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

  

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

ones()

  

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

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

答案 1 :(得分:3)

  

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将继承datatype的{​​{1}},并将在x定义的相同device上运行

x

输出:

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

ones()

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()的{​​{1}}(如示例所示)定义张量,并且不依赖于现有张量,而1.与现有张量一起使用张量从现有张量继承sizenew_ones()之类的属性,并使用给定的datatype定义device