Skip to content

Train

segmentation.Trainer

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

Usage

demo/train.py 참고

build(config, data) classmethod

Trainer class의 instance를 생성합니다.

Parameters:

Name Type Description Default
config Dict

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

{
    "network_type": str,  # "v1_shallow" / "v1_standard" / "v1_deep" / "v2_fast" / "v2_standard" / "v2_accurate" 중 하나를 지원합니다.
    "total_iterations": int,  # total training iterations
    "n_classes": int,  # number of data classes (including background class, n_classes >= 2)
    "batch_size": int,  # number of train batch size (default 12)
    "roi": Optional[Dict],  # roi 세팅. ROIHandlerAPI의 build config와 동일합니다. None이면 ROI 적용 안함. (default None)
    "crop_wh": Union[List[int], Tuple[int, int]],  # crop size for cropper (default (256, 256))
    "resize_factor": Optional[float],  # training image resize scale (default None)
    "augmentation": Optional[List[Dict]],  # 학습에 사용할 augmentation config들을 모은 list 입니다. (default None)
    "num_workers": int,  # number of train data worker processes (default 8)
    "multipage": Optional[Dict],  # multipage 설정. None인 경우 multipage 사용 안 함. (default None)
        {
            "image_mode": List[str],  # multipage 이미지들의 모드 리스트. 리스트 길이 = 병합할 이미지 수.
                                      # 모드는 "RGB" 또는 "L" 사용 가능.
                                      # ex) ["RGB", "L", "RGB", ...] - 첫 번째 이미지는 color, 두 번째 이미지는 gray, ...
        }
    "inspection_size_wh": Optional[List[int]],  # validation에서 사용할 inspection_size_wh 입니다.
                                                # 자세한 정보는 InferenceHandler의 get_default_inference_option 함수 설명에 나와있습니다.
    "oversized_image_handling": Optional[str],  # validation에서 사용할 oversized_image_handling 입니다.
                                                # 자세한 정보는 InferenceHandler의 get_default_inference_option 함수 설명에 나와있습니다.
    "cache_directory": Optional[str],  # 전처리된 데이터를 저장할 경로입니다. 각 학습마다 다른 경로로 설정하고, 학습이 종료되면 해당 경로를 삭제해야합니다.
                                       # None으로 세팅하는 경우 데이터를 디스크에 쓰지 않고 메모리에 올려둡니다.
}

required
data Dict

Trainer가 사용 할 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": [  # 2가지 타입 지원: "bounding_box" + "bitmap" 타입 / "contours" 타입
                {  # "bounding_box" + "bitmap" 타입
                    "class_index": int,  # class index (0: background)
                    "bounding_box": List[int],  # [left, top, width, height]
                    "bitmap": str,  # base64 encoded png image string (shape: (h_label, w_label))
                },
                {  # "contours" 타입
                    "class_index": int,  # class index (0: background)
                    "contours": [  # cv2 형식의 contours. 0번째 contour가 outer, 나머지는 모두 inner.
                        ndarray(int32, shape=(num_points_0, 1, 2)),
                        ndarray(int32, shape=(num_points_1, 1, 2)),
                        ndarray(int32, shape=(num_points_2, 1, 2)),
                        ...  # contour 개수 만큼 반복
                    ],
                },
                ...,  # 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
Trainer Trainer

build가 완료된 segmentation.Trainer class의 instance를 반환합니다.

to_device(device)

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

Parameters:

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

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

required

Returns: None: None

train_one_step()

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

Returns:

Name Type Description
Dict Dict

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

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

validation_enabled()

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

Returns:

Name Type Description
bool bool

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

validate()

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

Returns:

Name Type Description
Dict Dict

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

{
    "pixel/mean_iou": float,  # pixel mean iou value.
    "pixel/class_{idx}_iou": float,  # 각 {idx} class 별 pixel iou value.
}

post_train_process()

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

Returns:

Name Type Description
Dict Dict

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

{
    "params.object_boundary_threshold": List[int],
    "params.calc_object_area_and_apply_threshold": bool,
    "params.calc_object_score_and_apply_threshold": bool,
    "params.object_area_threshold": List[int],
    "params.object_score_threshold": List[float],
    "params.batch_size": int,
    "params.inspection_size_wh": Optional[List[int]],
    "params.oversized_image_handling": str,
}

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

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

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)

저장한 checkpoint로부터 Trainer의 상태를 불러오고, 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 입니다.