在 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.dtype
和torch.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()
用于定义具有给定size
的1.
(如示例中所示(的张量,并且不依赖于现有张量,而new_ones()
使用现有张量,该张量从现有张量继承datatype
和device
等属性,并使用给定size
定义tensor
。