首页 > 解决方案 > torch.empty_like() 是否取决于输入值和输入大小?

问题描述

torch.empty_like的火炬文档中的描述说:

torch.empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) → Tensor

返回与输入大小相同的未初始化张量。torch.empty_like(input)相当于torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)

参数
input (Tensor) – 输入的大小将决定输出张量的大小。

我要做的是:

>>> torch.empty(3,4)
tensor([[-1.8597e+15,  4.5657e-41, -1.8597e+15,  4.5657e-41],
        [ 4.4842e-44,  0.0000e+00,  8.9683e-44,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00]])

>>> c1
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])

>>> torch.empty_like(c1)
tensor([[139942262173040,  93851872482144,               1,               0],
        [              0,               0,  93851872492496,               0],
        [              0,               0,               0,               0]])

>>> d
tensor([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]])

>>> torch.empty_like(d)
tensor([[-8.6092e-25,  3.0620e-41,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00],
        [ 0.0000e+00,  0.0000e+00,  0.0000e+00,  0.0000e+00]])

似乎返回的张量torch.empty_like取决于输入值,与文档中的描述相反。有人可以解释一下吗?

标签: pythonpytorch

解决方案


文档描述是正确的。我不确定你是否torch.empty_like对在不同的调用中返回不同的输出感到困惑,但你可以看到这也是通过多次torch.empty调用的行为。torch.empty((2,3), dtype=torch.int64)

注意torch.empty_like 确实取决于dtype输入的(但不是它的具体值)。


推荐阅读