Learning path: Ship Your First Model: From Notebook to a FastAPI Service · Step 8 of 9
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.
What you will learn
- Move paths, test_size, n_iter and the seed out of train.py into config.toml
- Read the config with tomllib into a plain dict
- Set up logging with levels, a timestamp, a run id, the terminal and a log file
- Keep passwords and API keys out of the config and the logs
Before you start
- Python Virtual Environments: One Project, One Toolbox
- Project: Car Price Predictor End to End
- Hyperparameter tuning with RandomizedSearchCV
Imagine a heater where, every time you want it warmer, you open it up and change the wiring. You rewire it and hope nothing breaks. A heater with a thermostat works differently: you turn the dial, twenty, twenty-one, twenty-two, and the heater stays shut.
Editing train.py to change a setting is the rewiring. A config file is the dial. The code doesn't change; only the setting does. And while we're at it, we'll make every run tell us what it did, with logging instead of print.
The example uses the same car price model and data as Car Price Predictor End to End, here laid out as a small package called carprice: a scikit-learn pipeline with a random forest, tuned with RandomizedSearchCV and scored with test RMSE, on 205 cars.
Settings are hiding in the code
Here's the old main() in train.py:
def main():
X, y = load_cars("data/CarPrice.csv")
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
cv = KFold(n_splits=5, shuffle=True, random_state=42)
search = RandomizedSearchCV(
make_model(), PARAMS, n_iter=10, cv=cv, random_state=42,
scoring="neg_root_mean_squared_error")
search.fit(X_train, y_train)
best = search.best_estimator_
rmse = root_mean_squared_error(y_test, best.predict(X_test))
print("test RMSE", round(rmse))
Path("models").mkdir(exist_ok=True)
joblib.dump(best, "models/car_model.joblib")
print("saved models/car_model.joblib")
Count the settings typed right into the code:
- Paths: where the data is, and where the model gets saved.
test_sizeandn_iter: the settings we may actually want to change.- The seed:
42is written three times in this file, and once more inpipeline.py. Change one and miss another, and your run is only half changed.
One file holds every setting
All of them move into config.toml at the project root:
# Change these here, not in the code.
[paths]
data = "data/CarPrice.csv"
model = "models/car_model.joblib"
[train]
test_size = 0.2
n_iter = 10
seed = 42
[logging]
level = "INFO"
file = "logs/train.log"
The seed is now one line. Why TOML? YAML would work as well, but it needs a package. tomllib ships with Python 3.11 and up, so there's no new install, and it's the same format as pyproject.toml.
Read it into one dict
A small config.py reads the file:
import tomllib
def load_config(path="config.toml"):
with open(path, "rb") as f:
return tomllib.load(f)
It opens the file in binary mode ("rb"), because tomllib asks for that, and hands back a plain Python dictionary. Each [section] becomes a key: cfg["paths"], cfg["train"], cfg["logging"].
Now the new train.py has no numbers in it:
import logging
from pathlib import Path
import joblib
from sklearn.metrics import root_mean_squared_error
from sklearn.model_selection import (
KFold, RandomizedSearchCV, train_test_split)
from carprice.config import load_config, start_logging
from carprice.data import load_cars
from carprice.pipeline import PARAMS, make_model
log = logging.getLogger(__name__)
def main():
cfg = load_config()
start_logging(cfg["logging"])
t, paths = cfg["train"], cfg["paths"]
seed = t["seed"]
log.info("start n_iter=%d test_size=%s seed=%d",
t["n_iter"], t["test_size"], seed)
X, y = load_cars(paths["data"])
log.debug("loaded %d cars, %d columns", *X.shape)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=t["test_size"], random_state=seed)
log.info("split %d train, %d test", len(X_train), len(X_test))
cv = KFold(n_splits=5, shuffle=True, random_state=seed)
search = RandomizedSearchCV(
make_model(seed), PARAMS, n_iter=t["n_iter"], cv=cv,
random_state=seed, scoring="neg_root_mean_squared_error")
search.fit(X_train, y_train)
log.debug("best cv RMSE %d", round(-search.best_score_))
best = search.best_estimator_
rmse = root_mean_squared_error(y_test, best.predict(X_test))
log.info("test RMSE %d", round(rmse))
model_path = Path(paths["model"])
if model_path.exists():
log.warning("overwriting %s", model_path)
model_path.parent.mkdir(exist_ok=True)
joblib.dump(best, model_path)
log.info("saved %s", model_path)
The data path goes to load_cars, 0.2 goes to the split, 10 goes to the search as n_iter, and 42 goes in as every random_state. make_model(seed) now takes the seed, so the forest gets the same one. predict.py reads the model path from the config too. To change a setting, you never open this file.
load_config turns it into a dict, and the code only reads from that dict.A log line answers four questions
print gives you text, and then it's gone: no time, no level, and nothing is saved. Here's start_logging, also in config.py:
import logging
import uuid
from pathlib import Path
def start_logging(cfg):
run_id = uuid.uuid4().hex[:8]
log_file = Path(cfg["file"])
log_file.parent.mkdir(exist_ok=True)
logging.basicConfig(
level=cfg["level"],
format=f"%(asctime)s %(levelname)-7s {run_id} %(message)s",
datefmt="%m-%d %H:%M:%S",
handlers=[logging.StreamHandler(),
logging.FileHandler(log_file)])
- Run id:
uuid.uuid4().hex[:8]makes eight random characters. It goes right inside the format string, so every line of this run carries it. - Level: how serious the line is.
DEBUGis extra detail,INFOis normal progress,WARNINGis worth a look, andERRORmeans something failed.level="INFO"drops the debug lines. - Handlers: where a line goes.
StreamHandlerprints to the terminal,FileHandlerwrites tologs/train.log. The window closes, and the file stays.
Back in train.py, log = logging.getLogger(__name__) gives the module its logger, and log.info(...), log.debug(...) and log.warning(...) write the lines.
Run it with the default config
python -m carprice.train
11-02 19:58:27 INFO da19ba40 start n_iter=10 test_size=0.2 seed=42
11-02 19:58:27 INFO da19ba40 split 164 train, 41 test
11-02 19:58:44 INFO da19ba40 test RMSE 2195
11-02 19:58:44 INFO da19ba40 saved models\car_model.joblib
The first line records the settings this run used, the next gives the split, then the test RMSE: 2195. It's the first run, so there's nothing to overwrite. The same lines are also in logs/train.log.
That's the same test RMSE as before the change, to the digit, and python -m carprice.predict car.json still says:
predicted 29904
Moving the settings changed nothing about the model. That's the point.
Turn the dial: n_iter from 10 to 3
In config.toml, change n_iter = 10 to n_iter = 3. Zero code files changed. Run the same command:
11-02 19:58:49 INFO c601f019 start n_iter=3 test_size=0.2 seed=42
11-02 19:58:49 INFO c601f019 split 164 train, 41 test
11-02 19:58:53 INFO c601f019 test RMSE 2805
11-02 19:58:53 WARNING c601f019 overwriting models\car_model.joblib
11-02 19:58:53 INFO c601f019 saved models\car_model.joblib
A new run id, and the log records n_iter=3. With 5 folds, that's 15 fits instead of 50. Quicker, but the test RMSE goes up to 2805: fewer settings tried, and this time it cost us. (More on the search itself in grid and random search.)
And there's the WARNING: overwriting the model. That quick run just replaced our better model, and the log told us.
More detail on request
Put n_iter back to 10, and turn another dial: level = "DEBUG".
11-02 19:58:56 INFO 4aada54a start n_iter=10 test_size=0.2 seed=42
11-02 19:58:56 DEBUG 4aada54a loaded 205 cars, 9 columns
11-02 19:58:56 INFO 4aada54a split 164 train, 41 test
11-02 19:59:11 DEBUG 4aada54a best cv RMSE 2392
11-02 19:59:11 INFO 4aada54a test RMSE 2195
11-02 19:59:11 WARNING 4aada54a overwriting models\car_model.joblib
11-02 19:59:11 INFO 4aada54a saved models\car_model.joblib
Two extra DEBUG lines appear: 205 cars loaded, and the best cross-validation RMSE, 2392. Same code, just more detail, and the test RMSE is back to 2195.
One run out of many
logs/train.log now holds all three runs, because FileHandler keeps adding to the end of the file. To see just one run, search for its id. On Windows:
findstr c601f019 logs\train.log
11-02 19:58:49 INFO c601f019 start n_iter=3 test_size=0.2 seed=42
11-02 19:58:49 INFO c601f019 split 164 train, 41 test
11-02 19:58:53 INFO c601f019 test RMSE 2805
11-02 19:58:53 WARNING c601f019 overwriting models\car_model.joblib
11-02 19:58:53 INFO c601f019 saved models\car_model.joblib
Just the quick run's five lines. On macOS or Linux, use grep c601f019 logs/train.log.
Passwords and keys never go in config.toml
config.toml goes into Git. Once a key is committed, it stays in the history, in every clone and every copy. So a password or an API key lives in an environment variable, and the program reads it when it runs:
python -c "import os; key = os.environ['CARPRICE_API_KEY']"
If the variable isn't set, the program stops with a KeyError that names the missing variable:
Traceback (most recent call last):
File "<string>", line 1, in <module>
import os; key = os.environ['CARPRICE_API_KEY']
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
File "<frozen os>", line 717, in __getitem__
KeyError: 'CARPRICE_API_KEY'
A log is a file too. We log n_iter, test_size and the seed, and nothing private. A key in a log is a leaked key.
The project's .gitignore keeps the generated files out of Git as well: models/, logs/, __pycache__/, *.egg-info/ and .venv/.
Common mistakes
- Leaving one copy of a value in the code. If the seed is in the config and still typed somewhere else, changing it gives a half-changed run. Pass it in, like
make_model(seed). - Opening the TOML file in text mode.
tomllib.loadneedsopen(path, "rb"). - Logging without a run id. Once the file holds many runs, you can't tell which line belongs to which.
- Secrets in the config or the log. Settings go in the config file; secrets go in the environment.
Recap
| Piece | Job |
|---|---|
config.toml | Every setting: paths, test_size, n_iter, seed, log level and file |
load_config() | Reads it with tomllib into a plain dict |
start_logging() | Levels, time, a run id, the terminal and a file |
| Run id | On every line, so findstr or grep pulls out one run |
os.environ | Where secrets come from, never the config |
The default config still gives a test RMSE of 2195, exactly as before.
Try it yourself: set test_size = 0.3 in config.toml and train again. Then find both runs in logs/train.log by their run ids. The project files are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Testing a FastAPI App with pytest: Three Small Tests
Next →SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
The SQL a Python developer needs, on a tiny shop with four customers and eight orders: CREATE TABLE, INSERT with placeholders, SELECT with WHERE, JOIN, GROUP BY, pandas.read_sql, and why values never go in f-strings.