You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch Normalize报错:输入为torch.float32却被识别为torch.int32

问题

处理NYU v2深度数据集时,应用以下图像变换代码:

def standard_transform(normalise=False):
    composition = [
        transforms.Resize(standard_img_HW()),
        transforms.ToTensor(),
    ]
    if normalise:
        composition.append(transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
    return transforms.Compose(composition)

运行时触发以下错误:

TypeError(f"Input tensor should be a float tensor. Got {tensor.dtype}.")
TypeError: Input tensor should be a float tensor. Got torch.int32.

但已确认输入的深度图是torch.float32类型张量:

tensor([[[2.7520, 2.7520, 2.7522,  ..., 2.2429, 2.2428, 2.2428],
         [2.7519, 2.7520, 2.7521,  ..., 2.2429, 2.2428, 2.2427],
         [2.7518, 2.7518, 2.7520,  ..., 2.2428, 2.2427, 2.2427],
         ...,
         [2.1980, 2.1980, 2.1979,  ..., 2.0813, 2.0810, 2.0809],
         [2.1979, 2.1979, 2.1977,  ..., 2.0816, 2.0813, 2.0812],
         [2.1979, 2.1978, 2.1977,  ..., 2.0817, 2.0814, 2.0813]]])
torch.Size([1, 480, 640])
torch.float32

已确认输入是张量而非图像,且多次检查张量类型为float,求解决方法。

解决方案
  • 移除变换链中的transforms.ToTensor():输入已经是张量,ToTensor()会将其当作PIL图像处理,把原本的float深度值强制转换为int32类型,直接触发类型错误。修改后的变换函数:
def standard_transform(normalise=False):
    composition = [
        transforms.Resize(standard_img_HW()),
    ]
    if normalise:
        # 深度图为单通道,需将归一化参数改为单通道对应值
        composition.append(transforms.Normalize((0.5,), (0.5,)))
    return transforms.Compose(composition)
  • 校验standard_img_HW()返回格式:确保它返回(height, width)顺序的元组,符合transforms.Resize对输入张量的要求。
  • 显式锁定张量类型:若问题仍存在,在应用变换前手动确认张量类型:
depth_tensor = depth_tensor.to(torch.float32)

内容的提问来源于stack exchange,提问作者Sam Y

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 07:52:49