使用torch.Tensor() 創建張量,加上requires_grad參數報錯(Pytorch 1.0)

x = torch.Tensor([[.5, .3, 2.1]])
print(x)
> tensor([[0.5000, 0.3000, 2.1000]])

加上參數 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
原因

You are creating the tensor x by using the torch.Tensor class constructor which doesn’t take the requires_grad flag. Instead, you want to use torch.tensor() (lowercase ‘t’) method。

x = torch.tensor([[.5, .3, 2.1]], requires_grad=False)

或者

a = torch.Tensor([1,2])
a.requires_grad_()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章