From 85aaa69b80572428bf5dc2be60eb965cc97600b8 Mon Sep 17 00:00:00 2001 From: Edmund Miller Date: Fri, 9 Oct 2026 20:09:55 +0200 Subject: [PATCH] Add fixed Gradient XGBoost label-projection ensemble --- .../gradient_xgboost_ensemble/README.md | 24 +++++ .../gradient_xgboost_ensemble/config.vsh.yaml | 40 ++++++++ .../gradient_xgboost_ensemble/recipes.json | 92 +++++++++++++++++++ .../gradient_xgboost_ensemble/script.py | 64 +++++++++++++ 4 files changed, 220 insertions(+) create mode 100644 src/methods/gradient_xgboost_ensemble/README.md create mode 100644 src/methods/gradient_xgboost_ensemble/config.vsh.yaml create mode 100644 src/methods/gradient_xgboost_ensemble/recipes.json create mode 100644 src/methods/gradient_xgboost_ensemble/script.py diff --git a/src/methods/gradient_xgboost_ensemble/README.md b/src/methods/gradient_xgboost_ensemble/README.md new file mode 100644 index 0000000..7e80090 --- /dev/null +++ b/src/methods/gradient_xgboost_ensemble/README.md @@ -0,0 +1,24 @@ +# Gradient XGBoost ensemble + +This adapts ten frozen parameter recipes recovered from the Gradient kidney +label-projection campaign: top 3,000 supplied HVGs plus AQP3, normalized sparse +expression, and majority voting. Only training-cell labels are used at inference +fit time. It accepts the OpenProblems training/test API and emits predictions as +AnnData. AQP3 is resolved through feature names as well as the gene index. + +The recipes were selected after repeated feedback on the original test set +(263 attempts); they were subsequently reused without retuning in donor-fold +validation. The exact original ensemble membership is a source-supported +reconstruction and its original tie rule is unverified. This implementation +uses lexicographically smallest labels on tied votes, as in the frozen donor +validation. Dependency versions match the recovered producer Dockerfile. +Supplied cohort-wide HVG scores and normalization are reused; this component +does not fit preprocessing separately within folds. + +This contribution does not claim that the campaign score is an independently +validated OpenProblems leaderboard result. OpenProblems must evaluate this +adaptation on its own datasets. + +```sh +viash test src/methods/gradient_xgboost_ensemble/config.vsh.yaml +``` diff --git a/src/methods/gradient_xgboost_ensemble/config.vsh.yaml b/src/methods/gradient_xgboost_ensemble/config.vsh.yaml new file mode 100644 index 0000000..89c1c3c --- /dev/null +++ b/src/methods/gradient_xgboost_ensemble/config.vsh.yaml @@ -0,0 +1,40 @@ +__merge__: /src/api/comp_method.yaml +name: gradient_xgboost_ensemble +label: Gradient XGBoost ensemble +summary: Majority vote of ten fixed XGBoost classifiers on highly variable genes. +description: | + Train ten fixed XGBoost classifiers on normalized expression of the top + 3,000 highly variable genes, adding AQP3 when present. Predict by majority + vote, breaking ties by lexicographic label order. Parameters were selected + during a kidney label-projection campaign with repeated test feedback; + this contribution requires independent evaluation on OpenProblems datasets. + The tie rule is from a subsequent frozen donor validation, because the + original campaign's tie rule could not be verified. This is an adaptation + rather than an exact replay of the original score. +references: + doi: '10.1145/2939672.2939785' +links: + repository: https://github.com/dmlc/xgboost + documentation: https://xgboost.readthedocs.io/en/stable/index.html +info: + preferred_normalization: log_cp10k +authors: + - name: Edmund Miller + roles: [author] + info: + github: edmundmiller +resources: + - type: python_script + path: script.py + - path: recipes.json +engines: + - type: docker + image: openproblems/base_python:1 + setup: + - type: python + packages: [xgboost==3.4.1, scikit-learn==1.9.1, anndata==0.13.4, numpy==2.5.3, scipy==1.18.1, pandas==3.0.6] +runners: + - type: executable + - type: nextflow + directives: + label: [midtime, highmem, midcpu] diff --git a/src/methods/gradient_xgboost_ensemble/recipes.json b/src/methods/gradient_xgboost_ensemble/recipes.json new file mode 100644 index 0000000..2ec555a --- /dev/null +++ b/src/methods/gradient_xgboost_ensemble/recipes.json @@ -0,0 +1,92 @@ +[ + { + "n_hvg": 3000, + "n_estimators": 850, + "learning_rate": 0.05572301764105427, + "max_depth": 10, + "subsample": 0.8, + "colsample_bytree": 0.18, + "seed": 17 + }, + { + "n_hvg": 3000, + "n_estimators": 850, + "learning_rate": 0.0523475679682032, + "max_depth": 10, + "subsample": 0.8, + "colsample_bytree": 0.18, + "seed": 17 + }, + { + "n_hvg": 3000, + "n_estimators": 851, + "learning_rate": 0.08057190998396768, + "max_depth": 10, + "subsample": 0.8, + "colsample_bytree": 0.18, + "seed": 17 + }, + { + "n_hvg": 3000, + "n_estimators": 610, + "learning_rate": 0.0914207870888236, + "max_depth": 10, + "subsample": 0.8, + "colsample_bytree": 0.18, + "seed": 17 + }, + { + "n_hvg": 3000, + "n_estimators": 745, + "learning_rate": 0.062154911560308904, + "max_depth": 10, + "subsample": 0.8, + "colsample_bytree": 0.18, + "seed": 17 + }, + { + "n_hvg": 3000, + "n_estimators": 1100, + "learning_rate": 0.045, + "max_depth": 10, + "subsample": 0.8, + "colsample_bytree": 0.18, + "seed": 17 + }, + { + "n_hvg": 3000, + "n_estimators": 950, + "learning_rate": 0.061, + "max_depth": 10, + "subsample": 0.8, + "colsample_bytree": 0.18, + "seed": 17 + }, + { + "n_hvg": 3000, + "n_estimators": 1033, + "learning_rate": 0.06218229787146111, + "max_depth": 10, + "subsample": 0.8, + "colsample_bytree": 0.36045527470080035, + "seed": 17 + }, + { + "n_hvg": 3000, + "n_estimators": 950, + "learning_rate": 0.061, + "max_depth": 10, + "subsample": 0.8, + "colsample_bytree": 0.25, + "seed": 17 + }, + { + "n_hvg": 3000, + "n_estimators": 950, + "learning_rate": 0.061, + "max_depth": 10, + "subsample": 0.8, + "colsample_bytree": 0.2, + "seed": 17 + } +] diff --git a/src/methods/gradient_xgboost_ensemble/script.py b/src/methods/gradient_xgboost_ensemble/script.py new file mode 100644 index 0000000..800fa97 --- /dev/null +++ b/src/methods/gradient_xgboost_ensemble/script.py @@ -0,0 +1,64 @@ +import json +from pathlib import Path + +import anndata as ad +import numpy as np +import pandas as pd +from scipy import sparse +from sklearn.preprocessing import LabelEncoder +from xgboost import XGBClassifier + +## VIASH START +par = { + "input_train": "resources_test/task_label_projection/cxg_immune_cell_atlas/train.h5ad", + "input_test": "resources_test/task_label_projection/cxg_immune_cell_atlas/test.h5ad", + "output": "output.h5ad", +} +meta = {"name": "gradient_xgboost_ensemble", "resources_dir": "."} +## VIASH END + +train = ad.read_h5ad(par["input_train"]) +test = ad.read_h5ad(par["input_test"]) +if not train.var_names.equals(test.var_names): + raise ValueError("Training and test genes must have the same order") +if not train.obs_names.is_unique or not test.obs_names.is_unique: + raise ValueError("Cell identifiers must be unique") +if "label" not in train.obs or train.obs["label"].isna().any(): + raise ValueError("Every training cell needs a label") +if not np.isfinite(train.var["hvg_score"]).all(): + raise ValueError("HVG scores must be finite") + +recipes = json.loads((Path(meta["resources_dir"]) / "recipes.json").read_text()) +labels = LabelEncoder() +y_train = labels.fit_transform(train.obs["label"].astype(str)) +votes = np.zeros((test.n_obs, len(labels.classes_)), dtype=np.uint8) +threads = meta.get("cpus") or 1 +for recipe in recipes: + mask = np.zeros(train.n_vars, dtype=bool) + mask[np.argsort(train.var["hvg_score"].to_numpy())[-recipe["n_hvg"]:]] = True + names = train.var.get("feature_name", pd.Series(train.var_names, index=train.var_names)) + mask |= (names == "AQP3").to_numpy() | (train.var_names == "AQP3") + if not mask.any(): + raise ValueError("No expression features available") + x_train = train.layers["normalized"][:, mask].astype(np.float32) + x_test = test.layers["normalized"][:, mask].astype(np.float32) + if sparse.issparse(x_train): + x_train, x_test = sparse.csr_matrix(x_train), sparse.csr_matrix(x_test) + if len(labels.classes_) == 1: + predicted = np.zeros(test.n_obs, dtype=int) + else: + params = {k: v for k, v in recipe.items() if k not in ("n_hvg", "seed")} + model = XGBClassifier(**params, random_state=recipe["seed"], + tree_method="hist", n_jobs=threads, eval_metric="mlogloss") + model.fit(x_train, y_train) + predicted = model.predict(x_test).astype(int) + votes[np.arange(test.n_obs), predicted] += 1 + +# LabelEncoder sorts labels, so argmax resolves tied votes lexicographically. +output = ad.AnnData( + obs=pd.DataFrame({"label_pred": labels.inverse_transform(votes.argmax(axis=1))}, + index=test.obs_names), + uns={"method_id": meta["name"], "dataset_id": test.uns["dataset_id"], + "normalization_id": test.uns["normalization_id"]}, +) +output.write_h5ad(par["output"], compression="gzip")