How to Generate Experiment Tracking Run IDs in Python
Generate unique experiment run IDs with timestamps and random suffixes for tracking ML pipeline executions.
Python code
14 linesimport random
import string
import time
def generate_run_id(prefix="exp"):
timestamp = time.strftime("%Y%m%d_%H%M%S")
suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
return f"{prefix}_{timestamp}_{suffix}"
if __name__ == "__main__":
# Simulate tracking three experiment runs
for i in range(3):
run_id = generate_run_id()
print(f"Run {i + 1}: {run_id}")
Output
Run 1: exp_20240315_143022_ab3x9z
Run 2: exp_20240315_143022_k7p2mq
Run 3: exp_20240315_143022_t5w8jr
How it works
The generate_run_id function combines a timestamp from time.strftime with a random 6-character alphanumeric suffix. This creates human-readable, chronologically sortable IDs unique enough for most experiment tracking needs. The timestamp ensures IDs are roughly ordered by creation time, while the random suffix reduces collision probability. Using random.choices with string.ascii_lowercase + string.digits avoids ambiguous characters and keeps IDs compact.
Common mistakes
- Forgetting that two runs in the same second can collide without the random suffix
- Using `time.time()` directly instead of `strftime` which produces ugly unreadable IDs
- Not including a prefix to distinguish experiment types in large tracking systems
Variations
- Use `uuid.uuid4().hex[:6]` instead of `random.choices` for stronger uniqueness guarantees
- Format timestamp as `%Y%m%d%H%M%S%f` (with microseconds) to reduce collision risk further
Real-world use cases
- Logging each training run into MLflow or Weights & Biases with a unique identifier for later comparison.
- Storing model artifacts and checkpoints in cloud storage with run-specific keys for easy retrieval.
- Tracking hyperparameter sweeps where each configuration needs a distinct ID to link results back.
Sponsored
More from ML engineering pipelines
- Bayesian Optimization in Python: A Simplified Mock Implementation medium
- Build a Data Helper Class in Python for ML Pipelines easy
- Build a Mock Random Forest Classifier in Python easy
- Champion Challenger Deployment Mock in Python easy
- Compare Model A vs Model B Metrics in Python easy
- Create a Minimal Great Expectations Suite Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.