【问题标题】:PyTorch: Error>> expected scalar type float but found doublePyTorch:错误>>预期标量类型浮点但发现双
【发布时间】:2021-08-11 05:02:57
【问题描述】:

我刚开始使用pytorch,正在尝试一个简单的多层感知器。我的 ReLU 激活函数如下:

def ReLU_activation_func(outputs):
    print(type(outputs))
    result = torch.where(outputs > 0, outputs, 0.)
    result = float(result)
    return result

所以我试图保持大于 0 的值,如果值小于 0,则将值更改为 0。 这是我使用 ReLU 函数的主要代码的一部分(我有错误):

def forward_pass(train_loader):
    for batch_idx, (image, label) in enumerate(train_loader):
        print(image.size())
        x = image.view(-1, 28 * 28)
        print(x.size())
    
        input_node_num = 28 * 28
        hidden_node_num = 100
        output_node_num = 10
        W_ih = torch.rand(input_node_num, hidden_node_num)
        W_ho = torch.rand(hidden_node_num, output_node_num)
        final_output_n = ReLU_activation_func(torch.matmul(x, W_ih))

当我运行代码时,出现以下错误:

RuntimeError:
1 forward_pass(train_loader)

in forward_pass(train_loader)
-----14         W_ih = torch.rand(input_node_num, hidden_node_num)
-----15         W_ho = torch.rand(hidden_node_num, output_node_num)
---->16         final_output_n = ReLU_activation_func(torch.matmul(x, W_ih))

in ReLU_activation_func(outputs)
-----10     print(type(outputs))
---->11     result = torch.where(outputs > 0, outputs, 0.)
-----12     result = float(result)
-----13     return result

RuntimeError: expected scalar type float but found double

有什么帮助吗?

【问题讨论】:

标签: python pytorch


【解决方案1】:

问题不在result 上,而在XW_ihtorch.where(outputs > 0, outputs, 0.) 上。

如果您没有为dtypetorch.rand() 设置参数,它将根据pytorch 的全局默认值分配dtype。

可以使用torch.set_default_tensor_type()更改全局变量。

或者走简单的路线:

def ReLU_activation_func(outputs):
    print((outputs).dtype)
    result = torch.where(outputs > 0, outputs, torch.zeros_like(outputs)).float()
    return result

# for the forward pass function, convert the tensor to floats before matmul
def forward_pass(train_loader):
    for batch_idx, (image, label) in enumerate(train_loader):
        ... <your code>
        X, W_ih = X.float(), W_ih.float()
        final_output_n = ReLU_activation_func(torch.matmul(x, W_ih))

【讨论】:

  • 我使用了您的简单路线,但随后出现此错误:“zeros_like(): argument 'input' (position 1) must be Tensor, not numpy.ndarray” at code line "result = torch.其中(输出> 0,输出,torch.zeros_like(输出)).float()“
  • 当我 print(type(outputs)) 时,它显示 , 好像输出有两种数据类型
  • 这意味着outputnumpy.array。应该使用`result = numpy.where(th.numpy() &gt; 0, th.numpy(), numpy.zeros_like(th.numpy())),如果你想输出是一个火炬张量,你可以在返回result之前添加result = torch.from_numpy(result)
  • 这解决了我的问题!非常感谢 :) 爱你
猜你喜欢
  • 1970-01-01
  • 2023-03-21
  • 2021-03-05
  • 2018-03-14
  • 2021-12-20
  • 2021-07-10
  • 2020-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多