Skip to main content
Glama
README.md
# ML Experiment Tracker

[![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://python.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![MCP Compatible](https://img.shields.io/badge/MCP-compatible-purple)](https://modelcontextprotocol.io)
[![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff)

**Automated ML experiment tracker powered by Claude Code.**  
Log runs from any ML framework, auto-generate charts, and push results to **Notion** and **Google Sheets** via an MCP server — all in one line of code.

---

## Why this exists

Existing tools (MLflow, W&B, Neptune) are powerful but heavyweight — they require a running server, a cloud account, or complex setup just to log a training run. This project takes a different approach:

- **Zero-server local storage** — SQLite under `~/.ml_tracker/experiments.db`
- **One-line API** — `log_run(experiment, params, metrics)` and you're done
- **Claude Code MCP integration** — ask Claude natural questions like _"which run had the best F1 last week?"_ or _"compare my top 3 models"_
- **Automatic dashboards** — results flow to Notion and Google Sheets without any manual copy-paste
- **Framework-agnostic** — works with sklearn, PyTorch, XGBoost, Keras, or plain Python

---

## Quick Start

```bash
git clone https://github.com/tonyc973/ml-experiment-tracker
cd ml-experiment-tracker
pip install -e ".[all]"
cp .env.example .env   # fill in your API keys
```

```python
from ml_tracker import log_run

run = log_run(
    experiment="MyProject_Baseline",
    params={"learning_rate": 0.001, "epochs": 50, "batch_size": 32},
    metrics={"accuracy": 0.9423, "f1": 0.9311, "roc_auc": 0.9701},
    tags={"model": "xgboost", "dataset": "churn_v2"},
)
# ✓ Run logged a3f8b21e | MyProject_Baseline | metrics: ['accuracy', 'f1', 'roc_auc']
```

That's it. The run is saved locally and, if credentials are configured, synced to your Notion database and Google Sheet automatically.

---

## Features

| Feature | Description |
|---|---|
| **Local SQLite storage** | All runs saved to `~/.ml_tracker/experiments.db` — no cloud required |
| **Auto chart generation** | Metric bar charts and learning curves saved per run |
| **Notion sync** | Creates a rich database page per run with embedded charts |
| **Google Sheets sync** | Appends formatted rows; auto-creates the spreadsheet |
| **MCP server** | 8 tools for Claude Code — query, compare, and push runs via natural language |
| **CLI** | `ml-tracker list`, `ml-tracker best`, `ml-tracker push` |
| **Context manager** | `with start_run(...)` for automatic timing |
| **Environment capture** | Python version, library versions, git commit logged automatically |

---

## Context Manager (auto-timing)

```python
from ml_tracker import start_run

with start_run("CaliforniaHousing", params={"model": "GradientBoosting", "lr": 0.05}) as run:
    model.fit(X_train, y_train)
    run.metrics["rmse"] = compute_rmse(model, X_test, y_test)
    run.metrics["r2"]   = model.score(X_test, y_test)
# Duration is measured automatically
```

---

## Learning Curves

```python
history = {"train_loss": [], "val_accuracy": []}
for epoch in range(50):
    loss = train_one_epoch(model, loader)
    acc  = evaluate(model, val_loader)
    history["train_loss"].append((epoch, loss))
    history["val_accuracy"].append((epoch, acc))

log_run(
    experiment="NeuralNet_Sweep",
    params={"hidden": [128, 64], "lr": 0.001},
    metrics={"final_accuracy": acc},
    metrics_history=history,   # → generates learning_curves.png automatically
)
```

---

## Notion Setup

1. Go to [notion.so/my-integrations](https://www.notion.so/my-integrations) → **New integration**
2. Copy the **Internal Integration Token** → set as `NOTION_TOKEN`
3. Create a Notion database, open it, copy the ID from the URL → set as `NOTION_DATABASE_ID`
4. Share the database with your integration (click **Share → Invite**)

```bash
export NOTION_TOKEN=secret_xxxxx
export NOTION_DATABASE_ID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

The tracker will create a Notion page for each run with:
- All metrics as number properties (filterable/sortable)
- Params as a JSON code block
- Metric charts embedded as images

---

## Google Sheets Setup

1. Go to [Google Cloud Console](https://console.cloud.google.com/) → **APIs & Services** → **Credentials**
2. Create a **Service Account** → download the JSON key
3. Enable **Google Sheets API** and **Google Drive API**
4. Share your target spreadsheet with the service account's `client_email`

```bash
export GOOGLE_CREDS_JSON='{"type":"service_account","project_id":"..."}'
# OR
export GOOGLE_CREDS_FILE=./service_account.json
export GOOGLE_SHEET_NAME="ML Experiment Results"
```

---

## MCP Server (Claude Code Integration)

Add to your Claude Desktop or Claude Code config:

```json
{
  "mcpServers": {
    "ml-tracker": {
      "command": "python",
      "args": ["-m", "ml_tracker.server"],
      "cwd": "/path/to/ml-experiment-tracker/src"
    }
  }
}
```

Then ask Claude:

> _"What experiments have I run?"_  
> _"Which run had the best F1 score in BreastCancer_Classification?"_  
> _"Compare runs abc12345 and def67890 side by side."_  
> _"Push run abc12345 to Notion."_  
> _"Generate a comparison chart for accuracy across all MLP runs."_

### Available MCP Tools

| Tool | Description |
|---|---|
| `log_run` | Log a new run with params, metrics, tags |
| `get_runs` | List recent runs, optionally filtered by experiment |
| `get_best_run` | Find the run with the best metric value |
| `compare_runs` | Side-by-side comparison of multiple runs |
| `push_to_notion` | Push a run to your Notion database |
| `push_to_sheets` | Push a run to Google Sheets |
| `generate_comparison_chart` | Bar chart comparing a metric across runs |
| `list_experiments` | List all experiment names |
| `summarize_experiment` | Stats (min/max/mean/stdev) for all metrics |

---

## CLI

```bash
# List recent runs
ml-tracker list
ml-tracker list MyExperiment --limit 20

# Find the best run
ml-tracker best MyExperiment --metric accuracy
ml-tracker best MyExperiment --metric val_loss --lower

# List all experiments
ml-tracker experiments

# Push a run to dashboards
ml-tracker push abc12345 --notion
ml-tracker push abc12345 --sheets
ml-tracker push abc12345 --notion --sheets
```

---

## Project Structure

```
ml-experiment-tracker/
├── src/ml_tracker/
│   ├── __init__.py          # Public API: log_run, start_run, get_runs, ...
│   ├── models.py            # ExperimentRun dataclass
│   ├── tracker.py           # SQLite storage, log_run(), start_run(), get_*()
│   ├── visualizer.py        # matplotlib chart generation
│   ├── notion_backend.py    # Notion API integration
│   ├── sheets_backend.py    # Google Sheets / gspread integration
│   ├── server.py            # MCP server (8 tools)
│   └── cli.py               # Typer CLI
├── examples/
│   ├── sklearn_classification.py   # Multi-model breast cancer comparison
│   ├── sklearn_regression.py       # Regression with context manager
│   └── hyperparameter_search.py    # Grid search + learning curves
├── tests/
│   ├── test_models.py
│   └── test_tracker.py
├── .env.example
└── pyproject.toml
```

---

## Running Examples

```bash
pip install -e ".[dev]"

# Classification — compares 4 models on breast cancer dataset
python examples/sklearn_classification.py

# Regression — uses start_run() context manager
python examples/sklearn_regression.py

# Hyperparameter search — grid search with learning curves
python examples/hyperparameter_search.py
```

---

## Running Tests

```bash
pip install -e ".[dev]"
pytest tests/ -v
```

---

## Installation Options

```bash
# Core only (local storage + charts)
pip install -e .

# With Notion support
pip install -e ".[notion]"

# With Google Sheets support
pip install -e ".[sheets]"

# Everything
pip install -e ".[all]"

# Development (includes scikit-learn + test tools)
pip install -e ".[dev]"
```

---

## Environment Variables

| Variable | Required | Description |
|---|---|---|
| `NOTION_TOKEN` | Notion only | Integration token from notion.so/my-integrations |
| `NOTION_DATABASE_ID` | Notion only | Target database ID from the Notion URL |
| `GOOGLE_CREDS_JSON` | Sheets only | Service account JSON as a string |
| `GOOGLE_CREDS_FILE` | Sheets only | Path to service account JSON file |
| `GOOGLE_SHEET_NAME` | Sheets only | Spreadsheet name (default: "ML Experiment Results") |
| `ML_TRACKER_DB` | Optional | Override default SQLite path |

---

## License

MIT © [tonyc973](https://github.com/tonyc973)