作者|Aakarsh Yelisetty
编译|Flin
起源|towardsdatascience
让咱们看看如何在波及文本辨认的自定义数据集上应用FAIR(Facebook AI Research)的Detectron 2进行实例检测。
你是否尝试过应用你本人抉择的自定义数据集从头开始训练对象检测模型?
如果是的话,你就会晓得这个过程有多乏味。如果咱们抉择基于区域倡议的办法,如更快的R-CNN,或者咱们也能够应用SSD和YOLO等一次性检测器算法,咱们须要从应用特色金字塔网络和区域倡议网络来构建模型。
如果咱们想从头开始实现的话,它们中的任何一个都有点简单。咱们须要一个框架,在这个框架中,咱们能够应用最先进的模型,例如Fast,Faster和Mask R-CNN。然而,重要的是咱们须要从头开始构建一个模型,以了解其背地的数学原理。
如果咱们想应用自定义数据集疾速训练对象检测模型,Detectron 2就能够提供帮忙。Detectron 2库的模型库中存在的所有模型都在COCO Dataset上进行了预训练。咱们只须要在事后训练的模型上微调咱们的自定义数据集。
Detectron 2齐全重写了2018年公布的第一款Detectron。其前身是在Caffe2上编写的,Caffe2是一个深度学习框架,也失去了Facebook的反对。Caffe2和Detectron当初都不举荐应用。Caffe2当初是PyTorch的一部分,它的继承者Detectron 2齐全是在PyTorch上编写的。
Detectron2旨在通过提供疾速的训练并解决公司从钻研到生产的过程中面临的问题,来促成机器学习的倒退。
以下是Detectron 2提供的各种类型的指标检测模型。
让咱们间接钻研实例检测。
实例检测是指对象的分类和定位,并带有边界框。在本文中,咱们将应用Detectron 2的模型库中的Faster RCNN模型来辨认图像中的文本语言。
请留神,咱们将语言限度为2种。
咱们辨认北印度语和英语文本,并为其余语言提供了一个名为“Others”的类。
咱们将实现一个以这种形式输入的模型。
让咱们开始吧!
应用Detectron 2,能够应用七个步骤对任何自定义数据集执行对象检测。所有这些步骤都能够在此Google Colab Notebook 中轻松找到,你能够立刻运行!
应用Google Colab进行这项工作很容易,因为咱们能够应用GPU进行更快的训练。
步骤1:装置Detectron 2
首先装置一些依赖项,例如Torch Vision和COCO API,而后查看CUDA是否可用。CUDA有助于跟踪以后抉择的GPU。而后装置Detectron2。
# install dependencies: !pip install -U torch==1.5 torchvision==0.6 -f https://download.pytorch.org/whl/cu101/torch_stable.html!pip install cython pyyaml==5.1!pip install -U 'git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI'import torch, torchvisionprint(torch.__version__, torch.cuda.is_available())!gcc --version# install detectron2:!pip install detectron2==0.1.3 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.5/index.html
步骤2:筹备和注册数据集
导入一些必要的程序包。
# You may need to restart your runtime prior to this, to let your installation take effectimport detectron2from detectron2.utils.logger import setup_loggersetup_logger()# import some common librariesimport numpy as npimport cv2import randomfrom google.colab.patches import cv2_imshow# import some common detectron2 utilitiesfrom detectron2 import model_zoofrom detectron2.engine import DefaultPredictorfrom detectron2.config import get_cfgfrom detectron2.utils.visualizer import Visualizerfrom detectron2.data import MetadataCatalog
内置数据集中列出了detectron2具备内置反对的数据集。如果要应用自定义数据集,同时还要重用detectron2的数据加载器,则须要注册数据集(即,通知detectron2如何获取数据集)。
- 内置数据集: https://detectron2.readthedoc...
咱们应用具备三个类别的文本检测数据集:
- 英语
- 印地语
- 其余
咱们将从在COCO数据集上事后训练的现有模型训练文本检测模型,该模型可在detectron2的模型库中应用。
如果你有趣味理解从原始数据集格局到Detectron 2承受的格局的转换,请查看:
- https://colab.research.google...
如何将数据输出模型?输出数据要求属于某些格局,如YOLO格局、PASCAL VOC格局、COCO格局等。Detectron2承受COCO格局的数据集。数据集的COCO格局由一个JSON文件组成,该文件蕴含图像的所有细节,如大小、正文(即边界框坐标)、与其边界框对应的标签等。例如,
这是一个JSON格局的图像。边界框示意有不同类型的格局。它必须是Detectron2的structures.BoxMode成员。这样的格局有5种。但目前,它反对 BoxMode.XYXY_ABS, BoxMode.XYWH_ABS.
咱们应用第二种格局。(X,Y)示意边界框的一个坐标,W,H示意该框的宽度和高度。category_id 指的是边界框所属的类别。
而后,咱们须要注册咱们的数据集。
import jsonfrom detectron2.structures import BoxModedef get_board_dicts(imgdir): json_file = imgdir+"/dataset.json" #Fetch the json file with open(json_file) as f: dataset_dicts = json.load(f) for i in dataset_dicts: filename = i["file_name"] i["file_name"] = imgdir+"/"+filename for j in i["annotations"]: j["bbox_mode"] = BoxMode.XYWH_ABS #Setting the required Box Mode j["category_id"] = int(j["category_id"]) return dataset_dictsfrom detectron2.data import DatasetCatalog, MetadataCatalog#Registering the Datasetfor d in ["train", "val"]: DatasetCatalog.register("boardetect_" + d, lambda d=d: get_board_dicts("Text_Detection_Dataset_COCO_Format/" + d)) MetadataCatalog.get("boardetect_" + d).set(thing_classes=["HINDI","ENGLISH","OTHER"])board_metadata = MetadataCatalog.get("boardetect_train")
为了验证数据加载是否正确,让咱们可视化训练集中随机抉择的样本的标注。
步骤3:可视化训练集
咱们将从数据集的train文件夹中随机抉择3张图片,并查看边界框的外观。
#Visualizing the Train Datasetdataset_dicts = get_board_dicts("Text_Detection_Dataset_COCO_Format/train")#Randomly choosing 3 images from the Setfor d in random.sample(dataset_dicts, 3): img = cv2.imread(d["file_name"]) visualizer = Visualizer(img[:, :, ::-1], metadata=board_metadata) vis = visualizer.draw_dataset_dict(d) cv2_imshow(vis.get_image()[:, :, ::-1])
输入看起来是这样的,
第四步:训练模型
咱们向前迈进了一大步。这是咱们给出配置和设置模型筹备承受训练的步骤。从技术上讲,咱们只是在数据集上微调咱们的模型,因为模型曾经在COCO数据集上进行了预训练。
在Detectron2的模型库里有大量的模型可用于指标检测。在这里,咱们应用faster_rcnn_R_50_FPN_3x。
这里有一个主干网(这里是Resnet),用于从图像中提取特色,而后是一个区域倡议网络,用于提出区域倡议,以及一个用于收紧边界框的框头部。
你能够在我的前一篇文章中读到更多对于R-CNN如何更快工作的文章。
- https://towardsdatascience.co...
让咱们为训练设置配置。
from detectron2.engine import DefaultTrainerfrom detectron2.config import get_cfgimport oscfg = get_cfg()cfg.merge_from_file(model_zoo.get_config_file("COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml")) #Get the basic model configuration from the model zoo #Passing the Train and Validation setscfg.DATASETS.TRAIN = ("boardetect_train",)cfg.DATASETS.TEST = ("boardetect_val",)# Number of data loading threadscfg.DATALOADER.NUM_WORKERS = 4cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml") # Let training initialize from model zoo# Number of images per batch across all machines.cfg.SOLVER.IMS_PER_BATCH = 4cfg.SOLVER.BASE_LR = 0.0125 # pick a good LearningRatecfg.SOLVER.MAX_ITER = 1500 #No. of iterations cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 256 cfg.MODEL.ROI_HEADS.NUM_CLASSES = 3 # No. of classes = [HINDI, ENGLISH, OTHER]cfg.TEST.EVAL_PERIOD = 500 # No. of iterations after which the Validation Set is evaluated. os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)trainer = CocoTrainer(cfg) trainer.resume_or_load(resume=False)trainer.train()
我不认为这是最好的配置。当然,其余配置的精确度也会进步。毕竟,这取决于抉择正确的超参数。
留神,这里咱们还计算验证集中每500次迭代的精确度。
第五步:应用训练好的模型进行推理
当初是时候通过在验证集上测试模型来推断后果了。
胜利实现训练后,输入文件夹保留在本地存储器中,其中存储最终权重。你能够保留此文件夹,以便未来依据此模型进行推断。
from detectron2.utils.visualizer import ColorMode#Use the final weights generated after successful training for inference cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.8 # set the testing threshold for this model#Pass the validation datasetcfg.DATASETS.TEST = ("boardetect_val", )predictor = DefaultPredictor(cfg)dataset_dicts = get_board_dicts("Text_Detection_Dataset_COCO_Format/val")for d in random.sample(dataset_dicts, 3): im = cv2.imread(d["file_name"]) outputs = predictor(im) v = Visualizer(im[:, :, ::-1], metadata=board_metadata, scale=0.8, instance_mode=ColorMode.IMAGE ) v = v.draw_instance_predictions(outputs["instances"].to("cpu")) #Passing the predictions to CPU from the GPU cv2_imshow(v.get_image()[:, :, ::-1])
后果:
第6步:评估训练模型
通常,模型的评估遵循COCO评估规范。用均匀精度(mAP)来评估模型的性能。
这是一篇对于mAP的文章:https://tarangshah.com/blog/2...
#import the COCO Evaluator to use the COCO Metricsfrom detectron2.evaluation import COCOEvaluator, inference_on_datasetfrom detectron2.data import build_detection_test_loader#Call the COCO Evaluator function and pass the Validation Datasetevaluator = COCOEvaluator("boardetect_val", cfg, False, output_dir="/output/")val_loader = build_detection_test_loader(cfg, "boardetect_val")#Use the created predicted model in the previous stepinference_on_dataset(predictor.model, val_loader, evaluator)
对于0.5的IoU,咱们取得约79.4%的准确度,这还不错。能够通过略微调整参数并减少迭代次数来减少。但请密切注意训练过程,因为该模型可能会过拟合。
如果你须要从保留的模型中进行推断,请浏览:https://colab.research.google...
论断
在本文中,我重点介绍了应用Detectron 2的自定义数据集进行指标检测的过程,而不是着重于取得更高的准确性。
只管这仿佛是一个非常简单的过程,但在Detectron 2的库中还有很多值得摸索的中央。咱们有大量的优化参数,能够进一步调整以取得更高的准确性,这齐全取决于一个人的自定义数据集。
你能够从我的Github存储库下载 notebook,而后尝试在Google Colab或Jupyter Notebooks上运行它。
- https://github.com/aakarsh759...
心愿你明天学到了一些新常识。
原文链接:https://towardsdatascience.co...
欢送关注磐创AI博客站:
http://panchuang.net/
sklearn机器学习中文官网文档:
http://sklearn123.com/
欢送关注磐创博客资源汇总站:
http://docs.panchuang.net/