code: def main(parser_data):
      device = torch.device(
          parser_data.device if torch.cuda.is_available() else "cpu"
      )
      print("Using {} device training.".format(device.type))
  
      data_transform = {
          "val": transforms.Compose([transforms.ToTensor()])
      }
  
      # read class_indict
      label_json_path = "./coco91_indices.json"
      assert os.path.exists(
          label_json_path
      ), "json file {} dose not exist.".format(label_json_path)
      with open(label_json_path, "r") as f:
          category_index = json.load(f)
  
      coco_root = parser_data.data_path
  
      # 注意这里的collate_fn是自定义的，因为读取的数据包括image和targets，不能直接使用默认的方法合成batch
      batch_size = parser_data.batch_size
      nw = min(
          [os.cpu_count(), batch_size if batch_size > 1 else 0, 8]
      )  # number of workers
      print("Using %g dataloader workers" % nw)
  
      # load validation data set
      val_dataset = CocoDetection(
          coco_root, "val", data_transform["val"]
      )
      val_dataset_loader = torch.utils.data.DataLoader(
          val_dataset,
          batch_size=batch_size,
          shuffle=False,
          pin_memory=True,
          num_workers=nw,
          collate_fn=val_dataset.collate_fn,
      )
  
      # create model
      res50 = resnet50()
      backbone = create_feature_extractor(
          res50, return_nodes={"layer3": "0"}
      )
      backbone.out_channels = 1024
  
      anchor_generator = AnchorsGenerator(
          sizes=((32, 64, 128, 256, 512),),
          aspect_ratios=((0.5, 1.0, 2.0),),
      )
  
      roi_pooler = torchvision.ops.MultiScaleRoIAlign(
          featmap_names=["0"],  # 在哪些特征层上进行roi pooling
          output_size=[7, 7],  # roi_pooling输出特征矩阵尺寸
          sampling_ratio=2,
      )  # 采样率
  
      # num_classes equal 80 + background classes
      model = FasterRCNN(
          backbone=backbone,
          num_classes=parser_data.num_classes + 1,
          rpn_anchor_generator=anchor_generator,
          box_roi_pool=roi_pooler,
      )
  
      # 载入你自己训练好的模型权重
      weights_path = parser_data.weights_path
      assert os.path.exists(weights_path), "not found {} file.".format(
          weights_path
      )
      weights_dict = torch.load(weights_path, map_location="cpu")
      weights_dict = (
          weights_dict["model"]
          if "model" in weights_dict
          else weights_dict
      )
      model.load_state_dict(weights_dict)
      # print(model)
  
      model.to(device)
  
      # evaluate on the val dataset
      cpu_device = torch.device("cpu")
  
      det_metric = EvalCOCOMetric(
          val_dataset.coco, "bbox", "det_results.json"
      )
      model.eval()
      with torch.no_grad():
          for image, targets in tqdm(
              val_dataset_loader, desc="validation..."
          ):
              # 将图片传入指定设备device
              image = list(img.to(device) for img in image)
  
              # inference
              outputs = model(image)
              outputs = [
                  {k: v.to(cpu_device) for k, v in t.items()}
                  for t in outputs
              ]
              det_metric.update(targets, outputs)
  
      det_metric.synchronize_results()
      det_metric.evaluate()
  
      # calculate COCO info for all classes
      coco_stats, print_coco = summarize(det_metric.coco_evaluator)
  
      # calculate voc info for every classes(IoU=0.5)
      voc_map_info_list = []
      classes = [v for v in category_index.values() if v != "N/A"]
      for i in range(len(classes)):
          stats, _ = summarize(det_metric.coco_evaluator, catId=i)
          voc_map_info_list.append(
              " {:15}: {}".format(classes[i], stats[1])
          )
  
      print_voc = "\n".join(voc_map_info_list)
      print(print_voc)
  
      # 将验证结果保存至txt文件中
      with open("record_mAP.txt", "w") as f:
          record_lines = [
              "COCO results:",
              print_coco,
              "",
              "mAP(IoU=0.5) for each category:",
              print_voc,
          ]
          f.write("\n".join(record_lines))
  
file_path: deep-learning-for-image-processing/pytorch_object_detection/train_coco_dataset/validation.py
imports: import os
  import json
  import torch
  import torchvision
  from tqdm import tqdm
  import numpy
  from torchvision.models.feature_extraction import create_feature_extractor
  import transforms
  from network_files import FasterRCNN, AnchorsGenerator
  from my_dataset import CocoDetection
  from backbone import resnet50
  from train_utils import EvalCOCOMetric
label_desc: Use image node_id 2 for calling a global function with example usage: main(parser_data) without return types