Claude Code for Weights & Biases: ML Experiment Tracking — Claude Skills 360 Blog
Blog / AI / Claude Code for Weights & Biases: ML Experiment Tracking
AI

Claude Code for Weights & Biases: ML Experiment Tracking

Published: September 5, 2027
Read time: 5 min read
By: Claude Skills 360

Weights & Biases tracks ML experiments with one line. pip install wandb. wandb.login() authenticates with API key. wandb.init(project="churn-model", name="gbm-v1", config={"lr": 0.05, "n_estimators": 200}, tags=["production", "sklearn"]) starts a run. wandb.log({"loss": 0.23, "auc": 0.87, "epoch": 5}) logs metrics — call in a loop for time series. wandb.log({"roc_curve": wandb.plot.roc_curve(y_true, y_proba, labels=["no_churn", "churn"])}). wandb.log({"conf_matrix": wandb.plot.confusion_matrix(probs=y_proba, y_true=y_true, class_names=["no", "yes"])}). wandb.log({"predictions": wandb.Table(dataframe=df)}) logs tabular data. Images: wandb.log({"chart": wandb.Image(fig)}). Artifacts: artifact = wandb.Artifact("churn-dataset", type="dataset"), artifact.add_dir("data/"), run.log_artifact(artifact). Model artifact: artifact = wandb.Artifact("churn-model", type="model"), artifact.add_file("model.pkl"), run.log_artifact(artifact). Download: artifact = run.use_artifact("churn-model:latest"), artifact.download(). wandb.summary["best_auc"] = 0.91 sets run summary. Sweeps: sweep_config = {"method": "bayes", "metric": {"goal": "maximize", "name": "auc"}, "parameters": {"lr": {"distribution": "log_uniform_values", "min": 0.001, "max": 0.1}}}, sweep_id = wandb.sweep(sweep_config, project="churn-model"), wandb.agent(sweep_id, function=train, count=50). HuggingFace: TrainingArguments(report_to="wandb") auto-integrates. run.finish(). Claude Code generates W&B training loops, sweep configs, artifact management, and TypeScript API clients.

CLAUDE.md for W&B

## W&B Stack
- Version: wandb >= 0.16
- Init: wandb.init(project, name, config=hyperparams_dict, tags=[...])
- Log: wandb.log({"metric": value}) — call per step/epoch for time series
- Summary: wandb.summary["key"] = value — per-run summary metric
- Artifacts: wandb.Artifact(name, type) → artifact.add_file/add_dir → run.log_artifact()
- Sweeps: wandb.sweep(config) → wandb.agent(sweep_id, fn, count)
- Finish: wandb.finish() — or use as context manager with wandb.init() as run:

Training with W&B Logging

# train.py — complete training script with W&B experiment tracking
from __future__ import annotations
import os
import pickle
import time

import numpy as np
import pandas as pd
import wandb
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import (
    average_precision_score,
    classification_report,
    confusion_matrix,
    roc_auc_score,
)
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler


FEATURE_COLS = ["age", "tenure_days", "monthly_spend", "support_tickets", "last_login_days"]
TARGET_COL   = "churned"
PROJECT      = "churn-prediction"


def train_model(config: dict | None = None) -> float:
    """Training function — works standalone or as a W&B sweep agent."""

    with wandb.init(config=config) as run:
        cfg = run.config

        # ── Load data ────────────────────────────────────────────────────
        train_df = pd.read_csv("data/train.csv")
        X = train_df[FEATURE_COLS].values
        y = train_df[TARGET_COL].values

        # ── Log dataset artifact ──────────────────────────────────────────
        dataset_artifact = wandb.Artifact(
            name="churn-dataset",
            type="dataset",
            description="Churn training dataset",
            metadata={"rows": len(train_df), "features": FEATURE_COLS},
        )
        dataset_artifact.add_file("data/train.csv")
        run.log_artifact(dataset_artifact)

        # ── Cross-validation with per-fold logging ────────────────────────
        cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
        fold_aucs: list[float] = []

        for fold, (train_idx, val_idx) in enumerate(cv.split(X, y)):
            X_tr, X_val = X[train_idx], X[val_idx]
            y_tr, y_val = y[train_idx], y[val_idx]

            pipeline = Pipeline([
                ("scaler", StandardScaler()),
                ("clf",    GradientBoostingClassifier(
                    n_estimators=cfg.n_estimators,
                    learning_rate=cfg.learning_rate,
                    max_depth=cfg.max_depth,
                    min_samples_leaf=cfg.min_samples_leaf,
                    subsample=cfg.subsample,
                    random_state=42,
                )),
            ])
            pipeline.fit(X_tr, y_tr)

            y_proba = pipeline.predict_proba(X_val)[:, 1]
            auc     = roc_auc_score(y_val, y_proba)
            ap      = average_precision_score(y_val, y_proba)
            fold_aucs.append(auc)

            run.log({
                "fold":     fold,
                "fold_auc": auc,
                "fold_ap":  ap,
            })

        mean_auc = float(np.mean(fold_aucs))

        # ── Final model on full training data ─────────────────────────────
        final_pipeline = Pipeline([
            ("scaler", StandardScaler()),
            ("clf",    GradientBoostingClassifier(
                n_estimators=cfg.n_estimators,
                learning_rate=cfg.learning_rate,
                max_depth=cfg.max_depth,
                min_samples_leaf=cfg.min_samples_leaf,
                subsample=cfg.subsample,
                random_state=42,
            )),
        ])
        final_pipeline.fit(X, y)
        y_proba_all = final_pipeline.predict_proba(X)[:, 1]
        y_pred_all  = final_pipeline.predict(X)

        # ── Log rich metrics ──────────────────────────────────────────────
        run.log({
            "cv_auc_mean":   mean_auc,
            "cv_auc_std":    float(np.std(fold_aucs)),
            "train_auc":     roc_auc_score(y, y_proba_all),
            "roc_curve":     wandb.plot.roc_curve(y, y_proba_all[:, np.newaxis], labels=["churn"]),
            "conf_matrix":   wandb.plot.confusion_matrix(
                probs=np.column_stack([1 - y_proba_all, y_proba_all]),
                y_true=y,
                class_names=["no_churn", "churn"],
            ),
        })

        # Log feature importance
        importances = final_pipeline.named_steps["clf"].feature_importances_
        fi_table = wandb.Table(
            columns=["feature", "importance"],
            data=sorted(zip(FEATURE_COLS, importances), key=lambda x: -x[1]),
        )
        run.log({"feature_importance": wandb.plot.bar(fi_table, "feature", "importance", title="Feature Importances")})

        # ── Model artifact ────────────────────────────────────────────────
        model_path = "model.pkl"
        with open(model_path, "wb") as f:
            pickle.dump(final_pipeline, f)

        model_artifact = wandb.Artifact(
            name="churn-model",
            type="model",
            description=f"GBM churn model - AUC {mean_auc:.4f}",
            metadata={
                "cv_auc": mean_auc,
                "n_estimators":  cfg.n_estimators,
                "learning_rate": cfg.learning_rate,
                "max_depth":     cfg.max_depth,
            },
        )
        model_artifact.add_file(model_path)
        run.log_artifact(model_artifact)

        wandb.summary["cv_auc"]    = mean_auc
        wandb.summary["best_fold"] = int(np.argmax(fold_aucs))

    return mean_auc


# ── Standalone training ──────────────────────────────────────────────────────

DEFAULT_CONFIG = {
    "n_estimators":    200,
    "learning_rate":   0.05,
    "max_depth":       4,
    "min_samples_leaf": 10,
    "subsample":       0.8,
}

if __name__ == "__main__":
    wandb.login()
    train_model(config=DEFAULT_CONFIG)

Hyperparameter Sweeps

# sweeps.py — W&B Bayesian hyperparameter sweep
import wandb
from train import train_model, PROJECT


SWEEP_CONFIG = {
    "method": "bayes",                  # bayes | grid | random
    "metric": {
        "goal": "maximize",
        "name": "cv_auc_mean",
    },
    "parameters": {
        "n_estimators":    {"values": [100, 200, 400, 600]},
        "learning_rate":   {"distribution": "log_uniform_values", "min": 0.005, "max": 0.2},
        "max_depth":       {"values": [2, 3, 4, 5, 6]},
        "min_samples_leaf": {"values": [5, 10, 20, 50]},
        "subsample":       {"distribution": "uniform", "min": 0.6, "max": 1.0},
    },
    "early_terminate": {
        "type": "hyperband",
        "min_iter": 3,
    },
}


def run_sweep(count: int = 50) -> None:
    """Launch Bayesian sweep with parallel agents."""
    sweep_id = wandb.sweep(SWEEP_CONFIG, project=PROJECT)
    print(f"Sweep ID: {sweep_id}")
    # Run agent — set count > 1 for multiple sequential runs per agent
    wandb.agent(sweep_id, function=train_model, count=count)


if __name__ == "__main__":
    wandb.login()
    run_sweep(count=50)

TypeScript API Client

// lib/wandb/client.ts — query W&B runs via REST API
const WANDB_API     = "https://api.wandb.ai"
const WANDB_API_KEY = process.env.WANDB_API_KEY ?? ""

export type WandbRun = {
  id:          string
  name:        string
  state:       string
  summary:     Record<string, number>
  config:      Record<string, unknown>
  created_at:  string
}

async function wandbFetch<T>(path: string): Promise<T> {
  const res = await fetch(`${WANDB_API}${path}`, {
    headers: { Authorization: `Basic ${btoa(`api:${WANDB_API_KEY}`)}` },
  })
  if (!res.ok) throw new Error(`W&B API ${res.status}: ${await res.text()}`)
  return res.json()
}

/** List runs for a project, sorted by best AUC */
export async function listRuns(entity: string, project: string): Promise<WandbRun[]> {
  const data = await wandbFetch<{ runs: WandbRun[] }>(
    `/api/v1/runs/${entity}/${project}?order=-summary_metrics.cv_auc_mean&per_page=50`
  )
  return data.runs
}

/** Get best run by a summary metric */
export async function getBestRun(
  entity:  string,
  project: string,
  metric:  string = "cv_auc_mean",
): Promise<WandbRun | null> {
  const runs = await listRuns(entity, project)
  return runs.sort((a, b) => (b.summary[metric] ?? 0) - (a.summary[metric] ?? 0))[0] ?? null
}

/** Download artifact URL */
export async function getArtifactUrl(
  entity:   string,
  project:  string,
  artifact: string,
  version:  string = "latest",
): Promise<string> {
  const data = await wandbFetch<{ artifact: { id: string; currentVersion: { id: string } } }>(
    `/api/v1/artifacts/${entity}/${project}/${artifact}/${version}`
  )
  return `${WANDB_API}/artifacts/${entity}/${project}/${artifact}/${version}`
}

For the MLflow alternative when needing a self-hosted, open-source experiment tracking server that runs inside your own infrastructure without a SaaS dependency — MLflow’s tracking server and model registry work identically on-prem or in any cloud while W&B is a managed SaaS service with richer built-in visualizations, collaboration features, interactive dashboards, and the Sweeps distributed hyperparameter search system. For the Neptune.ai alternative when needing unlimited storage for large media artifacts, custom metadata namespaces, advanced query language for run filtering, and team collaboration without per-seat pricing — Neptune offers more flexible artifact retention while W&B’s Artifacts system with lineage tracking and the W&B Table comparison tool provide industry-standard visualization for model debugging and dataset versioning. The Claude Skills 360 bundle includes W&B skill sets covering experiment logging, artifact management, Bayesian sweeps, and TypeScript API clients. Start with the free tier to try ML experiment tracking generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free