LSMA

LONDON SCHOOL OF MULTIOMICS & AI

LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 79 lessons

Integrating omics in practice with factor models and DIABLO

Integrating omics in practice with factor models and DIABLO

Integrating omics in practice with factor models and DIABLO

Prepare matched omics views, fit a MOFA+ factor model in Python and read its shared and view-specific factors, see what DIABLO optimises and why it overfits, and test whether an integration really beats a single layer.

From strategy to practice

Why multi-omics, and how layers are integrated set out three points at which layers can meet: early, intermediate and late. This lesson opens up the intermediate route in code, with the two methods you will meet most often in papers: MOFA, a factor model that finds patterns without being told any labels, and DIABLO, a supervised method that finds patterns separating known groups. It ends with how to judge whether an integration has earned its place.

In these methods each omics layer is called a view (MOFA's word) or a block (DIABLO's word): one table with a row per sample and a column per feature. Both need matched samples: the same patients, in the same order, in every view. The row is what ties the layers together. If row 12 is patient P012 in the RNA table and someone else in the protein table, the method will find links that are not there, so the sample checks of the previous lesson come first.

The data here are simulated, on purpose. With real data you never know which patterns are truly present, so you cannot tell whether a method found them. Here two hidden factors are planted. One, shared, moves a few features in all three views and also shapes a two-group label, subtype. The other, rna_only, moves a different set of RNA features. Everything else is noise, and the views have very different units. The code runs in Google Colab.

Python
import numpy as np, pandas as pd

rng = np.random.default_rng(7)
n = 150                                   # patients, the same in every view
ids = [f"P{i:03d}" for i in range(n)]

# SIMULATED data: we plant the hidden factors, so we know the right answer
shared   = rng.normal(size=n)             # moves all three views
rna_only = rng.normal(size=n)             # moves RNA only
subtype  = (shared + 0.5 * rng.normal(size=n) > 0).astype(int)   # 1 = subtype B

def make_view(n_feat, effects, scale, prefix):
    X = rng.normal(size=(n, n_feat))      # noise in every feature
    for factor, first, last in effects:   # a factor moves features first..last-1
        w = rng.choice([-1, 1], last - first) * rng.uniform(0.3, 0.8, last - first)
        X[:, first:last] += np.outer(factor, w)
    cols = [f"{prefix}{i:03d}" for i in range(n_feat)]
    return pd.DataFrame(X * scale, index=ids, columns=cols)

rna  = make_view(1000, [(shared, 0, 40), (rna_only, 40, 80)], 1.0,  "gene")
meth = make_view(400,  [(shared, 0, 30)],                    0.05, "cpg")
prot = make_view(80,   [(shared, 0, 15)],                    8.0,  "prot")

views = {"RNA": rna, "methylation": meth, "protein": prot}
for name, v in views.items():
    print(f"{name:12s} {v.shape}  overall SD {v.values.std():.2f}")
print("subtype B:", subtype.sum(), "of", n)
RNA (150, 1000) overall SD 1.01 methylation (150, 400) overall SD 0.05 protein (150, 80) overall SD 8.16 subtype B: 66 of 150

What this does

  • make_view builds one view: noise, plus each planted factor added to a block of features with random weights. The first 40 RNA genes, 30 CpG sites and 15 proteins follow shared; RNA genes 40 to 79 follow rna_only.
  • scale mimics different units: small numbers for methylation, large ones for protein intensities. Every view uses the same index, ids, so rows are matched.

Reading the output

Each view has 150 patients, with 1,000, 400 and 80 features, and the spread differs more than a hundredfold between methylation and protein. 66 patients are in subtype B.

Preparing the views: scaling and filtering

The previous lesson explained why scaling single features is not enough. In numbers: each view's share of the total variance across all three views, at three stages of preparation.

Python
def variance_share(vs):
    tot = {k: (v - v.mean()).pow(2).values.sum() for k, v in vs.items()}
    return {k: f"{100 * t / sum(tot.values()):.0f}%" for k, t in tot.items()}

print("raw values:          ", variance_share(views))

z = {k: (v - v.mean()) / v.std() for k, v in views.items()}   # every feature SD 1
print("each feature scaled: ", variance_share(z))

top = rna.var().sort_values(ascending=False).index[:200]      # 200 most variable genes
z["RNA"] = z["RNA"][top]
print("plus RNA filtered:   ", variance_share(z))
print("planted genes kept:", sum(int(g[4:]) < 80 for g in top), "of 80")
raw values: {'RNA': '16%', 'methylation': '0%', 'protein': '84%'} each feature scaled: {'RNA': '68%', 'methylation': '27%', 'protein': '5%'} plus RNA filtered: {'RNA': '29%', 'methylation': '59%', 'protein': '12%'} planted genes kept: 64 of 80

What this does

  • variance_share adds up each view's squared deviations from the feature means and reports its share of the grand total.
  • (v - v.mean()) / v.std() turns every feature into a z-score, with mean 0 and standard deviation 1.
  • rna.var() ranks genes by variance across patients; the 200 most variable are kept. The labels are never used.

Reading the output

On raw values, protein supplies 84% of all variance purely because of its units. After z-scoring, the ranking follows feature counts instead, and RNA, with 1,000 features, supplies 68%. Neither reflects biology. After filtering, the views are closer in weight, and the filter kept 64 of the 80 genes that carry planted signal, because genes driven by a factor vary more than noise.

So: put every view on a comparable scale, and filter each view to its informative features so that views have broadly similar sizes. The MOFA authors recommend this, because larger views tend to dominate the factors. Filter without labels, or inside cross-validation, for the reasons in Machine learning on an expression table: from patients to marker genes (Module 7). Real views also need their own normalisation first: library-size scaling and a log for counts (Module 4), beta or M-values for methylation, log intensities for proteomics.

Factor models: MOFA and MOFA+

MOFA (Multi-Omics Factor Analysis) describes every view as the product of two smaller tables. The factor scores, Z, have one row per patient and one column per factor, and are shared by all views. The weights, W, form one table per view, with a row per feature and a column per factor. Because Z is common to every view, a factor that explains variation in both RNA and protein must be the same pattern across patients in both. That is how the layers are linked.

  • Shared and view-specific factors. A prior, an assumption built into the model, lets each factor switch off in any view: its weights there shrink to zero unless the data support them. A factor active in every view is shared; one active in a single view is view-specific.
  • Sparse weights. A second prior pushes most individual weights to near zero, so each factor rests on a manageable set of features.
  • Missing views. The model fits only the values that exist, so a patient without proteomics still gets factor scores from their other views.

MOFA+, the current version, trains faster and supports groups of samples, such as several cohorts. Its engine is the Python package mofapy2; the R package MOFA2 calls the same engine and adds plotting tools. For single-cell data, the muon package wraps it as mu.tl.mofa.

Integrating omics in practice: factor models and DIABLO · LSMA free course Top: three views, RNA, methylation and protein, share the same patient rows; the bottom rows of the protein view are empty because those patients have no protein data. They are approximated by one table of factor scores, patients by factors, multiplied by one table of weights for each view. Bottom: a grid of variance explained from the code in this lesson. Factor 1 explains 4.2% of RNA, 1.9% of methylation and 3.8% of protein, so it is shared. Factor 2 explains 4.8% of RNA and almost nothing elsewhere, so it is specific to RNA. Factor 3 explains under 1% anywhere and is inactive. 1 · WHAT MOFA FITS none RNAMethylationProtein same patients in every row ≈ Z scores × W, one table per view factors × features which features each factor moves 2 · VARIANCE EXPLAINED (%), FROM THE CODE BELOW F1F2F3 RNAMethylationProtein 4.24.80.0 1.90.00.2 3.80.00.6 F1 · shared: active in all three views F2 · view-specific: RNA only F3 · inactive: under 1% anywhere
Figure 1. Top: MOFA approximates every view by one shared table of factor scores (patients × factors) multiplied by a table of weights for that view. Patients missing a whole view, like the dashed protein rows, still get scores from their other views. Bottom: the variance-explained grid from the run below, read column by column. Schematic, not to scale.
Python
!pip install -q mofapy2
import io, contextlib
from mofapy2.run.entry_point import entry_point

z["protein"].iloc[120:] = np.nan          # protein assay missing for 30 patients

names = list(z)
with contextlib.redirect_stdout(io.StringIO()):   # hide MOFA's long progress log
    ent = entry_point()
    ent.set_data_options(scale_views=False)
    ent.set_data_matrix([[z[k].values] for k in names],   # one list per view
                        likelihoods=["gaussian"] * 3,
                        views_names=names, samples_names=[ids],
                        features_names=[list(z[k].columns) for k in names])
    ent.set_model_options(factors=5)
    ent.set_train_options(iter=1000, convergence_mode="fast", seed=1, quiet=True)
    ent.build()
    ent.run()

Z = ent.model.nodes["Z"].getExpectation()          # factor scores: patients x factors
W = ent.model.nodes["W"].getExpectation()          # weights: one array per view
r2 = ent.model.calculate_variance_explained()[0]   # views x factors
print("scores:", Z.shape, "| weights:", [w.shape for w in W])
print(pd.DataFrame(100 * r2, index=names,
                   columns=[f"F{k+1}" for k in range(Z.shape[1])]).round(1))
scores: (150, 5) | weights: [(200, 5), (400, 5), (80, 5)] F1 F2 F3 F4 F5 RNA 4.2 4.8 0.0 0.4 0.3 methylation 1.9 0.0 0.2 0.0 0.0 protein 3.8 0.0 0.6 0.0 0.0

What this does

  • !pip install -q mofapy2 installs the package in Colab; this lesson used version 0.7.5.
  • The protein rows of the last 30 patients are set to NaN, as if their proteomics had failed. Nothing else is done about them.
  • The steps run in a fixed order: data options, data, model options, training options, build(), run(). Data go in as one list per view, each holding one table per sample group. MOFA centres features itself; scale_views=False because the views are already scaled.
  • factors=5 asks for up to five factors. "gaussian" suits continuous values; binary data would use "bernoulli" and counts "poisson". redirect_stdout just hides MOFA's long training log.
  • The last lines read the scores and weights and the variance explained (R²): the fraction of each view's variance that each factor reproduces.

Reading the output

Read the table a column at a time, as in Figure 1. F1 explains variance in all three views: a shared factor. F2 explains 4.8% of RNA and nothing elsewhere: an RNA-specific factor. F3 to F5 are inactive. MOFA was told neither how many real factors exist nor which views they touch, and recovered the planted design. The percentages are small because most features are noise; a few percent per factor is common in real data too.

Python
truth = pd.DataFrame({"shared": shared, "rna_only": rna_only, "subtype": subtype})
fac = pd.DataFrame(Z[:, :2], index=ids, columns=["F1", "F2"])
print(pd.concat([fac, truth.set_index(fac.index)], axis=1).corr()
        .loc[["F1", "F2"], ["shared", "rna_only", "subtype"]].round(2))

w1 = pd.Series(W[0][:, 0], index=z["RNA"].columns)          # RNA weights on F1
print("\ntop RNA genes on F1:", list(w1.abs().sort_values(ascending=False).index[:6]))

missing = fac.index[120:]                                    # no protein data
print("F1 vs shared, patients without protein:",
      round(np.corrcoef(fac.loc[missing, "F1"], shared[120:])[0, 1], 2))
shared rna_only subtype F1 -0.98 -0.08 -0.68 F2 0.07 0.96 0.11 top RNA genes on F1: ['gene027', 'gene032', 'gene004', 'gene025', 'gene018', 'gene026'] F1 vs shared, patients without protein: -0.99

What this does

  • The first block correlates the F1 and F2 scores with the planted factors and the label. With real data, known sample facts such as age or batch help name a factor.
  • W[0][:, 0] holds every gene's RNA weight on F1; the six largest in absolute size are printed.

Reading the output

F1 correlates −0.98 with shared, and F2 0.96 with rna_only. The minus sign means nothing: flipping a factor and its weights together leaves their product unchanged. So read scores and weights together: a gene with a large positive weight is high in patients with a high score. F1 also tracks the subtype (−0.68), though MOFA never saw labels. The top six F1 genes are all planted ones; with real genes, this list goes into the enrichment test of Pathways and enrichment analysis. The 30 patients without protein data still get F1 scores that track the truth (−0.99), from their RNA and methylation.

Go deeper: how many factors, and can you trust them?

Ask for more factors than you expect and ignore those that explain almost nothing; asking for too few can merge two patterns into one. Training starts from random values, so refit with several seeds or on subsets of samples and match factors between runs by correlating their scores. Name only factors that reappear. In real cohorts the strongest factors are often technical, such as batch.

Supervised integration with DIABLO

MOFA describes the main patterns, whatever they are. Often the question is narrower: which features, across layers, separate known groups, such as tumour subtypes or drug responders? DIABLO (Data Integration Analysis for Biomarker discovery using Latent cOmponents) is built for that. It is part of the R package mixOmics, as the function block.splsda, and is used from R, so here it is explained as a method and its core idea shown in Python.

What it optimises

DIABLO is a multi-block sparse PLS-DA (partial least squares discriminant analysis). For each block it builds a component, a weighted sum of the block's features, with one score per sample. The weights maximise, together, the covariance of each block's component with the groups and with the components of connected blocks. Sparse means a penalty sets most weights to zero, so each component uses only a chosen number of features per block. Later components are found the same way, uncorrelated with earlier ones.

The design matrix

Which blocks should agree is set by a design matrix, one row and column per block, holding values from 0 to 1. A 1 between RNA and protein favours components that agree strongly between them; a 0 ignores their link and concentrates on separating the groups. The aims pull against each other: the mixOmics authors suggest a low value such as 0.1 when prediction matters most. Report the design, because it changes the features chosen.

Choosing components and features, and the overfitting risk

The number of components and keepX, the features kept per block on each component, are chosen by repeated cross-validation: perf() estimates the error for each number of components, and tune.block.splsda() tries a grid of keepX values. A common starting point is one component fewer than the number of groups. With thousands of features and few samples, combinations that separate the training samples exist even in noise, so the familiar plot of samples on the first two components will look well separated whatever the data. It describes the training samples; it is not evidence. The evidence is the cross-validated error, with tuning inside every fold, and ideally a test on another cohort.

scikit-learn has no DIABLO, but its two-block ancestors are there. CCA (canonical correlation analysis) finds one component per block with the highest correlation; canonical PLS finds the highest covariance, DIABLO's criterion. Both are fitted to RNA and protein on 80 patients and checked on 40 more.

Python
from sklearn.cross_decomposition import CCA, PLSCanonical

A, B = rna[top].iloc[:120], prot.iloc[:120]     # patients with both views
tr, te = slice(0, 80), slice(80, 120)           # 80 to fit, 40 held out

for model in [CCA(n_components=1, max_iter=2000), PLSCanonical(n_components=1)]:
    model.fit(A.iloc[tr], B.iloc[tr])
    a_tr, b_tr = model.transform(A.iloc[tr], B.iloc[tr])
    a_te, b_te = model.transform(A.iloc[te], B.iloc[te])
    r_tr = np.corrcoef(a_tr[:, 0], b_tr[:, 0])[0, 1]
    r_te = np.corrcoef(a_te[:, 0], b_te[:, 0])[0, 1]
    r_true = abs(np.corrcoef(a_te[:, 0], shared[80:120])[0, 1])
    print(f"{type(model).__name__:13s} RNA-protein r: train {r_tr:.2f}, held out {r_te:.2f}"
          f" | held-out RNA score vs planted factor {r_true:.2f}")
CCA RNA-protein r: train 1.00, held out 0.44 | held-out RNA score vs planted factor 0.54 PLSCanonical RNA-protein r: train 0.91, held out 0.67 | held-out RNA score vs planted factor 0.92

What this does

  • Only the 120 patients with both views are used; DIABLO likewise expects every sample in every block. Both classes scale features using the training patients.
  • The code prints the RNA–protein score correlation on training and held-out patients, and how closely the held-out RNA score tracks the planted factor.

Reading the output

CCA reports a perfect 1.00 on training patients: with 280 features and 80 patients it can always make the two scores agree, signal or not. On held-out patients this falls to 0.44, and its RNA score follows the planted factor loosely (0.54). PLS reaches 0.91 in training but holds up far better (0.67) and recovers the planted factor closely (0.92). Maximising covariance keeps components tied to directions in which features really vary, a brake on overfitting. DIABLO adds sparsity as a second brake, and still needs cross-validation.

Judging an integration

Three questions decide whether an integration is worth reporting. Does it beat single views? Are its features stable? Did anything leak? The first is tested with the AUC from Measuring a model honestly: confusion matrix, ROC, precision, recall and imbalance, where 0.5 is guessing and 1 is perfect, scoring each view alone and all three joined on the same 50 splits.

Python
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score

y = subtype[:120]
blocks = {"RNA": rna[top], "methylation": meth, "protein": prot}
blocks = {k: v.iloc[:120] for k, v in blocks.items()}
blocks["all three"] = pd.concat(blocks.values(), axis=1)

cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=10, random_state=0)
auc = {}
for name, X in blocks.items():
    m = make_pipeline(StandardScaler(), LogisticRegression(C=0.05, max_iter=5000))
    auc[name] = cross_val_score(m, X, y, cv=cv, scoring="roc_auc")
    print(f"{name:12s} {X.shape[1]:4d} features  AUC {auc[name].mean():.2f} ± {auc[name].std():.2f}")

gain = auc["all three"] - auc["methylation"]          # same 50 splits, so compare pairwise
print(f"all three minus best single view: {gain.mean():+.3f}, better in {(gain > 0).sum()} of 50 splits")
RNA 200 features AUC 0.80 ± 0.08 methylation 400 features AUC 0.85 ± 0.06 protein 80 features AUC 0.79 ± 0.07 all three 680 features AUC 0.88 ± 0.07 all three minus best single view: +0.025, better in 34 of 50 splits

What this does

  • RepeatedStratifiedKFold repeats five-fold cross-validation ten times: 50 splits. Scaling sits inside the pipeline, and C=0.05 sets strong regularisation, keeping weights small.
  • Because every model sees the same splits, the last lines compare them split by split.

Reading the output

Single views reach 0.80, 0.85 and 0.79; all three together 0.88. Methylation, the view with the lowest R² in MOFA, predicts best: variance explained says how much of a view a factor accounts for, not how useful the view is for a question. The joined model wins by a small margin, typical when layers carry the same signal and combining them mostly averages away noise.

Worked example · is a gain of 0.025 real?

all three views − best single view = 0.88 − 0.85 ≈ +0.025
spread of each AUC across splits ≈ 0.07, almost three times the gain
splits won by the joined model = 34 ÷ 50 = 68%

Step by step. As two separate averages, a 0.025 difference disappears in a spread of 0.07. But both models met the same splits, so a hard split is hard for both; subtracting split by split removes that, and the joined model wins 34 of 50. The gain is small but consistent. Repeated splits reuse patients, so they are not independent, and the single view was picked after seeing results. Report such a gain with that context and confirm it in another cohort.

Are the chosen features stable?

DIABLO's keepX keeps a fixed number of features per block. The code mimics that simply: in each of the same 50 resamples, keep the 10 features per view that best separate the subtypes, and count how often each is kept.

Python
from sklearn.feature_selection import f_classif

keep = 10                                  # features per view, like DIABLO's keepX
counts = {k: pd.Series(0, index=blocks[k].columns) for k in ["RNA", "methylation", "protein"]}
for train, _ in cv.split(blocks["RNA"], y):          # the same 50 resamples
    for k in counts:
        F, _ = f_classif(blocks[k].iloc[train], y[train])
        best = np.argsort(F)[::-1][:keep]              # this resample's top 10
        counts[k].iloc[best] += 1

planted = {"RNA": 40, "methylation": 30, "protein": 15}   # first features moved by 'shared'
for k, c in counts.items():
    stable = c[c >= 40].index                          # chosen in at least 80% of resamples
    n_planted = sum(int(f[-3:]) < planted[k] for f in stable)
    print(f"{k:12s} chosen in 80%+ of resamples: {len(stable):2d}, planted: {n_planted}"
          f" | ever chosen: {(c > 0).sum()}")
RNA chosen in 80%+ of resamples: 6, planted: 6 | ever chosen: 22 methylation chosen in 80%+ of resamples: 5, planted: 5 | ever chosen: 20 protein chosen in 80%+ of resamples: 6, planted: 6 | ever chosen: 27

Reading the output

f_classif scores each feature on the training part of each split, and a feature kept in 40 or more of the 50 counts as stable. In every view, all the stable features (6, 5 and 6) are planted ones, yet 20 to 27 different features per view were chosen at least once. A single run would report 10 per view, some of them noise that happened to fit. Real signatures behave the same way. Report how often each feature was chosen.

Leakage, the multi-omics way

Leakage, test samples shaping the model, was shown in Module 7. Multi-omics adds routes:

  • Filtering or tuning outside the loop: choosing features, components, keepX or the design on all samples, then cross-validating.
  • Factors fitted on everyone: MOFA uses no labels, so this is milder, but test patients still shaped the factors. For a strict test, fit on training samples only or use an independent cohort.
  • Normalisation or batch correction of each view across all samples before the split.

MOFA was introduced by Argelaguet et al. 2018, Molecular Systems Biology, on chronic lymphocytic leukaemia samples with mutations, RNA, DNA methylation and drug response; its first factor captured the known IGHV mutation status. MOFA+ followed in Argelaguet et al. 2020, Genome Biology. DIABLO was described by Singh et al. 2019, Bioinformatics, and mixOmics by Rohart et al. 2017, PLoS Computational Biology. In integration papers, check for a comparison with single views, settings chosen inside cross-validation, and a separate test cohort.

Key point

Match the samples, scale and filter each view, then integrate. A factor model such as MOFA shows what varies across layers, and variance explained per view separates shared from view-specific factors. A supervised method such as DIABLO finds features that separate groups, and is trustworthy only after honest cross-validation. Either way, show that it beats single views, that its features are stable, and that nothing leaked.

Further reading · Module 6MOFA2 documentation: tutorials, including training from Python with mofapy2. · mixOmics: the R package that provides DIABLO, with case studies. · scikit-learn: Cross decomposition: CCA and PLS in Python. · All reading for this course

Check your understanding

1. In a MOFA model, factor 3 explains 6% of the variance in RNA and almost none in methylation or protein. How should you describe it?

2. A DIABLO plot shows tumour subtypes perfectly separated on the first two components. What does this show on its own?

3. RNA alone reaches a cross-validated AUC of 0.85 and RNA plus proteomics 0.87, with a spread of 0.07 across splits. What is the best next step?

Ask LSMA