Pytorch预测

网友投稿 506 2022-11-05

Pytorch预测

Pytorch预测

# Coding by ajupyterfrom PIL import Imagefrom torch import nnimport torchimport torchvisionclass Model(nn.Module): def __init__(self): super(Model, self).__init__() self.model = nn.Sequential( nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2), nn.MaxPool2d(kernel_size=2), nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, stride=1, padding=2), nn.MaxPool2d(kernel_size=2), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2), nn.MaxPool2d(kernel_size=2), nn.Flatten(), nn.Linear(64 * 4 * 4, 64), nn.Linear(64, 10), ) def forward(self, x): output = self.model(x) return outputmodel = Model()model.load_state_dict(torch.load('cifa10_model-epoch19-test_loss699.5733557939529'))model.eval()with torch.no_grad(): image = Image.open('dog.png') image = image.convert('RGB') # 适配jpg和png jpg是四通道:rgb+透明度通道 tool = torchvision.transforms.Compose([ torchvision.transforms.Resize(size=(32, 32)), torchvision.transforms.ToTensor() ]) input = tool(image) input = input.reshape((1, 3, 32, 32)) print(input.shape) # torch.Size([3, 32, 32]) res = model(input) print(res) print(res.argmax(1)) # 横向比较 classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') print(f'res:{classes[res.argmax(1).item()]}') # only one element tensors can be converted to Python scalars

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Python爬虫框架,内置微博、自如、豆瓣图书、拉勾网、拼多多等爬虫
下一篇:关于MybatisPlus配置双数据库驱动连接数据库问题
相关文章

 发表评论

暂时没有评论,来抢沙发吧~