【问题标题】:How can I make a FloatTensor with requires_grad=True from a numpy array using PyTorch 0.4.0?如何使用 PyTorch 0.4.0 从 numpy 数组中使用 requires_grad=True 制作 FloatTensor?
【发布时间】:2018-10-09 18:23:13
【问题描述】:

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

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

x = Variable(torch.from_numpy(x).float(), requires_grad=True)

在 PyTorch 版本 0.4.0 中,the migration guide 展示了我们如何在启用 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 数组中创建 FloatTensorrequires_grad=True,最好在一行中?

【问题讨论】:

    标签: python numpy pytorch


    【解决方案1】:

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

    如果 x 是您的 numpy 数组,则此行应该可以解决问题:

    torch.tensor(x, requires_grad=True)
    

    这是一个使用 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)
    

    这给出了以下输出:

    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 的子类型,它强制执行浮点类型。你能解释一下torch.FloatTensor 的用途吗?
    • 请查看迁移指南,他们有详细的解释。他们改变了类型。现在,所有 pytorch 张量都不是像 torch.FloatTensor 这样的 python 数据类型,而是表单类型“torch.Tensor”。相反,您应该使用 now dtype,与 numpy 中使用的相同。但是请看一下指南,如果您还有任何问题,请询问:)
    猜你喜欢
    • 2019-01-17
    • 2021-07-04
    • 2019-01-15
    • 2016-07-20
    • 2020-12-26
    • 2021-07-29
    • 2017-11-26
    • 2021-02-16
    • 2017-11-07
    相关资源
    最近更新 更多