Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用PyTorch 0.4.0从numpy数组生成requires_grad=True的FloatTensor?_Python_Numpy_Pytorch - Fatal编程技术网

Python 如何使用PyTorch 0.4.0从numpy数组生成requires_grad=True的FloatTensor?

Python 如何使用PyTorch 0.4.0从numpy数组生成requires_grad=True的FloatTensor?,python,numpy,pytorch,Python,Numpy,Pytorch,Pytorch 0.4.0引入了张量和变量类的合并 在此版本之前,当我想从numpy数组创建带有autograd的变量时,我会执行以下操作(其中x是一个numpy数组): 使用PyTorch版本0.4.0,演示了如何在启用autograd的情况下创建张量,示例显示您可以执行以下操作: x = torch.ones(3, 4, requires_grad=True) 并将requires_grad设置为现有张量 existing_tensor.requires_grad_() 我尝试了以下三

Pytorch 0.4.0引入了张量和变量类的合并

在此版本之前,当我想从numpy数组创建带有autograd的
变量时,我会执行以下操作(其中
x
是一个numpy数组):

使用PyTorch版本0.4.0,演示了如何在启用autograd的情况下创建张量,示例显示您可以执行以下操作:

x = torch.ones(3, 4, requires_grad=True) 
并将
requires_grad
设置为现有张量

existing_tensor.requires_grad_()
我尝试了以下三种方法来创建一个带有
requires_grad=True
的张量,它会给出错误(其中
x
是一个numpy数组):

首先是

x = FloatTensor(x, requires_grad=True)
这就产生了错误

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
第二是做什么

x = FloatTensor(x)
x.requires_grad()
第三是

x = torch.from_numpy(x).single()
x.requires_grad()
它们都会在第二行抛出以下错误:

TypeError: 'bool' object is not callable
这些错误给了我一点提示,说明我做错了什么,而且由于最新版本非常新,很难在网上找到帮助的内容。如何使用PyTorch 0.4.0从一个numpy数组生成一个
FloatTensor
requires\u grad=True
,最好是在单行中?

如何使用PyTorch 0.4.0从一个numpy数组生成一个requires\u grad=True的FloatTensor

如果
x
是您的numpy数组,那么这一行应该起到以下作用:

火炬张量(x,需要_grad=True) 以下是使用PyTorch 0.4.0测试的完整示例:

将numpy导入为np
进口火炬
x=np.数组([1.3,0.5,1.9,2.45])
打印('np.array:',x)
t=火炬张量(x,x=真)
print('tensor:',t)
打印('requires\u grad:',t.requires\u grad)
这将提供以下输出:

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
编辑:
dtype
应该由给定的numpy数组
x
dtype
确定


我希望这能有所帮助。

谢谢。似乎我误解了
torch.FloatTensor
的作用,我认为是
torch.tensor
的一个子类型强制了float类型。你能解释一下torch.FloatTensor的用途吗?请看一下迁移指南,它们有详细的解释。他们改变了类型。所有pytorch张量现在都是格式类型“torch.Tensor”,而不是像torch.FloatTensor这样的python数据类型。相反,您应该使用now dtype,与numpy中使用的相同。但请看一下指南,如果您还有任何问题,请提问:)
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