RuntimeError: _th_normal not supported on CPUType for Long

RuntimeError: _th_normal not supported on CPUType for Long

我正在尝试使用以下方法从正态分布生成一个数字:

from torch.distributions import Normal
noise = Normal(th.tensor([0]), th.tensor(3.20))
noise = noise.sample()

但是我收到这个错误:RuntimeError: _th_normal not supported on CPUType for Long

你的第一个张量 th.tensor([0]) torch.Long 类型 由于在 float 或 [=15= 时从传递的值自动推断类型] 是函数所必需的。

你可以像这样显式传递 0.0 来解决它:

import torch

noise = torch.distributions.Normal(torch.tensor([0.0]), torch.tensor(3.20))
noise = noise.sample()

更好的是,完全删除 torch.tensor,在这种情况下,如果可能,Python 类型将自动转换为 float,所以这也是有效的:

import torch

noise = torch.distributions.Normal(0, 3.20)
noise = noise.sample()

请不要将 torch 别名为 th,这不是官方的,请使用完全限定的名称,因为这只会让每个人感到困惑。