19.predict

预测阶段大致步骤:

打开图片:[指定路径],[PIL打开]

转换图片:[RGB],[resize,totensor]

调用训练模型:[torch.load]

预测

输出结果:[argmax(1)]

要注意的是:

CUDA训练好的模型,预测时:1,device为cpu,调用时映射到cpu上

  1. 2devicegpu,将输入图片转化为CUDA类型
  1. # 1
  2. model = torch.load("pretrained_demo_10.pth",map_location=torch.device("cpu"))
  3. # 2
  4. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  5. # img = transform(img)后
  6. img = img.to(device)
  7. # or
  8. output = model(img.to(device))

预测结果为:dog √
image.png

code

  1. import torch
  2. import torchvision
  3. from PIL import Image
  4. # GPU训练的模型,测试时也要使用GPU
  5. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  6. # 打开测试图片
  7. image_path = "./img/dog.png"
  8. img = Image.open(image_path)
  9. # 很多截图软件截图是三通道外加一个透明通道, 所以转换一下
  10. img = img.convert("RGB")
  11. # resize and totensor
  12. transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32, 32)),
  13. torchvision.transforms.ToTensor()])
  14. img = transform(img)
  15. # img = img.to(device)必须加在这里 或使用output = model(img.to(device))
  16. # >>torch.Size([3, 32, 32])
  17. # 调用训练好的模型
  18. model = torch.load("pretrained_demo_10.pth")
  19. #model = torch.load("pretrained_demo_10.pth",map_location=torch.device("cpu"))
  20. # print(model)
  21. # 模型接收是4维 所以reshape增加一个batch_size维度
  22. img = torch.reshape(img,(1,3,32,32))
  23. # 测试
  24. model.eval()
  25. with torch.no_grad():
  26. output = model(img.to(device))
  27. #output = model(img)
  28. # 每个类别的得分
  29. print(output)
  30. # 输出预测类别
  31. print(output.argmax(1))