关于pytorch:深度学习-preprocess-预处理图片方式去-pytorch-化

6次阅读

共计 948 个字符,预计需要花费 3 分钟才能阅读完成。

我的模型须要线上部署了,想间接应用 onnx,而不是 pytorch,所以我须要把代码中对于 pytorch 的都删除了,比方上面这段代码,怎么应用其余库代替?

from torchvision import transforms


preprocess = transforms.Compose([transforms.Resize(224),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225]
    )
])

上面是 ChatGPT 给我的答案:

能够应用 Pillow 和 numpy 库代替 torchvision 和 torch 中的操作,示例代码如下:

from PIL import Image
import numpy as np

def preprocess(image_path):
    image = Image.open(image_path)
    image = image.resize((224, 224))
    image = np.array(image)
    image = image.transpose((2, 0, 1))
    image = image.astype(np.float32)
    image /= 255.0
    mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
    std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
    image = (image - mean) / std
    return image

这个函数将承受图像文件门路作为输出并返回预处理后的图像。


然而我测速发现,chatGPT 给的这段代码速度慢了 50%

╰─➤  time python pre001.py
python pre001.py  10.29s user 0.98s system 118% cpu 9.502 total
╰─➤  time python pre002.py
python pre002.py  15.91s user 0.99s system 111% cpu 15.185 total

能够看到新版的比原版的慢 50%,所以这个思路失败了


对于这两个形式是否可能利用多核 CPU,我发现都是不行的

正文完
 0