mmclassification Inference a model
Image demo
This script performs inference on a single image.
python demo/image_demo.py \
${IMAGE_FILE} \
${CONFIG_FILE} \
${CHECKPOINT_FILE} \
[--device ${GPU_ID}] \
[--score-thr ${SCORE_THR}]
coco_2017_train데이터셋으로 학습하고, coco_2017_val로 테스트한 모든 모델들은 Model zoo (https://modelzoo.co/)에서 관리
Faster RCNN (기존 모델)을 활용한다.
=> 즉 기존모델을 활요한다는 것은
해당 Model의 weight를 가지고 있는 checkpoint파일 (https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth)내려 (mmdection/checkpoints/)에 받아서
해당 config파일(mmdetection/configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py)통해,
coco 스타일의 데이터셋으로
import os
print(os.getcwd())
# /home/oschung_skcc/my/git/msc/mmclassification/docs/en/tutorials
os.chdir("/home/oschung_skcc/my/git/msc/mmclassification")
print(os.getcwd())
# !ln -s /raid/templates/data/msc_pilot/ msc_pilot
Inference a model
#######################################
### * Inference a model with Python API
#######################################
# - Prepare the model
# - Prepare the config file
# - Prepare the checkpoint file
# - Build the model
# - Inference with the model
### 사용할 이미지
data_dir = '/raid/templates/data/msc_pilot/cam_kht/'
img_file = '20220822_161009.jpg'
img = data_dir+img_file
from PIL import Image
Image.open(img)
# https://mmclassification.readthedocs.io/en/latest/
import mmcv
from mmcls.apis import init_model,inference_model,show_result_pyplot
device = 'cuda:6'
### 1) Model 설정을 위한 config 파일 준비
# MobileNet V2
# https://github.com/open-mmlab/mmclassification/tree/master/configs/mobilenet_v2
#!ls configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py #있는지 확인
config_file = 'configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py'
### 2) Model weigt을 위한 checkpoint 파일 준비
# https://mmclassification.readthedocs.io/en/master/papers/mobilenet_v2.html
checkpoint_file = 'https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth'
### 3) Model 빌드
model = init_model(config_file, checkpoint_file, device=device)
# model.__class__.__mro__ # 모델의 상속관계
### 4) Model을 통해 Inference
img_array = mmcv.imread(img)
# img_array.shape #(3000, 4000, 3)
result = inference_model(model, img_array)
### 결과
show_result_pyplot(model, img, result)
print(result)
#{'pred_label': 478, 'pred_score': 0.5635119676589966, 'pred_class': 'carton'}
Fine-tune(reTrain) a model
ImageNet으로 학습되었던 모델을
내dataset으로 재학습 시킨다.
(작은 데이터로 인한 over-fitting을 방지)
#######################################
### * Fine-tune(reTrain) a model with Python API
#######################################
# 1. Prepare the target dataset and meet MMClassification's requirements.
# 2. Modify the training config.
# 3. Start training and validation.
config_file = 'configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py'
checkpoint_file = 'https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth'
##############################################################################
### 1. Target dataset 준비
# Custome Dataset
##############################################################################
### 2. training config 수정
from mmcv import Config
cfg = Config.fromfile(config_file)
cfg.model.head.num_classes = 2 # 1000
cfg.model.head.topk = (1, )
cfg.model.backbone.init_cfg = dict(type='Pretrained', checkpoint=checkpoint_file, prefix='backbone')
cfg.data.samples_per_gpu = 32
cfg.data.workers_per_gpu = 2
# Specify the path and meta files of training dataset
cfg.data.train.data_prefix = 'data/cats_dogs_dataset/training_set/training_set'
cfg.data.train.classes = 'data/cats_dogs_dataset/classes.txt'
# Specify the path and meta files of validation dataset
cfg.data.val.data_prefix = 'data/cats_dogs_dataset/val_set/val_set'
cfg.data.val.ann_file = 'data/cats_dogs_dataset/val.txt'
cfg.data.val.classes = 'data/cats_dogs_dataset/classes.txt'
# Specify the path and meta files of test dataset
cfg.data.test.data_prefix = 'data/cats_dogs_dataset/test_set/test_set'
cfg.data.test.ann_file = 'data/cats_dogs_dataset/test.txt'
cfg.data.test.classes = 'data/cats_dogs_dataset/classes.txt'
# Specify the normalization parameters in data pipeline
normalize_cfg = dict(type='Normalize', mean=[124.508, 116.050, 106.438], std=[58.577, 57.310, 57.437], to_rgb=True)
cfg.data.train.pipeline[3] = normalize_cfg
cfg.data.val.pipeline[3] = normalize_cfg
cfg.data.test.pipeline[3] = normalize_cfg
# Modify the evaluation metric
cfg.evaluation['metric_options']={'topk': (1, )}
# Specify the optimizer
cfg.optimizer = dict(type='SGD', lr=0.005, momentum=0.9, weight_decay=0.0001)
cfg.optimizer_config = dict(grad_clip=None)
# Specify the learning rate scheduler
cfg.lr_config = dict(policy='step', step=1, gamma=0.1)
cfg.runner = dict(type='EpochBasedRunner', max_epochs=2)
# Specify the work directory
cfg.work_dir = './work_dirs/cats_dogs_dataset'
# Output logs for every 10 iterations
cfg.log_config.interval = 10
# Set the random seed and enable the deterministic option of cuDNN
# to keep the results' reproducible.
from mmcls.apis import set_random_seed
cfg.seed = 0
set_random_seed(0, deterministic=True)
cfg.gpu_ids = range(1)
cfg.device='cuda'
##############################################################################
### 3. 학습/검증
import mmcv
import os
import time
from mmcls.datasets import build_dataset
from mmcls.models import build_classifier
from mmcls.apis import train_model
mmcv.mkdir_or_exist(os.path.abspath(cfg.work_dir))
# dataset
datasets = [build_dataset(cfg.data.train)]
# Model
model = build_classifier(cfg.model)
model.init_weights()
model.CLASSES = datasets[0].CLASSES
# retraining :: fine tuning
train_model(model, datasets, cfg,
distributed=False,
validate=True,
timestamp=time.strftime('%Y%m%d_%H%M%S', time.localtime()),
meta=dict()
)
from mmcls.apis import inference_model, show_result_pyplot
model.cfg = cfg
img = mmcv.imread('data/cats_dogs_dataset/training_set/training_set/cats/cat.1.jpg')
result = inference_model(model, img)
show_result_pyplot(model, img, result)