[Python] 설정 파일 - YAML 사용하기

Bobae·2023년 9월 22일

yaml은 데이터 직렬화를 가능하게 하는 언어입니다.

yaml을 사용하면 데이터 구조에 맞게 쉽게 매핑이 가능하기 때문에, 주로 설정을 위한 파일로 많이 사용됩니다.

이번 포스팅에서는 yaml을 사용해서 ML프로젝트를 위해 모델 훈련시 설정파일을 불러와 사용하는 방법을 소개합니다.


yaml은 기본적으로 key, value로 이루어져있는 Dictionary 데이터 형태입니다. 다음과 같은 config.yaml파일이 있다고 가정합니다.

# config.yaml
model: roberta-tokenized-gpt2

training:
    random_seed: 123
    batch_size: 16
    gradient_accumulation_batches: 1
    optimization:
        optimizer_name: AdamW
        weight_decay: 0.01
    scheduler:
        scheduler_name: WarmupLinear
        warmup_steps: 0
    evaluation:
        batch_size: 16
task:
    name: CommonGEN        

yaml을 사용하면 config.yaml파일을 dictionary 데이터 형식으로 불러올 수 있습니다. 하지만, 변수에 접근하기 위해서는 [key] 문법을 사용해야 value를 얻을 수 있습니다.

Dot notation 방식이 좀 더 간편하고 편하므로, 이를 가능하게 하는 box 패키지를 사용해서 dot notation 방식으로 config 파일에 접근합니다.

import yaml
from box import Box

conf_url = 'config.yaml'
with open(conf_url, 'r') as f:
	config_yaml = yaml.load(f, Loader=yaml.FullLoader)
    config = Box(config_yaml)

print(config.model) #output: roberta-tokenized-gpt2
print(config.training.random_seed) #output: 123
profile
현재 머신러닝, 딥러닝을 공부하고 있습니다.

0개의 댓글