完整代码:
import torch
import torchvision
from PIL import Image
from torch import nn
image_path = "../imgs/dog.png"
image = Image.open(image_path)
print(image)
# 因为png格式是四个通道,除了RGB三通道外,还有一个透明度通道
image = image.convert("RGB")
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),
torchvision.transforms.ToTensor()])
image = transform(image)
print(image.shape)
class MyNN(nn.Module):
def __init__(self):
super(MyNN, 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("mynn_0.pth")
print(model)
image = torch.reshape(image,(1,3,32,32))
model.eval()
with torch.no_grad():
output = model(image.cuda())
print(output)
print(output.argmax(1))
采用GPU训练的模型,两种方法
(1)在CPU上加载,要从GPU映射到CPU,即把model = torch.load("mynn_9.pth")改为:
model = torch.load("mynn_9.pth",map_location=torch.device('cpu'))
(2)将image转到GPU中,即把output = model(image)改为:
output = model(image.cuda())
文章来源地址https://www.toymoban.com/news/detail-667290.html
预测错误的原因可能是训练次数不够多
改成:
model = torch.load("mynn_9.pth")
文章来源:https://www.toymoban.com/news/detail-667290.html
到了这里,关于PyTorch学习笔记(十七)——完整的模型验证(测试,demo)套路的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!