onnx 模型中的 PyTorch 标准化

发布于 2025-01-14 06:17:52 字数 227 浏览 5 评论 0原文

我正在 pytorch 中进行图像分类,其中我使用了这个变换

transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])

并完成了训练。之后,我将 .pth 模型文件转换为 .onnx 文件

现在,在推理中,我应该如何在 numpy 数组中应用此转换,因为 onnx 处理 numpy 数组中的输入

I am doing image classification in pytorch, in that, I used this transforms

transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])

and completed the training. After, I converted the .pth model file to .onnx file

Now, in inference, how should I apply this transforms in numpy array, because the onnx handles input in numpy array

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼趣 2025-01-21 06:17:52

你有几个选择。

由于自己编写标准化非常简单,

import numpy as np
mean = np.array([0.485, 0.456, 0.406]).reshape(-1,1,1)
std = np.array([0.229, 0.224, 0.225]).reshape(-1,1,1)
x_normalized = (x - mean) / std

因此您可以完全不需要 pytorch 或 torchvision 库。

如果您仍在使用 pytorch 数据集,您可以使用以下转换

transforms.Compose([
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
    torch.Tensor.numpy  # or equivalently transforms.Lambda(lambda x: x.numpy())
])

,该转换只会将归一化应用于张量,然后将其转换为 numpy 数组。

You have a couple options.

Since normalize is pretty trivial to write yourself you could just do

import numpy as np
mean = np.array([0.485, 0.456, 0.406]).reshape(-1,1,1)
std = np.array([0.229, 0.224, 0.225]).reshape(-1,1,1)
x_normalized = (x - mean) / std

which doesn't require the pytorch or torchvision libraries at all.

If you are still using your pytorch dataset you could use the following transform

transforms.Compose([
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
    torch.Tensor.numpy  # or equivalently transforms.Lambda(lambda x: x.numpy())
])

which will just apply the normalization to the tensor then convert it to a numpy array.

伴梦长久 2025-01-21 06:17:52

您可以将相同的转换应用于np.array,例如示例

You can apply the same transforms to np.array, for example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文