gpt4 book ai didi

python - 我如何使用 PyTorch 0.4.0 从 numpy 数组制作一个带有 requires_grad=True 的 FloatTensor?

转载 作者:太空狗 更新时间:2023-10-29 20:53:07 27 4
gpt4 key购买 nike

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 数组制作一个带有 requires_grad=TrueFloatTensor,最好是在一行中?

最佳答案

我如何使用 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 确定。

希望对您有所帮助。

关于python - 我如何使用 PyTorch 0.4.0 从 numpy 数组制作一个带有 requires_grad=True 的 FloatTensor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50087252/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com