> For the complete documentation index, see [llms.txt](https://docs.owkin.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.owkin.com/explore-and-analyse-data/data-analysis/patient-stratification-biomarkers/consensus-clustering.md).

# Consensus clustering

Discover patient or sample subgroups with similar numerical feature profiles using consensus agglomerative clustering.

Discover patient or sample subgroups with similar numerical feature profiles using consensus agglomerative clustering.

## Consensus agglomerative clustering

### Description

#### Analysis summary

Discovers patient or sample subgroups from a wide numeric feature table using consensus agglomerative clustering: repeated bootstrap subsamples test how consistently each pair of samples falls into the same cluster, and the final groups are the ones that co-cluster most reliably. The result reports a cluster label per sample, per-cluster separation statistics and a bootstrap-based stability score.

#### Computation

Runs consensus agglomerative clustering on the wide-format numeric feature matrix: each bootstrap iteration subsamples samples (and, optionally, features), clusters the subsample, and accumulates which sample pairs were sampled together and which of those co-clustered; dividing the two gives the consensus matrix, on which a final agglomerative clustering produces the cluster labels. Two consensus matrices are computed for every run. The 'train' one is the classic co-sampling consensus, counted over samples that were jointly subsampled. The 'test' one is built by a classifier: in each bootstrap, a classifier is fitted on the training split to recognise the clusters just found, then predicts cluster membership for the samples that were held out — the test consensus counts how often those never-clustered samples were predicted into the same cluster, so it measures how well the clustering structure generalises to unseen samples rather than how one subsample happened to cluster. The selected consensus mode's matrix drives the final labels. Stability is scored for both matrices with a two-proportion z-statistic comparing the rate at which pairs inside the same cluster co-cluster against the rate for pairs across clusters: a higher score means within-cluster pairs co-cluster much more consistently than between-cluster pairs, i.e. the clustering is stable and not an artefact of one particular subsample, while a score near zero means the clustering is no better than chance. The default stability variant rescales the statistic by the number of co-sampled pairs so scores stay comparable across cohort sizes and bootstrap counts. Per-cluster silhouette and nearest-neighbour-purity statistics are computed in the original feature space used for clustering — not in any 2-D rendering — so they validate clustering quality independently of the visualisation choice and complement the bootstrap-based stability score.

#### When to use

Use to discover unknown patient or sample subgroups from a mix of numeric features — gene expression, gene-signature scores, clinical numerics, histomics fractions — without predefining the groups. Not for clustering individual cells (scRNA-seq) or spots (spatial transcriptomics), and not for displaying a named, small feature panel as a heatmap annotated by known categorical variables — that is aggregation\_analysis's complex\_heatmap mode.

#### Caveats

The clusters reflect whatever features the query supplies: batch correction is a prerequisite — do not combine datasets, or centres/batches within one dataset, without correcting that effect first, since the batch stratification column only balances the bootstrap splits and does not correct the signal; uncorrected, the clusters will reflect batch, not biology. The number of clusters must be chosen up front — the analysis does not select it. Feature columns must be complete and numeric: missing values are not imputed, and the analysis raises on the first null or non-numeric feature column.

### Example questions

<details>

<summary><code>example questions</code></summary>

* Discover unsupervised patient subgroups from a mix of bulk RNA-seq gene expression, gene-signature scores and clinical numerics using consensus agglomerative clustering, visualised as a 2-D UMAP scatter plot coloured by cluster label
* Discover unsupervised patient subgroups from a mix of bulk RNA-seq gene expression, histomics fractions and clinical numerics using consensus agglomerative clustering, visualised as a diagonal\_heatmap of the consensus matrix with hierarchical-clustering dendrograms

</details>

### Input columns

<details>

<summary><code>input columns</code></summary>

| column       | type        | required | description                                                                                                                                                        |
| ------------ | ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| index        | any         | required | Sample or patient identifier — one row per sample/patient to cluster.                                                                                              |
| patient\_id  | categorical | required | Patient identifier required for population summary plots.                                                                                                          |
| batch\_group | categorical | optional | Batch / clinical stratification label per sample. SELECT this column whenever the user asks to cluster 'stratified by X' / 'by X' (e.g. gender, clinical centre…   |
|              | numeric     | required | One column per clustering feature — anything numeric the SQL SELECT'd besides index, patient\_id, and batch\_group. Mix kinds freely: gene expression (TPM/log-no… |

</details>

### Visualizations

* `scatter` How to read: Each dot is one sample or patient, placed by a 2-D UMAP embedding of the feature matrix and coloured by its cluster label — good for a quick visual sense of how well the discovered subgroups separate. Tight, disjoint point clouds indicate well-separated clusters; overlapping clouds suggest the chosen cluster count may not fit the data. UMAP positions are qualitative — do not over-read distances or shapes — and the quantitative check is the per-cluster silhouette and purity statistics, computed in the original feature space rather than this rendering.
* `diagonal_heatmap` How to read: Square heatmap of the consensus matrix: cell (i, j) is the bootstrap frequency with which samples i and j co-clustered (diagonal = 1), with a single top dendrogram driven by the agglomerative clustering that produced the final labels — rows and columns share the dendrogram's leaf order. Sharp, bright diagonal blocks mean stable, well-separated clusters; fuzzy blocks or bright off-diagonal signal mean unstable or overlapping ones — this is the view for judging cluster stability. Hovering a cell shows the pair's co-clustering frequency.

### Example analysis 1

#### Name — Consensus Agglomerative Clustering of Mosaic Bladder Patients by Gene Expression (ERBB2, ROR1, CD8A, TP53) + Immune Signature + Age

#### Analysis parameters

<details>

<summary><code>analysis_name, analysis_params, viz_params</code></summary>

```json
{
  "analysis_name": "consensus_agglomerative_clustering",
  "analysis_params": {
    "n_clusters": 8,
    "n_bootstrap": 50,
    "prop_sample": 0.8,
    "prop_features": 1.0,
    "seed": 0,
    "stability_method": "sharp_normalized",
    "consensus_mode": "train",
    "n_neighbors_umap": 15,
    "min_dist_umap": 0.1
  },
  "viz_params": {
    "plot_name": "scatter",
    "color_label": "Cluster",
    "title": "Consensus Agglomerative Clustering of Mosaic Bladder Patients by Gene Expression (ERBB2, ROR1, CD8A, TP53) + Immune Signature + Age"
  }
}
```

</details>

#### Visualization — `scatter`

![Consensus Agglomerative Clustering of Mosaic Bladder Patients by Gene Expression (ERBB2, ROR1, CD8A, TP53) + Immune Signature + Age](https://1034377358-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTmCjUj6W0sltjW7q2vBp%2Fuploads%2Fgit-blob-222596c7b00ee983ec6e6330673326278792bd3a%2Fconsensus_agglomerative_clustering__consensus_clustering__scatter.png?alt=media)

#### Output table

<details>

<summary><code>descriptive_stats</code> (8 rows)</summary>

| cluster | n | n\_clusters | silhouette\_category\_mean | nn\_purity\_category\_mean | silhouette\_global\_mean | silhouette\_n\_samples | nn\_purity\_global\_mean |
| ------- | - | ----------- | -------------------------- | -------------------------- | ------------------------ | ---------------------- | ------------------------ |
| 0       | 6 | 8           | -0.02272                   | 0.3846                     | -0.07557                 | 14                     | 0.1758                   |
| 1       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |
| 2       | 2 | 8           | -0.4608                    | 0.07692                    | -0.07557                 | 14                     | 0.1758                   |
| 3       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |
| 4       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |
| 5       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |
| 6       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |
| 7       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |

</details>

<details>

<summary><code>statistical_tests</code> (2 rows)</summary>

| consensus\_mode | stability\_score |
| --------------- | ---------------- |
| train           | 0.5727           |
| test            | 0.5068           |

</details>

### Example analysis 2

#### Name — Consensus Matrix of Mosaic Bladder Patients by Gene Expression (ERBB2, ROR1, CD8A, TP53) + Immune Signature + Age

#### Analysis parameters

<details>

<summary><code>analysis_name, analysis_params, viz_params</code></summary>

```json
{
  "analysis_name": "consensus_agglomerative_clustering",
  "analysis_params": {
    "n_clusters": 8,
    "n_bootstrap": 50,
    "prop_sample": 0.8,
    "prop_features": 1.0,
    "seed": 0,
    "stability_method": "sharp_normalized",
    "consensus_mode": "train",
    "n_neighbors_umap": 15,
    "min_dist_umap": 0.1
  },
  "viz_params": {
    "plot_name": "diagonal_heatmap",
    "title": "Consensus Matrix of Mosaic Bladder Patients by Gene Expression (ERBB2, ROR1, CD8A, TP53) + Immune Signature + Age"
  }
}
```

</details>

#### Visualization — `diagonal_heatmap`

![Consensus Matrix of Mosaic Bladder Patients by Gene Expression (ERBB2, ROR1, CD8A, TP53) + Immune Signature + Age](https://1034377358-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTmCjUj6W0sltjW7q2vBp%2Fuploads%2Fgit-blob-a4c23827685b75650153030f509369699b1fd363%2Fconsensus_agglomerative_clustering__consensus_clustering__diagonal_heatmap.png?alt=media)

#### Output table

<details>

<summary><code>descriptive_stats</code> (8 rows)</summary>

| cluster | n | n\_clusters | silhouette\_category\_mean | nn\_purity\_category\_mean | silhouette\_global\_mean | silhouette\_n\_samples | nn\_purity\_global\_mean |
| ------- | - | ----------- | -------------------------- | -------------------------- | ------------------------ | ---------------------- | ------------------------ |
| 0       | 6 | 8           | -0.02272                   | 0.3846                     | -0.07557                 | 14                     | 0.1758                   |
| 1       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |
| 2       | 2 | 8           | -0.4608                    | 0.07692                    | -0.07557                 | 14                     | 0.1758                   |
| 3       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |
| 4       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |
| 5       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |
| 6       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |
| 7       | 1 | 8           | 0.0                        | 0.0                        | -0.07557                 | 14                     | 0.1758                   |

</details>

<details>

<summary><code>statistical_tests</code> (2 rows)</summary>

| consensus\_mode | stability\_score |
| --------------- | ---------------- |
| train           | 0.5727           |
| test            | 0.5068           |

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.owkin.com/explore-and-analyse-data/data-analysis/patient-stratification-biomarkers/consensus-clustering.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
