在网络上下载图片,然后使用训练好的模型进行测试,查看预测结果。
文中所有模型(test_1.pth)为前文保存的网络模型
import torch
import torchvision
from PIL import Image
from torch import nn
image_path = "dog.png"
image = Image.open(image_path)
print(image)
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32, 32)), torchvision.transforms.ToTensor()])
class Test(nn.Module):
def __init__(self):
super(Test, 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
#在cpu上使用GPU的训练模型时要指定训练模型
model = torch.load("test_1.pth", map_location=torch.device('cpu'))
image = torch.reshape(image, (1, 3, 32, 32))
model = eval()
with torch.no_grad():
output = model(image)
print(output.argmax(1))