【发布时间】: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