Skip to main content

MetVAE

Sparse correlation networks from untargeted metabolomics data, with variational autoencoder imputation of values below the detection limit.

Metabolomics correlation released R Python GNPS

MetVAE constructs a correlation network from untargeted metabolomics data. Zeros in the abundance table are treated as values below the detection limit and imputed by a variational autoencoder. The effects of the specified sample covariates are removed, and a sparse correlation matrix between metabolite features is estimated. Pairs are retained either by Fisher z-tests with multiple-testing correction (sparse_by_p) or by the sparse estimation of correlation (SEC) estimator with a penalty selected by cross-validation (sparse_by_sec).

Platforms

Platform Package Install Documentation
R MetVAE BiocManager::install("MATRIX-Research-Lab/MetVAE"), then torch::install_torch() GitHub · vignette("MetVAE")
Python metvae (PyPI) pip install metvae PyPI · GitHub
GNPS GNPS_Local See the documentation GitHub · Documentation

The R package is installed from GitHub; its Bioconductor submission is under review. GNPS_Local is an offline, single-user version of GNPS molecular networking with a graphical interface.

Extended tutorial

The R tutorial estimates a metabolite correlation network from the stool metabolomes of the PRISM and validation cohorts of Franzosa et al. (2019), which include patients with Crohn’s disease (CD), patients with ulcerative colitis (UC), and controls. The data are the processed tables of the curated microbiome–metabolome collection of Muller et al. (2022). The network is adjusted for diagnosis, age, and cohort, so that it describes the co-variation of metabolites within these strata.

Select a platform.

Model

Let \(y_{ij}\) denote the abundance of metabolite \(j\) in sample \(i\), for \(i = 1, \ldots, n\) and \(j = 1, \ldots, p\), and let \(z_{ij}\) denote its value on the centered log-ratio (CLR) scale. Let \(\mathbf{x}_i\) denote the covariate vector of sample \(i\). MetVAE assumes the left-censored normal model

\[ z_{ij} = \mu_j + \mathbf{x}_i^\top \boldsymbol{\gamma}_j + \sigma_j \varepsilon_{ij}, \qquad \varepsilon_{ij} \sim N(0, 1), \]

in which a zero is recorded when the abundance falls below the detection limit. The parameters \(\mu_j\), \(\boldsymbol{\gamma}_j\), and \(\sigma_j\) are estimated under censoring, and the covariate effects are removed. A variational autoencoder trained on the adjusted data imputes the censored values \(M\) times. For imputation \(s\), let \(\tilde{z}^{(s)}_{ij}\) denote the completed adjusted data. The correlation of metabolites \(j\) and \(k\) is estimated from the variance of their log ratio,

\[ \hat{r}^{(s)}_{jk} = \frac{\widehat{\mathrm{Var}}\big(\tilde{z}^{(s)}_{\cdot j}\big) + \widehat{\mathrm{Var}}\big(\tilde{z}^{(s)}_{\cdot k}\big) - \widehat{\mathrm{Var}}\big(\tilde{z}^{(s)}_{\cdot j} - \tilde{z}^{(s)}_{\cdot k}\big)}{2 \, \widehat{\mathrm{SD}}\big(\tilde{z}^{(s)}_{\cdot j}\big) \, \widehat{\mathrm{SD}}\big(\tilde{z}^{(s)}_{\cdot k}\big)}, \]

and the estimate \(\hat{r}_{jk}\) is the mean of \(\hat{r}^{(s)}_{jk}\) over the \(M\) imputations, after entries with \(|\hat{r}^{(s)}_{jk}|\) below a threshold are set to zero.

Two procedures produce a sparse network. The first tests \(H_0: r_{jk} = 0\) with

\[ T_{jk} = \operatorname{atanh}(\hat{r}_{jk}) \sqrt{n - 3} \]

and retains the pairs whose adjusted p-value is below a cutoff. The second, SEC (Cui, Leng and Sun, 2016), solves

\[ \hat{\mathbf{R}} = \operatorname*{arg\,min}_{\mathbf{R}} \; \tfrac{1}{2} \lVert \mathbf{R} - \hat{\mathbf{R}}_0 \rVert_F^2 + \rho \sum_{j \ne k} \frac{|R_{jk}|}{|\hat{r}_{jk}|} \quad \text{subject to} \quad \lambda_{\min}(\mathbf{R}) \ge \epsilon, \]

where \(\hat{\mathbf{R}}_0\) is the matrix of the estimates \(\hat{r}_{jk}\), and the penalty \(\rho\) is selected by cross-validation.

Data

The metabolomics table has one row per sample and one column per LC-MS feature. The tutorial retains the features with a compound name. Features with the same HMDB identifier, or without one and with names that differ only by a trailing asterisk, are treated as one compound, and for each compound the feature with the smallest proportion of zeros is retained.

library(MetVAE)
library(tidyverse)
library(igraph)

url <- paste0("https://raw.githubusercontent.com/borenstein-lab/",
              "microbiome-metabolome-curated-data/main/data/processed_data/",
              "FRANZOSA_IBD_2019/")

meta <- read.delim(paste0(url, "metadata.tsv"), check.names = FALSE)
fmap <- read.delim(paste0(url, "mtb.map.tsv"), check.names = FALSE)
mtb  <- read.delim(paste0(url, "mtb.tsv"), check.names = FALSE, row.names = 1)
mtb  <- as.matrix(mtb)

# Features with a compound name; one feature per compound.
named <- fmap |>
  filter(!is.na(Compound.Name), Compound %in% colnames(mtb)) |>
  mutate(name = str_remove(Compound.Name, "[*]+$"),
         key  = coalesce(HMDB, name),
         zero = colMeans(mtb[, Compound] == 0),
         med  = apply(mtb[, Compound], 2, median)) |>
  arrange(key, zero, desc(med)) |>
  distinct(key, .keep_all = TRUE) |>
  distinct(name, .keep_all = TRUE)

y <- mtb[, named$Compound]
colnames(y) <- named$name
dim(y)
#> [1] 220 338
meta <- meta |>
  mutate(diagnosis = factor(Study.Group, levels = c("Control", "CD", "UC")),
         cohort    = factor(if_else(str_starts(Sample, "PRISM"), "PRISM", "Validation"))) |>
  column_to_rownames("Sample")

table(Diagnosis = meta$diagnosis, Cohort = meta$cohort)
#>          Cohort
#> Diagnosis PRISM Validation
#>   Control    34         22
#>   CD         68         20
#>   UC         53         23
tibble(zero = colMeans(y == 0)) |>
  ggplot(aes(x = zero)) +
  geom_histogram(binwidth = 0.025, boundary = 0, fill = "grey70", color = "grey30") +
  geom_vline(xintercept = 0.3, linetype = "dashed") +
  labs(x = "Proportion of zeros", y = "Number of metabolites") +
  theme_minimal(base_size = 12)
Figure 1: Proportion of zeros of each metabolite. Metabolites to the right of the dashed line are removed by the default filter of metvae().

Fitting the model

fit <- metvae(y, meta = meta[, c("Age", "diagnosis", "cohort")],
              continuous_covariate_keys = "Age",
              categorical_covariate_keys = c("diagnosis", "cohort"),
              feature_zero_threshold = 0.3,
              seed = 1L)
Argument Role
meta Sample metadata, with the sample names as row names.
continuous_covariate_keys Numeric covariates; they are centered and scaled.
categorical_covariate_keys Categorical covariates, coded by indicators with the first level as reference.
feature_zero_threshold Metabolites with a larger proportion of zeros are removed.
seed Seed of the initialization, the batch order, and the imputations.
tibble(epoch = seq_along(fit$train_loss), loss = fit$train_loss) |>
  ggplot(aes(x = epoch, y = loss)) +
  geom_line(color = "grey30") +
  labs(x = "Epoch", y = "Loss") +
  theme_minimal(base_size = 12)
Figure 2: Training loss of the variational autoencoder by epoch.

Correlation estimate

get_corr() imputes the zeros num_sim times and averages the correlation matrices of the completed data sets.

fit <- get_corr(fit, num_sim = 100L, threshold = 0.2)
p <- length(fit$feature_names)
p
#> [1] 291

The analysis retains 291 of the 338 metabolites, which give 42,195 pairs.

Sparse networks

res_p   <- sparse_by_p(fit, p_adj_method = "fdr_bh", cutoff = 0.05)
res_sec <- sparse_by_sec(fit, c_grid = c(0.05, 0.1, 0.25, 0.5, 1, 2, 4, 8),
                         refine = FALSE, seed = 1L)

n_edges <- function(m) (Matrix::nnzero(m) - nrow(m)) / 2
c(fdr = n_edges(res_p$sparse_estimate), sec = n_edges(res_sec$sparse_estimate))
#>   fdr   sec 
#> 12990  8895
res_sec$scores_by_rho |>
  ggplot(aes(x = rho, y = score)) +
  geom_line(color = "grey30") +
  geom_point(size = 1.5) +
  geom_vline(xintercept = res_sec$best_rho, linetype = "dashed") +
  scale_x_log10() +
  labs(x = expression(rho ~ "(log scale)"), y = "Validation error") +
  theme_minimal(base_size = 12)
Figure 3: Cross-validation error of SEC by penalty. The dashed line marks the selected penalty.

The grid of the penalty is \(\rho = c \sqrt{\log p / n}\) for the listed values of \(c\). The validation error decreases as \(\rho\) decreases over the whole grid, and cross-validation selects the smallest value, \(\rho =\) 0.00803. In these data the penalty therefore shrinks the estimate little, and the zeros of the SEC estimate arise mainly from the thresholds of get_corr() (0.2) and sparse_by_sec() (0.1).

Results

The pairs retained by SEC, with the strongest correlations first:

class_of <- setNames(coalesce(named$Putative.Chemical.Class, "Not assigned"), named$name)

edges <- Matrix::summary(res_sec$sparse_estimate) |>
  as_tibble() |>
  filter(i < j) |>
  transmute(metabolite_1 = fit$feature_names[i],
            metabolite_2 = fit$feature_names[j],
            r = x,
            class_1 = class_of[metabolite_1],
            class_2 = class_of[metabolite_2]) |>
  arrange(desc(abs(r)))

knitr::kable(head(edges, 15), digits = 2,
             caption = "Metabolite pairs with the largest absolute SEC correlation.")
Metabolite pairs with the largest absolute SEC correlation.
metabolite_1 metabolite_2 r class_1 class_2
guanosine 8-hydroxy-deoxyguanosine 0.94 Purine nucleosides Purine nucleosides
leucine valine 0.94 Amino acids, peptides, and analogues Amino acids, peptides, and analogues
C52:3 TAG C54:4 TAG 0.94 Triacylglycerols Not assigned
alanine leucine 0.93 Amino acids, peptides, and analogues Amino acids, peptides, and analogues
alanine valine 0.93 Amino acids, peptides, and analogues Amino acids, peptides, and analogues
C22:1 MAG 7-hexadecenoic acid methyl ester 0.93 1-monoacylglycerols Fatty acid methyl esters
C53:3 TAG C56:4 TAG 0.93 Not assigned Not assigned
uridine 8-hydroxy-deoxyguanosine 0.93 Not assigned Purine nucleosides
C52:2 TAG C54:4 TAG 0.92 Not assigned Not assigned
C53:3 TAG C54:2 TAG 0.92 Not assigned Not assigned
C52:2 TAG C52:3 TAG 0.92 Not assigned Triacylglycerols
threonine valine 0.92 L-alpha-amino acids Amino acids, peptides, and analogues
guanosine uridine 0.92 Purine nucleosides Not assigned
C54:2 TAG C56:4 TAG 0.92 Not assigned Not assigned
C52:4 TAG C54:5 TAG 0.92 Not assigned Not assigned
both <- edges |>
  mutate(fdr = as.matrix(res_p$sparse_estimate)[cbind(metabolite_1, metabolite_2)] != 0)
mean(both$fdr)
#> [1] 0.9718943

Of the pairs retained by SEC, a proportion of 0.97 are also retained by the Fisher z-tests at a false discovery rate of 0.05.

strong <- filter(edges, abs(r) >= 0.7)
g <- graph_from_data_frame(strong[, c("metabolite_1", "metabolite_2", "r")], directed = FALSE)

top_class <- setdiff(names(sort(table(class_of[V(g)$name]), decreasing = TRUE)), "Not assigned")[1:6]
palette   <- setNames(c("#a63d2f", "#476e61", "#a47b36", "#625d78", "#466675", "#c26743"), top_class)
V(g)$color <- coalesce(palette[class_of[V(g)$name]], "grey80")
# Label the metabolite with the most pairs in each cluster of at least five metabolites.
comp <- components(g)$membership
hub  <- tapply(seq_len(vcount(g)), comp, function(v) v[which.max(degree(g)[v])])
big  <- as.integer(names(which(table(comp) >= 5)))
V(g)$label <- NA_character_
V(g)$label[hub[as.character(big)]] <- V(g)$name[hub[as.character(big)]]

set.seed(1)
plot(g, layout = layout_with_fr(g), vertex.size = 4, vertex.frame.color = "grey30",
     vertex.label.cex = 0.7, vertex.label.color = "black", vertex.label.dist = 1.2,
     edge.lty = if_else(E(g)$r > 0, 1, 2), edge.color = "grey55",
     edge.width = 2 * abs(E(g)$r))
legend("bottomleft", legend = top_class, fill = palette, bty = "n", cex = 0.7)
Figure 4: Pairs with an absolute SEC correlation of at least 0.7. Node color is the putative chemical class; gray nodes belong to other classes. Solid edges are positive and dashed edges negative correlations.

The network has 163 metabolites and 778 pairs with an absolute correlation of at least 0.7. In each connected cluster of at least five metabolites, the metabolite with the most pairs is labeled.

Export

export_graphml() returns one igraph network per cutoff of the absolute correlation and writes each as a GraphML file, which Cytoscape reads.

networks <- export_graphml(res_sec, cutoffs = c(0.5, 0.7), output_dir = "networks")

Session information

Code
sessionInfo()
#> R version 4.6.2 (2026-10-29)
#> Platform: aarch64-apple-darwin23
#> Running under: macOS Sequoia 15.8.3
#> 
#> Matrix products: default
#> BLAS:   /Library/Frameworks/R.framework/Versions/4.6/Resources/lib/libRblas.0.dylib 
#> LAPACK: /Library/Frameworks/R.framework/Versions/4.6/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.1
#> 
#> locale:
#> [1] en_US/C.UTF-8/en_US/C/en_US/en_US
#> 
#> time zone: America/New_York
#> tzcode source: internal
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#>  [1] igraph_2.3.4    lubridate_1.9.5 forcats_1.0.1   stringr_1.6.0  
#>  [5] dplyr_1.2.1     purrr_1.2.2     readr_2.2.0     tidyr_1.3.2    
#>  [9] tibble_3.3.1    ggplot2_4.0.4   tidyverse_2.0.0 MetVAE_0.99.0  
#> 
#> loaded via a namespace (and not attached):
#>  [1] generics_0.1.4     stringi_1.8.9      lattice_0.23-1     hms_1.1.4         
#>  [5] digest_0.6.39      magrittr_2.0.5     evaluate_1.0.5     grid_4.6.2        
#>  [9] timechange_0.4.0   RColorBrewer_1.1-3 fastmap_1.2.0      jsonlite_2.0.0    
#> [13] Matrix_1.7-6       processx_3.10.0    torch_0.17.0       scales_1.4.0      
#> [17] coro_1.1.0         cli_3.6.6          rlang_1.3.0        bit64_4.8.6       
#> [21] withr_3.0.3        yaml_2.3.12        otel_0.3.0         tools_4.6.2       
#> [25] tzdb_0.5.0         vctrs_0.7.3        R6_2.6.1           lifecycle_1.0.5   
#> [29] htmlwidgets_1.6.4  bit_4.6.0          pkgconfig_2.0.3    callr_3.8.0       
#> [33] pillar_1.11.1      gtable_0.3.6       glue_1.8.1         Rcpp_1.1.2        
#> [37] xfun_0.62          tidyselect_1.2.1   knitr_1.52         farver_2.1.2      
#> [41] htmltools_0.5.9    rmarkdown_2.32     labeling_0.4.3     compiler_4.6.2    
#> [45] S7_1.0.0

The code in this tab is shown for reference and is not executed on this page. It applies the same analysis to the same data.

pip install metvae
import pandas as pd
from metvae.model import MetVAE

url = ("https://raw.githubusercontent.com/borenstein-lab/"
       "microbiome-metabolome-curated-data/main/data/processed_data/"
       "FRANZOSA_IBD_2019/")
meta = pd.read_csv(url + "metadata.tsv", sep="\t", index_col="Sample")
fmap = pd.read_csv(url + "mtb.map.tsv", sep="\t")
mtb = pd.read_csv(url + "mtb.tsv", sep="\t", index_col=0)

# Features with a compound name; one feature per compound.
named = fmap[fmap["Compound.Name"].notna() & fmap["Compound"].isin(mtb.columns)].copy()
named["name"] = named["Compound.Name"].str.replace(r"\*+$", "", regex=True)
named["key"] = named["HMDB"].fillna(named["name"])
named["zero"] = (mtb[named["Compound"]] == 0).mean().values
named = (named.sort_values(["key", "zero"]).drop_duplicates("key")
              .drop_duplicates("name"))
y = mtb[named["Compound"]]
y.columns = named["name"]

meta["diagnosis"] = pd.Categorical(meta["Study.Group"], ["Control", "CD", "UC"])
meta["cohort"] = ["PRISM" if s.startswith("PRISM") else "Validation" for s in meta.index]

model = MetVAE(data=y, meta=meta[["Age", "diagnosis", "cohort"]],
               continuous_covariate_keys=["Age"],
               categorical_covariate_keys=["diagnosis", "cohort"])
model.train()
model.get_corr()

results_p = model.sparse_by_p()
results_sec = model.sparse_by_sec()

The arguments and the structure of the results are described in the package README, and the example notebooks include an analysis of a hepatocellular carcinoma data set with 7,217 metabolites.

GNPS_Local runs GNPS feature-based molecular networking on a local computer and provides MetVAE through a graphical interface. Installation and use are described in the GNPS_Local documentation.

Data sources

Franzosa EA, Sirota-Madi A, Avila-Pacheco J, et al. Gut microbiome structure and metabolic activity in inflammatory bowel disease. Nature Microbiology 4:293–305 (2019). doi:10.1038/s41564-018-0306-4

Muller E, Algavi YM, Borenstein E. The gut microbiome-metabolome dataset collection: a curated resource for integrative meta-analysis. npj Biofilms and Microbiomes 8:79 (2022). doi:10.1038/s41522-022-00345-5

Citation

Lin H, Zhang L, Lotfi A, Jarmusch A, Lee I, Kim A, Morton JT, Aksenov A. Protocol for constructing correlation-based molecular networks from large-scale untargeted metabolomics data. bioRxiv (2026). doi:10.1101/2025.04.26.649581