predict_pt.py 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import os
  2. import time
  3. import torch
  4. import argparse
  5. from torchvision import transforms
  6. from block.dataset_get import CustomDataset
  7. # -------------------------------------------------------------------------------------------------------------------- #
  8. parser = argparse.ArgumentParser(description='|pt模型推理|')
  9. parser.add_argument('--model_path', default='./checkpoints/Alexnet/best.pt', type=str, help='|pt模型位置|')
  10. parser.add_argument('--data_path', default='./dataset/CIFAR-10/test_cifar10_JPG', type=str, help='|验证集文件夹位置|')
  11. parser.add_argument('--input_size', default=32, type=int, help='|模型输入图片大小|')
  12. parser.add_argument('--batch', default=200, type=int, help='|输入图片批量|')
  13. parser.add_argument('--device', default='cuda', type=str, help='|推理设备|')
  14. parser.add_argument('--num_worker', default=0, type=int, help='|CPU处理数据的进程数,0只有一个主进程,一般为0、2、4、8|')
  15. parser.add_argument('--float16', default=False, type=bool, help='|推理数据类型,要支持float16的GPU,False时为float32|')
  16. args, _ = parser.parse_known_args() # 防止传入参数冲突,替代args = parser.parse_args()
  17. # -------------------------------------------------------------------------------------------------------------------- #
  18. assert os.path.exists(args.model_path), f'! model_path不存在:{args.model_path} !'
  19. assert os.path.exists(args.data_path), f'! data_path不存在:{args.data_path} !'
  20. if args.float16:
  21. assert torch.cuda.is_available(), 'cuda不可用,因此无法使用float16'
  22. # -------------------------------------------------------------------------------------------------------------------- #
  23. def predict_pt(args):
  24. # 加载模型
  25. model_dict = torch.load(args.model_path, map_location='cpu')
  26. model = model_dict['model']
  27. model.half().eval().to(args.device) if args.float16 else model.float().eval().to(args.device)
  28. epoch = model_dict['epoch_finished']
  29. accuracy = round(model_dict['standard'], 4)
  30. print(f'| 模型加载成功:{args.model_path} | epoch:{epoch} | accuracy:{accuracy} |')
  31. # 推理
  32. start_time = time.time()
  33. with torch.no_grad():
  34. print(f"加载测试集至内存...")
  35. transform = transforms.Compose([
  36. transforms.ToTensor(), # 将图像转换为PyTorch张量
  37. transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) # 标准化
  38. ])
  39. dataset = CustomDataset(data_dir=args.data_path, image_size=(args.input_size, args.input_size), transform=transform)
  40. dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=args.batch,
  41. shuffle=False, drop_last=False, pin_memory=False,
  42. num_workers=args.num_worker)
  43. print(f"加载测试集完成,开始预测...")
  44. correct = 0
  45. total = 0
  46. epoch = 0
  47. for index, (image_batch, true_batch) in enumerate(dataloader):
  48. image_batch = image_batch.to(args.device)
  49. pred_batch = model(image_batch).detach().cpu()
  50. # 获取指标项
  51. _, predicted = torch.max(pred_batch, 1)
  52. total += true_batch.size(0)
  53. correct += (predicted == true_batch).sum().item()
  54. epoch = epoch + 1
  55. # 计算指标
  56. accuracy = correct / total
  57. end_time = time.time()
  58. print(f'\n| 验证 | accuracy:{accuracy:.4f} | 图片总数:{total} | 每张耗时:{(end_time - start_time) / total} ')
  59. if __name__ == '__main__':
  60. predict_pt(args)