【问题标题】:How to save Detectron2 model as a vanilla pytorch model?如何将 Detectron2 模型保存为 vanilla pytorch 模型?
【发布时间】:2022-10-09 17:31:10
【问题描述】:

我有一个用Detectron2 训练的Faster-RCNN 模型。模型权重保存为model.pth

我有我的config.yml 文件,有几种方法可以加载这个模型:

from detectron2.modeling import build_model
from detectron2.checkpoint import DetectionCheckpointer

cfg = get_cfg()
config_name = "config.yml" 
cfg.merge_from_file(config_name)

cfg.MODEL.WEIGHTS = './model.pth'
model = DefaultPredictor(cfg)

OR

model_ = build_model(cfg) 
model = DetectionCheckpointer(model_).load("./model.pth")

此外,您可以通过 given in official documentation 单独从该模型中获得预测:

image = np.array(Image.open('page4.jpg'))[:,:,::-1] # RGB to BGR format
tensor_image = torch.from_numpy(image.copy()).permute(2, 0, 1) # B, channels, W, H


with torch.no_grad():
    output = torch_model([{"image":tensor_image}])

运行以下命令:

print(type(model))
print(type(model.model))
print(type(model.model.backbone))

给你:

<class 'detectron2.engine.defaults.DefaultPredictor'>
<class 'detectron2.modeling.meta_arch.rcnn.GeneralizedRCNN'>
<class 'detectron2.modeling.backbone.fpn.FPN'>

问题:我想使用GradCam for model explainability,它使用pytorch模型作为given in this tutorial

我怎样才能把detectron2 模型变成香草pytorch 模型?

我努力了:

torch.save(model.model.state_dict(), "torch_weights.pth")
torch.save(model.model, "torch_model.pth")


from torchvision.models.detection import fasterrcnn_resnet50_fpn

dummy = fasterrcnn_resnet50_fpn(pretrained=False, num_classes=1)
# dummy.load_state_dict(torch.load('./model.pth', map_location = 'cpu')) 
dummy.load_state_dict(torch.load('./torch_weights.pth', map_location = 'cpu')) 

但显然,由于图层名称和大小等不同,我会遇到错误。

我也试过:

class TorchModel(torch.nn.Module):
    def __init__(self, model) -> None:
        super().__init__()
        self.model = model.model
    
    def forward(self, image):
        return self.model([{"image":image}])[0]['instances']

但它不适用于.backbone.layers

【问题讨论】:

    标签: python deep-learning pytorch torch detectron


    【解决方案1】:

    看起来笔记本 here 完全专注于将 GradCam 用于 Faster-RCNN 模型,因此摘要 here 基本上应该适合您。 (我无法在我的 M1 Mac 上进行detectron2 推理,因此无法检查AblationCam,但我能够运行不需要标签和框的EigenCam 代码。)

    import cv2
    from pytorch_grad_cam import AblationCAM, EigenCAM
    from pytorch_grad_cam.ablation_layer import AblationLayerFasterRCNN
    from pytorch_grad_cam.utils.model_targets import FasterRCNNBoxScoreTarget
    from pytorch_grad_cam.utils.reshape_transforms import fasterrcnn_reshape_transform
    from pytorch_grad_cam.utils.image import show_cam_on_image, scale_accross_batch_and_channels, scale_cam_image
    
    # I have modified the code there slightly
    im = cv2.imread("input.jpg")
    outputs = model(im)
    labels, boxes = outputs["instances"].pred_classes, outputs["instances"].pred_boxes
    
    targets = [FasterRCNNBoxScoreTarget(labels=labels, bounding_boxes=boxes)]
    target_layers = [model.model.backbone]
    cam = AblationCAM(model.model,
                      target_layers, 
                      use_cuda=torch.nn.cuda.is_available(), 
                      reshape_transform=fasterrcnn_reshape_transform,
                      ablation_layer=AblationLayerFasterRCNN(),
                      ratio_channels_to_ablate=1.0)
    
    # or a very fast alternative
    
    cam = EigenCAM(model.model,
                  target_layers, 
                  use_cuda=torch.nn.cuda.is_available(), 
                  reshape_transform=fasterrcnn_reshape_transform)
    

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 2021-05-08
      • 2022-09-26
      • 2020-12-20
      • 2020-08-25
      • 1970-01-01
      • 2021-12-15
      • 2019-09-26
      • 2020-10-17
      相关资源
      最近更新 更多