如何使用PyTorch 0.4.0从numpy数组中使用requires_grad = True创建FloatTensor?

HBe*_*eel 8 python numpy pytorch

Pytorch 0.4.0引入了Tensor和Variable类的合并.

在这个版本之前,当我想Variable从一个numpy数组创建一个autograd时,我会做以下(其中x是一个numpy数组):

x = Variable(torch.from_numpy(x).float(), requires_grad=True)
Run Code Online (Sandbox Code Playgroud)

使用PyTorch版本0.4.0,迁移指南显示了我们如何创建启用了autograd的Tensors,示例显示您可以执行诸如

x = torch.ones(3, 4, requires_grad=True) 
Run Code Online (Sandbox Code Playgroud)

并设定requires_grad现有的张量

existing_tensor.requires_grad_()
Run Code Online (Sandbox Code Playgroud)

我尝试了以下三件事来尝试创建一个Tensor,requires_grad=True它给出了错误(在哪里x是一个numpy数组):

首先是

x = FloatTensor(x, requires_grad=True)
Run Code Online (Sandbox Code Playgroud)

这给出了错误

TypeError: new() received an invalid combination of arguments - got 
(numpy.ndarray, requires_grad=bool), but expected one of:
 * (torch.device device)
 * (tuple of ints size, torch.device device)
      didn't match because some of the keywords were incorrect: 
requires_grad
 * (torch.Storage storage)
 * (Tensor other)
 * (object data, torch.device device)
      didn't match because some of the keywords were incorrect: 
requires_grad
Run Code Online (Sandbox Code Playgroud)

第二是要做

x = FloatTensor(x)
x.requires_grad()
Run Code Online (Sandbox Code Playgroud)

第三是

x = torch.from_numpy(x).single()
x.requires_grad()
Run Code Online (Sandbox Code Playgroud)

哪两个都在第二行抛出以下错误:

TypeError: 'bool' object is not callable
Run Code Online (Sandbox Code Playgroud)

这些错误让我几乎没有暗示我做错了什么,而且由于最新版本是如此新颖,因此难以在线查找内容以提供帮助.如何使用PyTorch 0.4.0从一个numpy数组中创建一个FloatTensorwith requires_grad=True,最好是在一行中?

blu*_*nox 10

如何使用PyTorch 0.4.0从numpy数组中创建一个带有requires_grad = True的FloatTensor,最好是在一行中?

如果x你的numpy数组这行应该做的伎俩:

torch.tensor(x, requires_grad=True)
Run Code Online (Sandbox Code Playgroud)

以下是使用PyTorch 0.4.0测试的完整示例:

import numpy as np
import torch

x = np.array([1.3, 0.5, 1.9, 2.45])
print('np.array:', x)
t = torch.tensor(x, requires_grad=True)
print('tensor:', t)
print('requires_grad:', t.requires_grad)
Run Code Online (Sandbox Code Playgroud)

这给出了以下输出:

np.array: [1.3  0.5  1.9  2.45]
tensor: tensor([ 1.3000,  0.5000,  1.9000,  2.4500], dtype=torch.float64)
requires_grad: True
Run Code Online (Sandbox Code Playgroud)

编辑:dtype应该由dtype您的numpy数组给定x.

我希望这有帮助.