【问题标题】:Resizing image in pytorch to match the dimensions of the model does not work在 pytorch 中调整图像大小以匹配模型的尺寸不起作用
【发布时间】:2022-09-29 05:29:36
【问题描述】:

我得到一个尺寸不匹配错误当我在模型上运行预测器时,即使训练、验证和测试工作。我想这意味着预测模型中的图像处理存在问题。

class Predictor(nn.Module):

    def __init__(self, model, class_names, mean, std):
        super().__init__()

        self.model = model.eval()
        self.class_names = class_names
        
        self.transforms = nn.Sequential( # --- THIS MIGHT BE THE PROBLEM
            T.Resize([256, ]),
            T.CenterCrop(224),
            T.ConvertImageDtype(torch.float),
            T.Normalize(mean.tolist(), std.tolist())
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        with torch.no_grad():
            # Apply transforms --- THIS MIGHT BE THE PROBLEM TOO
            x  = self.transforms(x)

            # Get the logits
            x  = self.model(x)

            # Apply softmax
            x  = F.softmax(x, dim=1)

            return x

我尝试硬编码model 类的输入神经元的维度,它确实工作了几秒钟,然后我得到另一个维度不匹配。

例如,在训练时,模型的输入神经元是128*7*7,然后我将其硬编码为57600,因为这是引发错误的输入维度。它在预测过程中确实适用于 26 张图像,但随后它引发了另一个维度不匹配错误,另一个维度为 51200

这确实意味着传递给模型的图像尺寸不一致!

这也意味着self.transforms(...) 不起作用,因为如果它起作用,就不会有尺寸不匹配

  • 您是否进行了健全性测试以确保调整大小功能不起作用?即找到破坏您的代码的输入图像,然后从那里进行调试。
  • 检查转换后图像的尺寸(例如,这可以通过添加打印语句来完成)。
  • 会尝试这样做,我会尽快更新问题

标签: python deep-learning pytorch conv-neural-network torch


【解决方案1】:

我可以通过强制使用硬编码的T.Compose([..., T.CenterCrop(224), ...]) 转换插入模型的数据来解决错误,以确保图像本身已插入模型裁剪就绪。

但是,我仍然不明白为什么以下内容不能解决该错误

self.transforms = nn.Sequential(T.Resize([256, ]),
                                T.CenterCrop(224),
                                T.ConvertImageDtype(torch.float),
                                T.Normalize(mean.tolist(), std.tolist()))

使用224*224 调用模型本身可以消除错误,但模型不接受任何其他维度,因为它会引发维度错误

【讨论】:

    猜你喜欢
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    相关资源
    最近更新 更多