Sub topic 2
Writing and Loading a Config File
This chapter assumes you know Python dataclasses, can run commands in a terminal, have PyYAML installed (pip install pyyaml), and have basic Git usage.
Writing the config file
Store the values that change between runs in a YAML file, not in the training code:
data_path: data/processed/train.csv
seed: 42
learning_rate: 0.001
batch_size: 32Loading it into a typed object
Read the file into a frozen dataclass. Unknown or missing keys then fail loudly.
from dataclasses import dataclass
import yaml
@dataclass(frozen=True)
class TrainConfig:
data_path: str
seed: int
learning_rate: float
batch_size: int
def apply_overrides(raw, overrides):
for item in overrides:
key, value = item.split("=", 1)
raw[key] = yaml.safe_load(value)
return raw
def load_config(path, overrides=()):
with open(path) as f:
raw = yaml.safe_load(f)
raw = apply_overrides(raw, overrides)
return TrainConfig(**raw)Overriding values from the command line
Pass key=value pairs after the script name. yaml.safe_load converts 0.01 to a float and 64 to an int, so types survive the trip from the shell.
import sys
from my_project.config import load_config
cfg = load_config("configs/train.yaml", sys.argv[1:])
print(cfg)python train.py learning_rate=0.01 batch_size=64Organizing raw, interim, and processed data
Split data folders by processing stage:
| Folder | Contents | Rule |
|---|---|---|
| data/raw/ | Original files as received | Never edit by hand |
| data/interim/ | Partly cleaned or joined files | Rebuilt by code |
| data/processed/ | Files the model reads | Rebuilt by code |
Versioning data without committing it to Git
Git handles small text files poorly, so keep data out of Git history and track a small pointer file instead. With DVC (Data Version Control):
dvc add data/raw
git add data/raw.dvc .gitignore
git commit -m "Track raw data version"Exercise:
Exercise
You run python train.py batch_szie=64. What happens?
Show answer
loadconfig raises a TypeError, because TrainConfig(**raw) receives an unexpected keyword argument named batchszie.