栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Pytorch预测

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Pytorch预测

本次测试输入 dog.png

# Coding by ajupyter
from PIL import Image
from torch import nn
import torch
import torchvision


class 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 output


model = 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/725793.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号