带有 requires_grad 参数的 torch.Tensor()

u2g*_*les 2 python pytorch tensor

我不能使用带有 requires_grad 参数的 torch.Tensor()(火炬版本:0.4.1)

没有 requires_grad :

x = torch.Tensor([[.5, .3, 2.1]])
print(x)
> tensor([[0.5000, 0.3000, 2.1000]])
Run Code Online (Sandbox Code Playgroud)

使用 requires_grad=True 或 requires_grad=False :

x = torch.Tensor([[.5, .3, 2.1]], requires_grad=False)
print(x)
Traceback (most recent call last):
  File "D:/_P/dev/ai/pytorch/notes/tensor01.py", line 4, in <module>
    x = torch.Tensor([[.5, .3, 2.1]], requires_grad=False)
TypeError: new() received an invalid combination of arguments - got (list, requires_grad=bool), but expected one of:
 * (torch.device device)
 * (torch.Storage storage)
 * (Tensor other)
 * (tuple of ints size, torch.device device)
      didn't match because some of the keywords were incorrect: requires_grad
 * (object data, torch.device device)
      didn't match because some of the keywords were incorrect: requires_grad
Run Code Online (Sandbox Code Playgroud)

小智 6

您正在x使用torch.Tensor不带requires_grad标志的类构造函数创建张量。相反,您想使用torch.tensor()(小写 't') 方法

x = torch.tensor([[.5, .3, 2.1]], requires_grad=False)
Run Code Online (Sandbox Code Playgroud)

编辑:添加到文档的链接:torch.Tensor