{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import subprocess, sys, numpy, pandas\n", "from importlib.metadata import version\n", "from packaging.version import Version\n", "\n", "pins = [f\"numpy=={numpy.__version__}\", f\"pandas=={pandas.__version__}\"]\n", "\n", "def install(*packages):\n", " subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", *packages, *pins],\n", " check=True)\n", "\n", "install(\"m3-sc\")\n", "if Version(version(\"scanpy\")) < Version(\"1.12.5\"):\n", " install(\"pynndescent<0.7\")" ], "id": "cell-00" }, { "cell_type": "markdown", "id": "cell-01", "metadata": {}, "source": [ "# Donor-level disease prediction\n", "\n", "m3 can predict a **donor's** disease status from their cells, in a leave-one-batch-out\n", "setting: we hold out one batch (B3), hide its donors' labels during training, and\n", "predict them at the end. Runs on the built-in Liu subsample (same settings as the\n", "full-data tutorial; the held-out set is smaller, so numbers may differ a bit)." ] }, { "cell_type": "code", "id": "cell-02", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import m3\n", "\n", "OUT = \"./tutorial_out_demo/02_patient_prediction\"\n", "os.makedirs(OUT, exist_ok=True)" ] }, { "cell_type": "markdown", "id": "cell-03", "metadata": {}, "source": [ "## 1. Load the demo data" ] }, { "cell_type": "code", "id": "cell-04", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data = m3.datasets.liu_demo()\n", "print(data)" ] }, { "cell_type": "markdown", "id": "cell-05", "metadata": {}, "source": [ "## 2. Build the model with a held-out batch\n", "\n", "On top of the columns from the representation-learning tutorial, donor prediction\n", "needs a few more:\n", "\n", "- `target_condition`, the condition to predict (here `cond_group`, i.e. disease).\n", "- `donor_key`, the column identifying each donor, so cells are grouped per donor.\n", "- `held_out`, the batch(es) to hold back; these donors' `target_condition` labels\n", " are hidden during training and predicted at the end.\n", "\n", "`model.contract[\"reference_vocab\"]` shows the label set the model learned to predict\n", "(the held-out donors' labels never enter it)." ] }, { "cell_type": "code", "id": "cell-06", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model = m3.M3(\n", " data,\n", " condition_keys=[\"cond_group\", \"Age_interval\"],\n", " target_condition=\"cond_group\",\n", " celltype_key=\"mergedcelltype\",\n", " batch_key=\"batch\",\n", " donor_key=\"sample_id\",\n", " held_out=[\"B3\"],\n", " embedding_dim=30,\n", ")\n", "print(\"reference vocab:\", model.contract[\"reference_vocab\"][\"cond_group\"])" ] }, { "cell_type": "markdown", "id": "cell-07", "metadata": {}, "source": [ "`.train()` fits the integration model **and** the donor predictor. The donor\n", "predictor summarises each donor as a cell-type-balanced mean of the latent\n", "embedding, then removes batch effects from it by adversarial domain adaptation: a\n", "**corrector** reshapes the profile while a **batch discriminator** tries to\n", "identify the batch from it, and the corrector is trained to predict disease while\n", "preventing the discriminator from succeeding. The `donor_predictor` settings:\n", "\n", "- `patient_w` — weight of the donor objective relative to the cell-level VAE loss.\n", "- `adv_max` — the maximum strength of batch removal.\n", "- `adv_warmup` — number of epochs over which batch-removal strength ramps from 0 to `adv_max`.\n", "- `n_disc` — discriminator updates per corrector update.\n", "- `glr`, `n_epochs` — the corrector's learning rate and number of epochs.\n", "\n", "Afterwards `model.capabilities` shows that `predict_donors` is available.\n", "\n", "Training on the full demo takes about half an hour on a laptop CPU, and longer on\n", "Colab. To skip it, do not run the next cell; run the one after it, which loads the\n", "trained model from a file instead." ] }, { "cell_type": "code", "id": "cell-08", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model.train(\n", " max_epochs=500,\n", " donor_predictor={\n", " \"glr\": 3e-3, \"n_epochs\": 120, \"adv_max\": 10, \"adv_warmup\": 7,\n", " \"n_disc\": 21, \"patient_w\": 10,\n", " },\n", ")\n", "print(\"capabilities:\", model.capabilities)" ] }, { "cell_type": "markdown", "id": "cell-09", "metadata": {}, "source": [ "Instead of training, this cell loads the trained model from a file that ships with\n", "m3. The file was written with `model.save(...)` after the training above;\n", "`m3.M3.load(...)` reads it back and needs the same `data`." ] }, { "cell_type": "code", "id": "cell-10", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model = m3.M3.load(m3.datasets.liu_demo_model(\"patient_prediction\"), data)\n", "print(\"capabilities:\", model.capabilities)" ] }, { "cell_type": "markdown", "id": "cell-11", "metadata": {}, "source": [ "## 3. Predict the held-out donors\n", "\n", "`model.predict_donors()` returns one row per held-out donor: the predicted label and\n", "the probability of each class. We also save it to CSV." ] }, { "cell_type": "code", "id": "cell-12", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "preds = model.predict_donors()\n", "print(\"query donors:\", len(preds))\n", "print(preds.to_string(index=False))\n", "preds.to_csv(os.path.join(OUT, \"predictions.csv\"), index=False)" ] }, { "cell_type": "markdown", "id": "cell-13", "metadata": {}, "source": [ "## 4. Evaluate against the held-out truth\n", "\n", "The held-out donors' real labels are in the data (they were only hidden from the\n", "model). We join them back to score accuracy." ] }, { "cell_type": "code", "id": "cell-14", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# map each donor to its true label, then attach it to the predictions\n", "donor_truth = (data.obs[[\"sample_id\", \"cond_group\"]].astype(str)\n", " .drop_duplicates().set_index(\"sample_id\")[\"cond_group\"].to_dict())\n", "preds[\"true_label\"] = preds[\"sample_id\"].map(donor_truth)\n", "acc = float((preds[\"predicted_label\"] == preds[\"true_label\"]).mean())\n", "print(f\"held-out accuracy = {acc:.3f}\")" ] }, { "cell_type": "markdown", "id": "cell-15", "metadata": {}, "source": [ "## 5. Patient-level embedding\n", "\n", "`model.donor_embedding()` returns one vector per donor, the donor-level\n", "representation the model actually classifies. We build a small table describing each\n", "donor (reference vs held-out query, true label, correct/wrong) and UMAP the vectors." ] }, { "cell_type": "code", "id": "cell-16", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import umap\n", "\n", "demb = model.donor_embedding() # one row per donor\n", "info = model.predict_donors(include_reference=True).set_index(\"sample_id\").reindex(demb.index)\n", "info[\"true_label\"] = [donor_truth.get(d) for d in demb.index]\n", "info[\"set\"] = np.where(info[\"is_reference\"], \"reference\", \"query\")\n", "info[\"correct\"] = np.where(\n", " info[\"is_reference\"].to_numpy(), \"reference\",\n", " np.where(info[\"predicted_label\"].to_numpy() == info[\"true_label\"].to_numpy(),\n", " \"correct\", \"wrong\"))\n", "\n", "X = demb.drop(columns=[\"is_reference\"]).to_numpy()\n", "xy = umap.UMAP(n_neighbors=min(15, len(X) - 1), random_state=0).fit_transform(X)\n", "plot_df = info.assign(x=xy[:, 0], y=xy[:, 1])" ] }, { "cell_type": "markdown", "id": "cell-17", "metadata": {}, "source": [ "The same UMAP, coloured three ways: reference vs query, the true label, and whether\n", "each held-out prediction was correct." ] }, { "cell_type": "code", "id": "cell-18", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig, axes = plt.subplots(1, 3, figsize=(18, 5))\n", "for ax, key in zip(axes, [\"set\", \"true_label\", \"correct\"]):\n", " for val, sub in plot_df.groupby(key):\n", " ax.scatter(sub[\"x\"], sub[\"y\"], s=60, alpha=0.85, label=str(val))\n", " ax.set(title=f\"Patient embedding — {key}\", xticks=[], yticks=[])\n", " ax.legend(fontsize=8)\n", "fig.tight_layout()\n", "fig.savefig(os.path.join(OUT, \"patient_embedding_umap.png\"), dpi=130, bbox_inches=\"tight\")\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "cell-19", "metadata": {}, "source": [ "## 6. Save the patient embedding\n", "\n", "The donor vectors and labels, in the three formats from the representation-learning\n", "tutorial." ] }, { "cell_type": "code", "id": "cell-20", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import h5py\n", "import anndata as ad\n", "\n", "np.save(os.path.join(OUT, \"patient_embedding.npy\"), X)\n", "with h5py.File(os.path.join(OUT, \"patient_embedding.h5\"), \"w\") as f:\n", " f.create_dataset(\"data\", data=X)\n", " f.create_dataset(\"donor_name\", data=np.asarray(list(demb.index), dtype=\"S\"))\n", " f.create_dataset(\"label\", data=np.asarray(info[\"true_label\"].astype(str).to_numpy(), dtype=\"S\"))\n", " f.create_dataset(\"is_reference\", data=info[\"is_reference\"].to_numpy())\n", "ad.AnnData(X=X, obs=info[[\"set\", \"true_label\", \"correct\"]].astype(str)).write_h5ad(\n", " os.path.join(OUT, \"patient_embedding.h5ad\"))\n", "print(\"saved patient embedding -> .npy / .h5 (data+donor_name+label) / .h5ad in\", OUT)" ] }, { "cell_type": "markdown", "id": "cell-21", "metadata": {}, "source": [ "**Done.** Leave-one-batch-out donor prediction, evaluated against the held-out\n", "truth, with a patient-level embedding." ] } ], "metadata": { "jupytext": { "cell_metadata_filter": "-all", "main_language": "python", "notebook_metadata_filter": "-all" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 5 }