Darekdari / Google Colab Machine Learning

How to Track Experiment Results in Google Colab

Colab's runtime is temporary, so results you only print can vanish. Here is how to log every run to Google Drive, make results reproducible, and compare experiments with a simple CSV log, TensorBoard, Weights & Biases or MLflow.

Drive loggingReproducible runsTracker pickerChecked 2 Dec 2026
01 / The problem

Why You Need to Track Experiment Results in Google Colab

You run ten versions of a model, change the learning rate, swap the dataset, and by evening you cannot say which run gave the best score. Worse, Colab's runtime is temporary, so if you only print results to the screen they disappear with the session.

This guide shows how to track experiments in Google Colab in a way that survives disconnects: a simple log to Google Drive, TensorBoard, Weights & Biases and MLflow, plus the habits that make results reproducible.

Facts checked on 2 December 2026. Colab, library versions and tool pricing change. Check each tool's official docs before relying on a setting. The code below is a starting point, so adapt it to your project.
02 / What to track

What Should You Track in Every Experiment?

A result is only useful if you can explain how you got it. For every run, save these:

Configuration

Learning rate, batch size, epochs, model name, optimizer and any other hyperparameter.

Metrics

Accuracy, loss, F1 or whatever you judge by, for training and validation, plus the final test score.

Data and code version

Dataset name and version, split, preprocessing, and a git commit or notebook version.

Random seed

The seed lets you repeat the run and get the same numbers (within hardware limits).

Environment

Library versions and the hardware (CPU, GPU type) used.

Artifacts

Saved model, plots and predictions, stored in Drive and not only in /content.

03 / Choose a method

Which Tracking Method Should You Use?

Start simple. Move to a heavier tool only when you feel the pain.

Simplest

CSV and JSON in Drive

No account, no install. Great for students, small projects and quick comparisons.

Training curves

TensorBoard

Live loss and accuracy charts inside the notebook. Good for deep learning.

Team and cloud

Weights & Biases

Hosted dashboards, run comparison and sharing. Needs an account and an API key.

Self-managed

MLflow

Open-source tracking you control. Can log to a folder in Drive.

Live demo

Pick my tracker

04 / Save first

Step 1: Mount Google Drive and Create an Experiments Folder

Everything you want to keep must go to Drive. Files in /content disappear when the runtime is replaced. (See the guide on why Colab files disappear for details.)

cell.py
from google.colab import drive
drive.mount('/content/drive')

import os
BASE = '/content/drive/MyDrive/ColabProjects/experiments'
os.makedirs(BASE, exist_ok=True)
print('Saving experiments to', BASE)

Run this cell at the top of every notebook. The folder is created once and reused.

05 / Reproducible

Step 2: Fix the Random Seed

If you do not set a seed, two identical runs give different numbers and you cannot tell whether a change helped. Set it once at the top and log it.

cell.py
import random
import numpy as np

def set_seed(seed=42):
    random.seed(seed)
    np.random.seed(seed)
    try:
        import torch
        torch.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)
    except ImportError:
        pass

set_seed(42)

Some GPU operations are not fully deterministic, so tiny differences can remain. Record the seed anyway.

06 / Simple log

Step 3: Log Every Run to a CSV and JSON File

This small function appends one row per run to a CSV and saves the full details as JSON. It works with any framework.

cell.py
import csv, json, time, uuid

CSV_PATH = BASE + '/results.csv'

def log_run(config, metrics, notes=''):
    run_id = time.strftime('%Y%m%d-%H%M%S') + '-' + uuid.uuid4().hex[:4]
    row = {'run_id': run_id, 'notes': notes}
    row.update({'cfg_' + k: v for k, v in config.items()})
    row.update({'m_' + k: v for k, v in metrics.items()})

    # 1) one row per run in a shared CSV
    new_file = not os.path.exists(CSV_PATH)
    with open(CSV_PATH, 'a', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=list(row.keys()))
        if new_file:
            writer.writeheader()
        writer.writerow(row)

    # 2) full details in a JSON file per run
    with open(BASE + '/' + run_id + '.json', 'w') as f:
        json.dump({'config': config, 'metrics': metrics, 'notes': notes}, f, indent=2)
    return run_id

Use it after each experiment:

cell.py
config = {'model': 'logreg', 'lr': 0.01, 'epochs': 20, 'seed': 42}
metrics = {'val_acc': 0.912, 'val_loss': 0.31}

run_id = log_run(config, metrics, notes='baseline')
print('Logged', run_id)

If you change the columns between runs, the CSV header will no longer match. Keep the same keys, or start a new file.

07 / Compare

Step 4: Compare Your Runs

Load the CSV in a new cell and sort by the metric you care about. You can do this in a fresh runtime, because the file lives in Drive.

cell.py
import pandas as pd

df = pd.read_csv(CSV_PATH)
best = df.sort_values('m_val_acc', ascending=False)
best.head(10)

Add a plot if you like: best.plot(x='cfg_lr', y='m_val_acc', kind='scatter') shows how the learning rate relates to accuracy.

08 / TensorBoard

Track Training Curves with TensorBoard

TensorBoard shows loss and accuracy as charts while the model trains. Write logs to Drive so they survive a disconnect, then open the viewer in the notebook.

cell.py
from torch.utils.tensorboard import SummaryWriter

writer = SummaryWriter(BASE + '/tb_logs/run_01')
for epoch in range(20):
    train_loss = 1.0 / (epoch + 1)   # replace with your real value
    writer.add_scalar('loss/train', train_loss, epoch)
writer.close()
cell.py
%load_ext tensorboard
%tensorboard --logdir /content/drive/MyDrive/ColabProjects/experiments/tb_logs

Use a new subfolder per run (run_01, run_02) so you can overlay them.

09 / Weights and Biases

Track Experiments with Weights & Biases

Weights & Biases (W&B) logs metrics to a hosted dashboard, so you can compare runs from any device. Store your API key in Colab Secrets (the key icon in the left sidebar) instead of pasting it into the notebook.

cell.py
!pip install -q wandb

import wandb
from google.colab import userdata

wandb.login(key=userdata.get('WANDB_API_KEY'))

run = wandb.init(project='colab-experiments', config={'lr': 0.01, 'epochs': 20})
for epoch in range(20):
    wandb.log({'epoch': epoch, 'train_loss': 1.0 / (epoch + 1)})
run.finish()

Never share a notebook that contains a visible API key. Check the W&B docs for current free-tier limits.

10 / MLflow

Track Experiments with MLflow

MLflow records parameters, metrics and artifacts. Pointing its tracking location to a Drive folder keeps your history across sessions without a server.

cell.py
!pip install -q mlflow

import mlflow

mlflow.set_tracking_uri('file:///content/drive/MyDrive/ColabProjects/experiments/mlruns')
mlflow.set_experiment('colab-experiments')

with mlflow.start_run(run_name='baseline'):
    mlflow.log_param('lr', 0.01)
    mlflow.log_param('epochs', 20)
    mlflow.log_metric('val_acc', 0.912)

To get a browser view, run the MLflow UI on your own machine or a server, since Colab is not ideal for hosting one.

11 / Checkpoints

Save Models and Checkpoints Safely

A good result is useless if the model disappears. Save checkpoints to Drive during training, so a disconnect costs you minutes, not hours.

cell.py
import shutil

# save inside the loop, not only at the end
shutil.copy('/content/model.pt', BASE + '/model_' + run_id + '.pt')

Name files with the run ID so each model matches a row in your log.

12 / Good habits

Best Practices for Tracking Experiments

  • Change one thing at a time. Otherwise you cannot tell what caused the change.
  • Name runs clearly. Use a short note such as “lr 0.001, dropout 0.3”.
  • Log failures too. Bad runs teach you what not to repeat.
  • Keep a test set untouched until the end, and compare on the validation set while tuning.
  • Version your data. Note which dataset file and split you used.
  • Save the notebook to Drive and note the version or git commit.
  • Back up important results to your computer too.
13 / Mistakes

Common Experiment Tracking Mistakes in Colab

Mistake

Printing results only

Output vanishes with the session. Log to a file in Drive.

Mistake

Saving to /content

Temporary storage is wiped when the runtime is replaced.

Mistake

No seed

Results change between runs, so comparisons mean nothing.

Mistake

Tuning on the test set

It inflates your score and hides overfitting.

Mistake

Pasting API keys in cells

Use Colab Secrets so keys do not leak when you share the notebook.

Mistake

Not noting the data version

You cannot reproduce a result if the data changed.

14 / Checklist

Quick Checklist: Tracking Experiments in Colab

Tick the steps as you go.

0 of 10 done

FAQ

Frequently Asked Questions About Tracking Experiments in Colab

How do I track experiment results in Google Colab?

Save the configuration and metrics of every run to a file in Google Drive, such as a CSV or JSON, or use a tracker like TensorBoard, Weights & Biases or MLflow. Do not rely on printed output or on the /content folder.

Where should I save experiment results in Colab?

In a folder in Google Drive, for example /content/drive/MyDrive/ColabProjects/experiments. Files in /content are temporary and disappear when the runtime is replaced.

What is the easiest way to track experiments?

Appending one row per run to a CSV in Drive is the simplest. It needs no account and works with any framework.

Is TensorBoard free to use in Colab?

Yes. TensorBoard is open-source and can be loaded in a notebook with the tensorboard magic command. Write the logs to Drive so they persist.

Do I need an account for Weights & Biases?

Yes. You need a free or paid account and an API key. Store the key in Colab Secrets and check the current free-tier limits on the W&B site.

Can MLflow run in Google Colab?

Yes, you can log runs from Colab with a tracking location in Drive. Viewing the MLflow UI is easier on your own machine or a server.

How do I make my Colab results reproducible?

Set a random seed, log all hyperparameters, note the dataset version and library versions, and save the notebook and code version.

Why did my experiment results disappear in Colab?

Most likely they were only printed or saved in /content, which is wiped when the runtime is replaced. Save to Drive from the start.

Conclusion

Track It Once, Trust It Later

Good experiment tracking is mostly habit: fix the seed, log every configuration and metric to Drive, save checkpoints as you go, and compare runs in one place. Start with the CSV logger, and add TensorBoard, W&B or MLflow when your projects grow.

Want more? Explore Google Colab tutorials, Python exercises, machine learning projects and programming tutorials on Darekdari.com.

Learn more

More info about us

Scroll to Top