接外包,有相关需求的可以联系我:Telegram | Email

如何使用训练好的PyTorch图像分类器模型

该文章创建(更新)于11/2/2020,请注意文章的时效性!

缘由

最近无聊就来尝试跑跑图片分类的模型,发现模型优化真的是一件挺重要的事情。但突然想到我们一直都是训练,怎么使用呢?就找到了方法!

思路

读取图片并将图片转化成和训练数据一样的格式

#-*-coding:utf-8-*-
import torch
from torchvision import transforms
from PIL import Image

img_path = "./trunk.jpeg"  


transform1 = transforms.Compose([
    transforms.CenterCrop((32,32)), # 只能对PIL图片进行裁剪
    transforms.ToTensor()
    ]
)

## PIL图片与Tensor互转
img_PIL = Image.open(img_path).convert('RGB')
# img_PIL.show() # 原始图片

img_PIL = img_PIL.resize((32,32),Image.NEAREST)
img_PIL.show()

img_PIL_Tensor = transform1(img_PIL)
print(type(img_PIL))
print(type(img_PIL_Tensor))

用模型获取结果

# 恢复模型并测试
net = Net()
net.load_state_dict(torch.load(PATH))

inputs = img_PIL_Tensor.unsqueeze(0)

new_outputs = net(inputs)


_, new_predicted = torch.max(new_outputs, 1)
print(classes[new_predicted])

总代码

#-*-coding:utf-8-*-
#-*-coding:utf-8-*-
import torch
from torchvision import transforms
from PIL import Image

img_path = "./trunk.jpeg"  


transform1 = transforms.Compose([
    transforms.CenterCrop((32,32)), # 只能对PIL图片进行裁剪
    transforms.ToTensor()
    ]
)

## PIL图片与Tensor互转
img_PIL = Image.open(img_path).convert('RGB')
# img_PIL.show() # 原始图片

img_PIL = img_PIL.resize((32,32),Image.NEAREST)
img_PIL.show()

img_PIL_Tensor = transform1(img_PIL)
print(type(img_PIL))
print(type(img_PIL_Tensor))

# 恢复模型并测试
net = Net()
net.load_state_dict(torch.load(PATH))

inputs = img_PIL_Tensor.unsqueeze(0)

new_outputs = net(inputs)


_, new_predicted = torch.max(new_outputs, 1)
print(classes[new_predicted])


其他


要不赞赏一下?

微信
支付宝
PayPal
Bitcoin

版权声明 | Copyright

除非特别说明,本博客所有作品均采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。转载请注明转自-
https://www.emperinter.info/2020/11/02/how-to-use-a-trained-pytorch-image-classifier-model/


要不聊聊?

我相信你准备留下的内容是经过思考的!【勾选防爬虫,未勾选无法留言】

*

*



YouTube | B站

微信公众号

优惠码

阿里云国际版20美元
Vultr10美元
搬瓦工 | Bandwagon应该有折扣吧?
Just My SocksJMS9272283 【注意手动复制去跳转】
域名 | namesiloemperinter(1美元)
币安 币安