Skip to content

SceneTextDetection

ocr.DetTrainer

Scene Text Detection 모델을 학습시키기 위한 Trainer class 입니다.

Usage
# Trainer 빌드
error, trainer = DetTrainer.build(CONFIG, DATA)
assert error >= 0

# 0번 GPU로 이동
error, result = trainer.to_device(DEVICE)
assert error >= 0

# validation 가능한지 확인
error, validation_enabled = trainer.validation_enabled()
assert error >= 0

# 학습 루프
for step in range(CONFIG["total_iterations"]):
    error, result = trainer.train_one_step()
    assert error >= 0

    if (step + 1) % PRINT_INTERVAL == 0:
        print(f"Train {step + 1}:", result)

    if validation_enabled and (step + 1) % VALIDATION_INTERVAL == 0:
        error, result = trainer.validate()
        assert error >= 0
        print(f"Validation {step + 1}:", result)

# 학습 후처리 (default inference options)
error, post_train_process_result = trainer.post_train_process()
assert error >= 0
print("post_train_process :", post_train_process_result)

# 체크포인트 저장
error, _ = trainer.save_checkpoint(
    checkpoint_path=CHECKPOINT_PATH,
    password=PASSWORD,
    metadata={"description": "demo"},
)

build(config, data) classmethod

DetTrainer class의 instance를 생성합니다.

Parameters:

Name Type Description Default
config Dict

DetTrainer를 build 하기 위한 config가 담겨 있는 dictionary 입니다.

{
    "network_type": str,  # "v2_fast" / "v2_standard" 중 하나를 지원합니다.
    "total_iterations": int,  # total training iterations
    "roi": Optional[Dict],  # roi 세팅. ROIHandlerAPI의 build config와 동일합니다. None이면 ROI 적용 안함. (default None)
    "target_text_size": Optional[int],  # 리사이즈 후 target text size (16-64, default None). 하단 설명 참고.
    "augmentation": Optional[List[Dict]],  # 학습에 사용할 augmentation config들을 모은 list 입니다. (default None)
    "batch_size": int,  # number of train batch size (default 6)
    "num_workers": int,  # number of train data worker processes (default 4)
    "representer_type": Optional[str],  # "curved" / "straight" 중 하나를 지원합니다. (default None)
}

required
data Dict

DetTrainer가 사용 할 train/validation data가 담겨 있는 dictionary 입니다.

{
    "train_images": {
        # 1: basic structure
        "{image_id}": {
            "path": Union[str, List[str]],      # 이미지 경로 (multipage인 경우 경로 리스트)
            "width": int,  # image width
            "height": int,  # image height
            "labels": [
                {
                    "polygon": [
                        [point_1_x, point_1_y], # TODO: 폴리곤 정렬 순서에 대해 제품팀과 논의
                        [point_2_x, point_2_y],
                        ...,
                        [point_n_x, point_n_y]
                    ],                          # float
                    "text": text in box         # str
                },
                ...# times number of labels in the image
            ],
        },
        # 2: label path structure
        "{image_id}": {
            "path": Union[str, List[str]],      # 이미지 경로 (multipage인 경우 경로 리스트)
            "width": int,                       # image width
            "height": int,                      # image height
            "labels_count": int,                # len(labels)
            "labels_path": str,                 # pickle path to "labels"
        },
        ...,  # times number of images
    },
    "validation_images": {...},
}

required

Returns:

Name Type Description
DetTrainer

build가 완료된 ocr.DetTrainer class의 instance를 반환합니다.

to_device(device=None)

DetTrainer의 device를 변경합니다. (cpu/gpu)

Parameters:

Name Type Description Default
device Union[device, str, int]

변경하고자 하는 device 입니다. int의 경우 해당 번호의 GPU를, "cpu" 문자열의 경우 cpu를 사용합니다.

None

Returns: None: None

train_one_step()

학습을 1스텝 수행하고, 결과를 반환합니다.

Returns:

Name Type Description
Dict

학습 결과가 들어있는 dictionary를 반환합니다.

{
    "step": int,  # 현재까지 진행된 총 학습 step.
    "epoch": int,  # 현재까지 진행된 총 학습 epoch.
    "epoch_step": int,  # 현재 epoch에서 몇 번째 step인지를 나타냄.
    "loss/total": float,  # 학습에 사용되는 모든 loss를 모두 더한 값.
    "loss/dice_loss": float,
    "loss/bce_loss": float,
    "loss/thr_loss": float,
    "loss/thk_loss": float,
    "loss/sin_loss": float,
    "loss/cos_loss": float,
    "loss/angle_loss": float,
    "learning_rate/0": float,  # optimizer의 learning rate
    "step_time(sec)": float,  # 학습을 1 step 진행하는데 걸린 총 시간
    "data_time(sec)": float,  # 데이터를 로딩하는데 걸린 시간
    "model_time(sec)": float,  # 모델 학습에 걸린 시간
}

validation_enabled()

DetTrainer가 validation이 가능한지 bool로 반환합니다.

Returns:

Name Type Description
bool

DetTrainer가 validation이 가능하면 True를, 불가능하다면 False를 반환합니다.

validate()

Validation을 수행하고, 결과를 리턴합니다.

Returns:

Name Type Description
Dict

validation 결과가 들어있는 dictionary를 반환합니다.

{
    "IoU": float,  # pixel iou value.
}

post_train_process()

train 후처리를 수행하고, 해당 모델의 default inference options을 리턴합니다.

Returns:

Name Type Description
Dict Dict

각 parameter에 대한 설명은 DetRecInferencer.get_default_inference_option를 참고해주세요.

{
    "detection.polygon_score_threshold": float,
    "detection.text_size_range": List[int],
    "params.inspection_size_wh": Optional[List[int]],
}

save_checkpoint(checkpoint_path, metadata=None, password=None)

현재 DetTrainer의 상태를 암호화하여 저장합니다.

Parameters:

Name Type Description Default
checkpoint_path str

checkpoint를 저장할 path 입니다.

required
metadata Optional[Dict]

checkpoint에 저장할 추가 metadata. Defaults to None.

None
password Optional[str]

checkpoint 파일에서 중요한 정보를 암호화 하는데 사용되는 password 입니다. None이면 암호화하지 않습니다. Defaults to None.

None

Returns: None: None

load_checkpoint(checkpoint_path, password=None, **options)

저장한 checkpoint로부터 DetTrainer의 상태를 불러오고, metadata를 반환합니다.

Parameters:

Name Type Description Default
checkpoint_path str

load할 checkpoint가 저장 되어 있는 path 입니다.

required
password Optional[str]

checkpoint 파일에서 중요한 정보를 복호화 하는데 사용되는 password 입니다. None이면 복호화하지 않습니다. Defaults to None.

None

Returns:

Name Type Description
Dict dict

save_checkpoint에서 저장했던 metadata 입니다.

auto-resize 설명

  • 이미지 상의 텍스트 박스의 height 값이 특정한 길이가 되도록 하는 resize factor를 자동으로 찾아 주는 기능.
  • 텍스트 검출 성능은 텍스트의 절대적인 크기에 영향을 받는데, 어떤 resize 값이 가장 적절한 지를 자동으로 결정해 줌.
  • 학습 데이터셋을 한번 쭉 훑어 텍스트 라벨 height의 평균 값을 구하고, 이 값이 지정된 수치가 되도록 하는 resize factor를 계산함.
    • (ex) 데이터셋의 mean text height가 12이고 미리 지정된 수치가 36이라면 resize 배율은 3이 됨.
  • 옵션은 None 혹은 16-64 의 integer로, 리사이즈 이후의 텍스트 height 평균 값이 얼마가 될 지 지정함. 지정값이 클수록 최종 이미지 사이즈는 커짐. 디폴트는 None.

Preview API에서 설정한 roi config를 그대로 Trainer.build() config의 roi 섹션에 넣어주면 학습 시 해당 roi가 적용되며, 학습에서 설정하는 roi는 validation 및 inference 시에도 동일하게 적용됩니다.

trainer_config = {
    "network_type": "standard",
    ...
    "target_text_size": 32,  # [None, 16, 24, 32, 40, 48, 56, 64]
    ...
}

error, trainer = DetTrainer.build(config=trainer_config, data)