Skip to content

DESeq2 and pyDESeq2

DESeq2 is the most widely used package for differential expression analysis of RNA-seq data. It uses a negative binomial model to test whether gene expression differs between experimental conditions. pyDESeq2 is a Python reimplementation of the same algorithm, from Muzellec and colleagues at Owkin, and it exists because a pipeline already written in Python should not have to cross into R for one step.

Both tabs below run the same analysis on the airway dataset, in the same container, from the same count matrix. That makes the comparison at the end of the page a measurement rather than a claim.

The analysis runs on the airway dataset that the workflow & the dataset page describes, eight samples from four donor cell lines, each untreated and treated with dexamethasone.

It ships as a Bioconductor package, which is the first problem a Python user hits. The R tab therefore writes the count matrix and the sample table to CSV, and the Python tab reads those files. pyDESeq2 wants samples as rows and genes as columns, the transpose of the R layout, so the export transposes on the way out.

The airway vignette documents this dataset and its sample metadata.

The count object comes from Michael Love’s airway 1.32.0 data package, which declares LGPL. It represents the Himes and colleagues experiment, deposited as GSE52778 and SRP033351. The source and license notice identifies the original object. This lesson derives its summaries and analysis results from that object.

library(airway)
library(DESeq2)
data("airway")
counts_matrix <- assay(airway, "counts")
dim(counts_matrix)
# Hand the same matrix to Python. pyDESeq2 wants samples as rows, so transpose.
dir.create("outputs", showWarnings = FALSE, recursive = TRUE)
write.csv(t(counts_matrix), "outputs/airway_counts.csv")
write.csv(
as.data.frame(colData(airway))[, c("cell", "dex")],
"outputs/airway_metadata.csv"
)
[1] 63677 8

The sample names are the join key. Each metadata row must match a count column in R or a count row in Python, in the same order. Here cell identifies the donor cell line, and dex identifies its untreated or treated sample. Keep both columns when adapting the example; removing cell discards the paired design.

Both libraries hold the counts, the sample table and the design in one object. The design formula is written the same way in both: ~ cell + dex models expression as a function of the donor cell line and the treatment, so the coefficient of interest is the treatment effect after the donor is accounted for.

The contrast below is treated versus untreated. A positive log2 fold change therefore means higher expression after dexamethasone, conditional on the donor term. For another study, choose the experimental unit, reference level and contrast from its sample table before reusing this formula.

The filter is the one the QC page explains, at least ten reads in total. It removes over 41,000 genes, which speeds up the fit.

The DESeq2 1.52.0 vignette, by Michael I. Love, Simon Anders, and Wolfgang Huber, documents this constructor. Its airway example uses the same paired design. The review has not established whether this code was adapted from that tutorial.

The compared DESeq2 1.52.0 vignette by Michael I. Love, Simon Anders, and Wolfgang Huber ships in the package source archive. Its package license is LGPL version 3 or later. The LGPL text and its GPL terms accompany this reference.

dds <- DESeqDataSetFromMatrix(
countData = counts_matrix,
colData = colData(airway),
design = ~ cell + dex
)
keep <- rowSums(counts(dds)) >= 10
dds <- dds[keep, ]
nrow(dds)
[1] 22369

One call does the whole pipeline in both languages: size factor estimation to correct for sequencing depth, as the normalization page shows, dispersion estimation to model the overdispersion that count data always has, a negative binomial fit per gene, and a Wald test on the coefficient.

The differential expression section of the DESeq2 vignette documents the DESeq and results calls below. The explicit treatment contrast belongs to this airway example.

dds <- DESeq(dds)
res <- results(dds, contrast = c("dex", "trt", "untrt"))
res_df <- as.data.frame(res)
res_df <- res_df[order(res_df$padj), ]
round(head(res_df[, c("baseMean", "log2FoldChange", "stat", "padj")], 5), 4)
baseMean log2FoldChange stat padj
ENSG00000152583 997.4447 4.5750 24.8314 0
ENSG00000165995 495.0957 3.2911 24.7353 0
ENSG00000120129 3409.0384 2.9478 24.1872 0
ENSG00000101347 12703.4128 3.7670 24.1488 0
ENSG00000189221 2341.7807 3.3537 23.5872 0

The adjusted p-value is the column to filter on, because every gene was tested and a raw p-value of 0.01 is expected by chance in hundreds of them.

tested <- res_df[!is.na(res_df$padj), ]
significant <- tested[tested$padj < 0.05, ]
# Tested, significant, up, down.
nrow(tested)
nrow(significant)
sum(significant$log2FoldChange > 0)
sum(significant$log2FoldChange < 0)
# Keep the R numbers for the comparison at the end of the page.
write.csv(
data.frame(
engine = "R DESeq2",
tested = nrow(tested),
significant = nrow(significant),
up = sum(significant$log2FoldChange > 0),
down = sum(significant$log2FoldChange < 0),
top_gene = rownames(res_df)[1]
),
"outputs/r_summary.csv",
row.names = FALSE
)
# The per-gene R estimates, so the Python tab can compare the two directly.
write.csv(
res_df[, c("baseMean", "log2FoldChange", "padj")],
"outputs/r_results.csv"
)
[1] 18032
[1] 4000
[1] 2193
[1] 1807

Where the two agree, and where they do not

Section titled “Where the two agree, and where they do not”

The comparison is the reason for running both. The table is built in the Python tab from the R summary written above and from the Python results in memory, so every cell in it comes from this page’s own run.

r_summary = pd.read_csv("outputs/r_summary.csv")
python_row = {
"engine": "pyDESeq2",
"tested": len(tested),
"significant": len(significant),
"up": int((significant["log2FoldChange"] > 0).sum()),
"down": int((significant["log2FoldChange"] < 0).sum()),
"top_gene": results_df.index[0],
}
comparison = pd.concat(
[r_summary, pd.DataFrame([python_row])], ignore_index=True
)
print(comparison.to_string(index=False))
# How far apart are the two fold change estimates for the genes both tested?
r_res = pd.read_csv("outputs/r_results.csv", index_col=0)
shared = r_res.join(results_df, how="inner", lsuffix="_r", rsuffix="_py")
delta = (shared["log2FoldChange_r"] - shared["log2FoldChange_py"]).abs()
spearman = shared["log2FoldChange_r"].corr(
shared["log2FoldChange_py"], method="spearman"
)
print(f"shared genes: {len(shared)}")
print(f"max abs log2FC difference: {delta.max():.4f}")
print(f"median abs log2FC difference: {delta.median():.6f}")
print(f"Spearman correlation: {spearman:.6f}")
engine tested significant up down top_gene
R DESeq2 18032 4000 2193 1807 ENSG00000152583
pyDESeq2 18032 3922 2156 1766 ENSG00000152583
shared genes: 22369
max abs log2FC difference: 0.7969
median abs log2FC difference: 0.000208
Spearman correlation: 0.999778

The two implementations do not return identical numbers, and they are not supposed to. They differ in the numerical details of dispersion estimation and in how the Wald p-values are computed, which moves genes near the significance boundary across it in one engine and not the other. What matters is whether the difference changes a conclusion, and the fold change agreement above answers that.

Use the R implementation when the rest of your analysis is Bioconductor, because the downstream annotation and gene set packages expect its objects. Use pyDESeq2 when the rest of the pipeline is Python and the alternative is exporting to R and back for one step.

The fold changes above are maximum likelihood estimates, and for a gene with few reads they are noisy. A gene with 5 reads in one condition and 50 in the other gets a large fold change and a wide standard error. Shrinkage pulls each estimate toward zero in proportion to its uncertainty, so a well measured change stays where it is and a noisy one collapses. The p-values do not change. The shrunken fold change is the one to plot and to rank on, and the visualization page draws it as an MA plot.

Both libraries shrink a coefficient of the model rather than a contrast, so that coefficient has to measure treated against untreated. airway ships dex with trt as its first level, which makes the model’s own coefficient run the other way. Each tab therefore sets untreated as the reference and refits before it shrinks.

The DESeq2 shrinkage section documents coefficient selection and apeglm shrinkage. The result comparison below uses this lesson’s own captured output.

# lfcShrink shrinks a model coefficient, not a contrast. Make untreated the
# reference so the coefficient is treated against untreated, then refit.
dds$dex <- relevel(dds$dex, ref = "untrt")
dds <- DESeq(dds)
resultsNames(dds)
mle <- results(dds, name = "dex_trt_vs_untrt")
shrunk <- lfcShrink(dds, coef = "dex_trt_vs_untrt", type = "apeglm")
# The same genes before and after shrinkage, largest moves first.
moved <- data.frame(
baseMean = mle$baseMean,
mle = mle$log2FoldChange,
shrunk = shrunk$log2FoldChange,
row.names = rownames(mle)
)
moved <- moved[order(-abs(moved$mle - moved$shrunk)), ]
round(head(moved, 5), 3)
# The top gene of the Wald test, for comparison.
round(moved["ENSG00000152583", ], 3)
[1] "Intercept" "cell_N061011_vs_N052611"
[3] "cell_N080611_vs_N052611" "cell_N61311_vs_N052611"
[5] "dex_trt_vs_untrt"
baseMean mle shrunk
ENSG00000265702 3.331 5.192 0.262
ENSG00000264569 2.751 4.808 0.184
ENSG00000222939 2.409 4.612 0.155
ENSG00000263567 4.104 -4.581 -0.211
ENSG00000236990 2.228 4.192 0.117
baseMean mle shrunk
ENSG00000152583 997.445 4.575 4.56

The genes that move most are the ones with almost no reads. ENSG00000265702 has a mean of 3.3 normalized reads, and its fold change of 5.192 shrinks to 0.262. ENSG00000152583 has a mean near 1,000 reads and moves from 4.575 to 4.56, because the data already pin its estimate down. pyDESeq2 shrinks with its own implementation, so its values differ, but the pattern holds. Three of its five largest moves are genes that the R tab also lists, all five have a mean under 3 reads, and the top gene moves from 4.573 to 4.561.

Love, Huber, and Anders, 2014 describe the DESeq2 count model and shrinkage method.

Muzellec and colleagues, 2023 describe the Python implementation and explain why its estimates can differ.

Himes and colleagues, 2014 report the airway smooth muscle experiment that supplies these samples.

The DESeq2 1.52.0 workflow explains paired designs, independent filtering, and coefficient shrinkage. These sections separate model choices from the R and Python result comparison.

The PyDESeq2 0.5.3 example documents the model, Wald test, and in-place fold-change shrinkage. Its version matches the API reviewed here.