maskrcnn训练自己的数据集

文章详细介绍了如何搭建MaskR-CNN的开发环境,包括conda环境创建、依赖库安装,特别是torch和torchvision的版本要求。在安装过程中遇到的错误,如setuptools版本警告、权限问题和模型权重不匹配的解决方法也进行了说明。此外,还提到了训练阶段的数据集准备、yaml配置文件修改以及处理模型训练时内存不足的策略。
摘要由CSDN通过智能技术生成

一、搭建环境

代码地址:https://github.com/facebookresearch/maskrcnn-benchmark

1、创建环境
我选择的是pthon=3.8,当低于3.8时,opencv将不满足安装条件

conda create -name maskrcnn python=3.8

2、激活环境

conda activate maskrcnn

3、this installs the right pip and dependencies for the fresh python

conda install ipython pip

4、maskrcnn_benchmark and coco api dependencies

pip install ninja yacs cython matplotlib tqdm opencv-python

如果安装速度慢或超时,可使用以下命令:

pip install ninja yacs cython matplotlib tqdm opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple

5、安装torch和torchvision
这里的版本非常关键,最终在cuda10.2+torch1.5.0+torchvision0.6.0下安装成功

6、install pycocotools

git clone https://github.com/cocodataset/cocoapi.git
cd cocoapi/PythonAPI
python setup.py build_ext install

7、install cityscapesScripts

git clone https://github.com/mcordts/cityscapesScripts.git
cd cityscapesScripts/
python setup.py build_ext install

8、install apex
如果cuda、torch的版本没有找到最佳匹配,这一部分安装会出现报错

git clone https://github.com/NVIDIA/apex.git
cd apex
python setup.py install --cuda_ext --cpp_ext

9、install PyTorch Detection

git clone https://github.com/facebookresearch/maskrcnn-benchmark.git
cd maskrcnn-benchmark
python setup.py build develop
  • 报错1
    解决方案:pip install setuptools==58.2.0
/home/liuyuxing/anaconda3/envs/maskrcnn/lib/python3.8/site-packages/setuptools/command/develop.py:40: EasyInstallDeprecationWarning: easy_install command is deprecated.
!!

        ********************************************************************************
        Please avoid running ``setup.py`` and ``easy_install``.
        Instead, use pypa/build, pypa/installer, pypa/build or
        other standards-based tools.

        See https://github.com/pypa/setuptools/issues/917 for details.
        ********************************************************************************

!!
  easy_install.initialize_options(self)
/home/liuyuxing/anaconda3/envs/maskrcnn/lib/python3.8/site-packages/setuptools/_distutils/cmd.py:66: SetuptoolsDeprecationWarning: setup.py install is deprecated.
!!

        ********************************************************************************
        Please avoid running ``setup.py`` directly.
        Instead, use pypa/build, pypa/installer, pypa/build or
        other standards-based tools.

        See https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html for details.
        ********************************************************************************

!!
  self.initialize_options()
running egg_info
error: Cannot update time stamp of directory 'maskrcnn_benchmark.egg-info'
  • 报错2
error: [Errno 13] Permission denied

解决方案sudo python setup.py build develop,若之后出现以下报错:

Traceback (most recent call last):
  File "setup.py", line 7, in <module>
    import torch
ImportError: No module named torch

终极解决方案:

#1
 which python
# 地址:/home/liuyuxing/anaconda3/envs/maskrcnn/bin/python
#2
sudo /home/liuyuxing/anaconda3/envs/maskrcnn/bin/python setup.py build develop

安装成功:
在这里插入图片描述

二、训练

1、创建自己的datasets
train2017和val2017分别存放了训练集和测试集的图片
在这里插入图片描述
2、选择.yaml文件
可以根据自己的需求选择不同文件,并记住该文件的地址:
在这里插入图片描述
3、修改.yaml文件
(1)修改权重地址
这个权重可在官方地址处下载:https://github.com/facebookresearch/maskrcnn-benchmark/blob/main/MODEL_ZOO.md
在这里插入图片描述

(2)数据集
在这里插入图片描述
4、修改训练类别数量
在这里插入图片描述在这里插入图片描述在这里插入图片描述
2是类别数,1是背景

5、数据集地址
在这里插入图片描述
6、权重文件的相关修改
由于我训练时使用了两类,若直接使用原权重文件(含81类),会产生以下报错:

size mismatch for roi_heads.box.predictor.cls_score.bias: copying a param with shape torch.Size([81]) from checkpoint, the shape in current model is torch.Size([3]).
size mismatch for roi_heads.box.predictor.cls_score.weight: copying a param with shape torch.Size([81, 1024]) from checkpoint, the shape in current model is torch.Size([3, 1024]).
size mismatch for roi_heads.box.predictor.bbox_pred.bias: copying a param with shape torch.Size([324]) from checkpoint, the shape in current model is torch.Size([12]).
size mismatch for roi_heads.box.predictor.bbox_pred.weight: copying a param with shape torch.Size([324, 1024]) from checkpoint, the shape in current model is torch.Size([12, 1024]).
size mismatch for roi_heads.mask.predictor.mask_fcn_logits.bias: copying a param with shape torch.Size([81]) from checkpoint, the shape in current model is torch.Size([32]).
size mismatch for roi_heads.mask.predictor.mask_fcn_logits.weight: copying a param with shape torch.Size([81, 256, 1, 1]) from checkpoint, the shape in current model is torch.Size([3, 256, 1, 1]).

解决方案1+2
方案1:http://t.csdn.cn/0LwDH

 import torch
 model = torch.load("e2e_mask_rcnn_X_101_32x8d_FPN_1x.pth")
 // Remove the previous training parameters. 
 del model['iteration']
 del model['scheduler']
 del model['optimizer']
 // Remove the output layers in COCO, these are the mismatched layers you saw.
 //Second stage prediction
 del model["model"]["module.roi_heads.box.predictor.cls_score.weight"]
 del model["model"]["module.roi_heads.box.predictor.cls_score.bias"]
 del model["model"]["module.roi_heads.box.predictor.bbox_pred.weight"]
 del model["model"]["module.roi_heads.box.predictor.bbox_pred.bias"]
 //mask prediction
 del model["model"]["module.roi_heads.mask.predictor.mask_fcn_logits.weight"]
 del model["model"]["module.roi_heads.mask.predictor.mask_fcn_logits.bias"]
 // RPN
 del model["model"]["module.rpn.head.cls_logits.weight"]
 del model["model"]["module.rpn.head.cls_logits.bias"]
 del model["model"]["module.rpn.head.bbox_pred.weight"]
 del model["model"]["module.rpn.head.bbox_pred.bias"]
 //save the model
 torch.save(model, "modified_model.pth")

若此时还没解决,则继续第二步
方案2:
\maskrcnn-benchmark-main\tools\train_net.py的第65行

extra_checkpoint_data = checkpointer.load(cfg.MODEL.WEIGHT)

更改为:

extra_checkpoint_data = checkpointer.load(cfg.MODEL.WEIGHT, False)

6、如何应付模型训练超过内存:
注释\maskrcnn-benchmark-main\tools\train_net.py第170行的
cfg.freeze() # cfg.freeze()使参数不能被修改
然后调整num_worksbatch_size:增加以下两句:(绿色箭头所指为新增加的两句,可以根据自己的实际情况调整这两个)
在这里插入图片描述

我曾尝试修改.yaml文件里的

DATALOADER:
    SIZE_DIVISIBILITY:1

但似乎并没不能改变bach_size.
有相关了解的同学欢迎补充

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
Mask R-CNN 是一种基于 Faster R-CNN 的目标检测算法,可以检测出物体的位置,还可以精确地分割出物体的 mask。下面是一个 Mask R-CNN 训练自己数据集的基本步骤: 1. 准备数据集 首先,您需要准备自己的数据集,包括图片和标注。图片可以是任何大小,但最好是统一大小,以便于训练。标注可以使用标准的 COCO 标注格式,包括标注文件和类别文件。 2. 定义类别 您需要定义自己数据集的类别,例如人、车、动物等等。您可以创建一个名为 `CustomConfig` 的类,继承自 `Config` 类,并在其中设置 `NUM_CLASSES` 参数为您的类别数量加 1(因为需要加入一个背景类别): ```python class CustomConfig(Config): # Give the configuration a recognizable name NAME = "custom_dataset" # Train on 1 GPU and 1 image per GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # Number of classes (including background) NUM_CLASSES = 1 + 4 # Background + 4 classes ``` 3. 定义数据集加载器 您需要定义一个数据集加载器,将准备好的数据集导入到模型中。您可以创建一个名为 `CustomDataset` 的类,继承自 `utils.Dataset` 类,并在其中实现 `load_dataset()`、`load_image()`、`load_mask()`、`image_reference()` 等方法,具体实现可以参考 Mask R-CNN 官方代码。 ```python class CustomDataset(utils.Dataset): def load_dataset(self, dataset_dir, subset): self.add_class("custom_dataset", 1, "class1") self.add_class("custom_dataset", 2, "class2") self.add_class("custom_dataset", 3, "class3") self.add_class("custom_dataset", 4, "class4") # Load annotations annotations = json.load(open(os.path.join(dataset_dir, "annotations.json"))) annotations = annotations["annotations"] # Add images and annotations to dataset for a in annotations: image_id = a["image_id"] image_path = os.path.join(dataset_dir, "images", str(image_id) + ".jpg") if not os.path.exists(image_path): continue if a["iscrowd"]: continue if a["category_id"] not in [1, 2, 3, 4]: continue self.add_image( "custom_dataset", image_id=image_id, path=image_path, width=a["width"], height=a["height"], annotations=a["bbox"] ) def load_mask(self, image_id): # Load annotations for image annotations = self.image_info[image_id]["annotations"] # Create one mask per instance masks = np.zeros([self.image_info[image_id]["height"], self.image_info[image_id]["width"], len(annotations)], dtype=np.uint8) # Load masks for i, a in enumerate(annotations): x1, y1, w, h = a x2 = x1 + w y2 = y1 + h masks[y1:y2, x1:x2, i] = 1 # Return masks and class IDs return masks, np.ones([len(annotations)], dtype=np.int32) def image_reference(self, image_id): info = self.image_info[image_id] return info["path"] ``` 4. 训练模型 在训练之前,您需要将预训练 COCO 权重加载到模型中: ```python model.load_weights(COCO_MODEL_PATH, by_name=True, exclude=["mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox", "mrcnn_mask"]) ``` 然后,您可以使用 `train()` 方法训练模型。在训练之前,您需要创建一个名为 `CustomConfig` 的配置对象,并设置好超参数和文件路径: ```python config = CustomConfig() config.display() model = modellib.MaskRCNN(mode="training", config=config, model_dir=MODEL_DIR) # Train the head branches model.train(dataset_train, dataset_val, learning_rate=config.LEARNING_RATE, epochs=30, layers='heads') ``` 5. 测试模型 在测试模型之前,您需要将模型切换到 inference 模式: ```python model = modellib.MaskRCNN(mode="inference", config=config, model_dir=MODEL_DIR) ``` 然后,您可以使用 `detect()` 方法对图片进行检测和分割: ```python results = model.detect([image], verbose=1) r = results[0] visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], class_names, r['scores']) ``` 以上就是使用 Mask R-CNN 训练自己数据集的基本步骤。具体实现可以参考 Mask R-CNN 官方代码。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值