Skip to main content
Article
mlopsexperiment-trackingpythonmachine-learningmodel-trainingvisualizationhyperparameter-tuning

Track Your First ML Experiment with Weights & Biases

Use Weights & Biases to log and visualize your machine learning model's metrics and hyperparameters. This guide shows how to integrate the `wandb` library into a Python training script to track your first experiment in minutes.

beginner15 min5 steps
The play
  1. Install & Login
    Install the Python library and authenticate your machine with your Weights & Biases account. The login command will prompt you for an API key, which you can find in your W&B profile settings.
  2. Initialize a Run
    In your training script, import `wandb` and call `wandb.init()` to start a new experiment run. This creates a unique, trackable run within a specified project on your Weights & Biases dashboard.
  3. Track Hyperparameters
    Pass a dictionary of hyperparameters to `wandb.init()` via the `config` argument. This saves the configuration with the run, making it easy to compare different experimental setups later.
  4. Log Metrics
    Inside your model's training loop, call `wandb.log()` with a dictionary of metrics like loss and accuracy. Weights & Biases automatically plots these values over time (by default, against the step number).
  5. View Your Dashboard
    After your script runs, follow the link printed in your terminal or navigate to your project page on the Weights & Biases website. You'll find interactive charts, hyperparameter tables, and system metrics for your run.
Starter code
import wandb
import random
import time

# 1. Start a new run
wandb.init(
    project="my-first-project",
    # Track hyperparameters and run metadata
    config={
        "learning_rate": 0.02,
        "architecture": "dummy-NN",
        "dataset": "synthetic",
        "epochs": 5,
    }
)

# This simple loop simulates a training process
epochs = wandb.config.epochs
learning_rate = wandb.config.learning_rate
offset = random.random() / 5

print(f"Starting training for {epochs} epochs...")

for epoch in range(1, epochs + 1):
    # Simulate training step
    time.sleep(1)
    
    # 2. Log metrics to W&B
    acc = 1 - (1 / (epoch + offset)) - random.random() / epoch - learning_rate
    loss = (1 / (epoch + offset)) + random.random() / epoch + learning_rate
    
    wandb.log({"accuracy": acc, "loss": loss, "epoch": epoch})
    print(f"Epoch {epoch}: Accuracy={acc:.4f}, Loss={loss:.4f}")

# 3. Mark the run as finished
wandb.finish()

print("Run complete. Check your Weights & Biases dashboard!")
Track Your First ML Experiment with Weights & Biases — Action Pack