Skip to content

Train

core.Trainer

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

Usage
# Trainer 빌드
error, trainer = Trainer.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

error, total_iterations = trainer.get_total_num_iterations()
print(f"total steps to train: {total_iterations}")

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

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

# 학습 후처리 (thresholds 계산)
error, result = trainer.post_train_process()
assert error >= 0
print(result)

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

build(config, data) classmethod

Trainer class의 instance를 생성합니다.

Parameters:

Name Type Description Default
config Dict

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

{
    "model_size": str,  # "shallow" / "standard" / "deep" 중 하나를 지원합니다.
    "roi": Optional[Dict],  # roi 세팅. ROIHandlerAPI의 build config와 동일합니다.
                            # Trainer build시 설정한 ROI를 Validation, Inference시에도 적용됩니다.
                            # None이면 ROI를 적용하지 않습니다. (default None)
    "data_resize": Optional[List[int]],  # training image resize scale (default [512, 512])
    "num_workers": int,  # number of train data worker processes (default 0)
}

required
data Dict

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

{
    "train_images": [
        {
            "path": str,  # image path
            "labels": {
                "ng": bool,  # ng or not
            },
        },
        ...,  # times number of images
    ],
    "validation_images": [...],
}

required

Returns:

Name Type Description
Trainer Trainer

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

to_device(device)

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

Parameters:

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

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

required

Returns:

Name Type Description
None None

None

get_total_num_iterations()

학습에 필요한 전체 스텝 수를 반환합니다. 학습에 필요한 전체 스텝 수를 변경할 수 없습니다. 전체 스텝 수보다 많이 돌린 모델과 전체 스텝 수만큼 돌린 모델은 같은 모델입니다.

Note
현재는 이미지 수가 100개 단위로 스텝 수가 늘어납니다.
이미지 갯수가
    1~100개일 때: 1
    101~200개일 때: 2
    201~300개일 때: 3
    ...

Returns:

Name Type Description
int int

학습에 필요한 전체 스텝 수.

train_one_step()

학습을 1스텝 수행합니다.

Returns:

Name Type Description
None None

None

post_train_process()

train을 마무리하기 위한 작업을 합니다. 주로 threshold를 자동으로 계산해줍니다.

Returns:

Name Type Description
Dict Dict

thresholds를 리턴합니다.

{
    "anomaly_threshold": float,  # is_ng를 판단할 때 사용됩니다.
    "score_threshold": float,  # mask를 만들 때 사용됩니다.
    "color_range": List[float],  # heatmap을 만들 때 scoremap에 사용될 (min, max)입니다.
}

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를 반환합니다.

{
    "AUROC": float,  # Area under ROC
    "AUPR": float,  # Area under PR curve
    "Best threshold": float,  # Best threshold
    "Best F1-Score": float,  # F1 score with labels
    "FN": str,  # False Negative
    "FP": str,  # False Positive
}

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:

Name Type Description
None 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 입니다.