【问题标题】:RuntimeError: Only Tensors of floating point dtype can require gradientsRuntimeError:只有浮点 dtype 的张量才能需要渐变
【发布时间】:2020-04-13 11:22:31
【问题描述】:

RuntimeError: 只有浮点 dtype 的张量可以需要渐变

收到以下错误

输入 = 变量(preprocessed_img, requires_grad = True)

img=train_loader.dataset.data[0]
print(type(img))
img_tensor = torch.tensor(img)
preprocess_image(img)

> def preprocess_image(img):    means=[0.485, 0.456, 0.406]     stds=[0.229,
> 0.224, 0.225]
> 
>   preprocessed_img = img.copy()[: , :, ::-1]  for i in range(3):
>       preprocessed_img[:, :, i] = preprocessed_img[:, :, i] - means[i]
>       preprocessed_img[:, :, i] = preprocessed_img[:, :, i] / stds[i]
>   preprocessed_img = \
>       np.ascontiguousarray(np.transpose(preprocessed_img, (2, 0, 1)))
>   preprocessed_img = torch.from_numpy(preprocessed_img)
>   preprocessed_img.unsqueeze_(0)  input = Variable(preprocessed_img,
> requires_grad = True)     return input

【问题讨论】:

  • 你应该在使用torch.tensor时指定类型。如果您使用 torch.Tensor,框架会直接推断类型,因此在 Ashish 的答案下方也应该可以工作

标签: pytorch


【解决方案1】:

使用torch.Tensor(img) 代替torch.tensor(img)。这应该可以解决您的问题。

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 2021-11-11
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2019-04-28
    相关资源
    最近更新 更多