How to use wandb.log
Quick answer
Use wandb.log to record metrics and other data during your training loop by passing a dictionary of key-value pairs. This function sends the logged data to your Weights & Biases project for real-time tracking and visualization.
PREREQUISITES
Python 3.8+pip install wandbWeights & Biases account (free tier available)wandb login or API key configured
Setup
Install the wandb Python package and authenticate your environment to enable logging.
- Install with
pip install wandb - Run
wandb loginin your terminal and enter your API key from Weights & Biases
pip install wandb
wandb login Step by step
Initialize a W&B run, then use wandb.log inside your training loop to log metrics such as loss and accuracy.
import wandb
import time
# Initialize a new run
wandb.init(project="my-project")
for step in range(1, 6):
# Simulate metrics
loss = 0.1 * step
accuracy = 0.8 + 0.04 * step
# Log metrics to W&B
wandb.log({"step": step, "loss": loss, "accuracy": accuracy})
print(f"Logged step {step}: loss={loss}, accuracy={accuracy}")
time.sleep(1) # Simulate time delay output
Logged step 1: loss=0.1, accuracy=0.84 Logged step 2: loss=0.2, accuracy=0.88 Logged step 3: loss=0.30000000000000004, accuracy=0.92 Logged step 4: loss=0.4, accuracy=0.96 Logged step 5: loss=0.5, accuracy=1.0
Common variations
You can log any numeric or media data by passing a dictionary to wandb.log. For example, log images, histograms, or custom objects. You can also log asynchronously or batch multiple metrics in one call.
import wandb
import numpy as np
from PIL import Image
wandb.init(project="my-project")
# Log multiple metrics at once
wandb.log({"loss": 0.25, "accuracy": 0.9, "epoch": 1})
# Log an image
image = Image.new("RGB", (64, 64), color="red")
wandb.log({"sample_image": wandb.Image(image)})
# Log a histogram
values = np.random.randn(1000)
wandb.log({"weights_histogram": wandb.Histogram(values)}) Troubleshooting
- If
wandb.logdoes not appear to send data, ensure you calledwandb.init()before logging. - If you see authentication errors, run
wandb loginagain or set theWANDB_API_KEYenvironment variable. - For slow logging, consider batching metrics or using
commit=Falseinwandb.logand callingwandb.logwithcommit=Trueless frequently.
Key Takeaways
- Always call wandb.init() before logging metrics with wandb.log.
- wandb.log accepts a dictionary of key-value pairs representing metrics or media.
- Use wandb.log inside your training loop to track metrics in real time.
- You can log images, histograms, and other media types with wandb.log.
- Troubleshoot by verifying authentication and proper initialization.