Pytorch学习笔记:最简单的推理网络组成(from tudui)

文章目录

  • 前言
    • 1.引入库
    • 2.读取数据
    • 3.数据处理(totensor,resize)
    • 4.重载网络模型和训练好的参数
    • 5.输入图片给模型


前言

摘要:最简单的推理网络组成(from tudui)

代码如下(示例):

1.引入库

import torch
import torchvision
from PIL import Image
from torch import nn

2.读取数据

image_path = "../imgs/airplane.png"
image = Image.open(image_path)
print(image)
image = image.convert('RGB')

3.数据处理(totensor,resize)

transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32, 32)),
                                            torchvision.transforms.ToTensor()])
image = transform(image)
print(image.shape)

4.重载网络模型和训练好的参数

class Tudui(nn.Module):
    def __init__(self):
        super(Tudui, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(64*4*4, 64),
            nn.Linear(64, 10)
        )

    def forward(self, x):
        x = self.model(x)
        return x

model = torch.load("tudui_29_gpu.pth", map_location=torch.device('cpu'))
print(model)

5.输入图片给模型

image = torch.reshape(image, (1, 3, 32, 32))
model.eval()
with torch.no_grad():
    output = model(image)
print(output)

你可能感兴趣的:(Pytorch学习笔记,pytorch,学习,深度学习)