Case study: compare priors and recovered programs
Source:vignettes/compare-priors.Rmd
compare-priors.RmdDo different feature priors change prediction or the programs recovered? This small simulation has known rank-two signal, sparse signed effects, and repeated samples from simulated donors. It fits a normal and a sparse (point-Laplace) effects prior, then compares the two fits three ways: reconstruction against known truth, held-out prediction by donor, and program agreement. It illustrates a workflow, not a calibrated benchmark or a recommendation of one prior. Get started defines view, activity and effects.
library(flashier.utils)
set.seed(31)
metadata <- data.frame(sample = paste0("s", 1:60),
donor = rep(paste0("d", 1:20), each = 3))
A <- matrix(rnorm(40), 20, 2)[rep(1:20, each = 3), ] +
matrix(rnorm(120, sd = .2), 60, 2)
B <- matrix(0, 24, 2)
B[1:8, 1] <- rep(c(1, -1), 4)
B[9:16, 2] <- rep(c(1, -1), 4)
signal <- tcrossprod(A, B)
X <- signal + matrix(rnorm(1440, sd = .3), 60, 24)
dimnames(X) <- dimnames(signal) <- list(metadata$sample, paste0("g", 1:24))
priors <- list(normal = list(ebnm::ebnm_normal, ebnm::ebnm_normal),
sparse = list(ebnm::ebnm_normal, ebnm::ebnm_point_laplace))
fits <- lapply(priors, function(p) {
set.seed(7)
flashier::flash(X, greedy_Kmax = 2, ebnm_fn = p,
nullcheck = FALSE, backfit = TRUE, verbose = 0)
})
views <- lapply(fits, standardize_factors, sample_side = "rows", scaling = "raw",
feature_scale = "simulated_intensity",
prior_support = c(activity = "signed", effects = "signed"))
library(ggplot2)
dimnames(B) <- list(colnames(X), c("F1", "F2"))
effects_long <- do.call(rbind, lapply(c(truth = "truth", names(views)), function(p)
cbind(fit = p, as.data.frame(as.table(if (p == "truth") B else views[[p]]$effects)))))
names(effects_long)[2:4] <- c("feature", "factor", "effect")
effects_long$fit <- factor(effects_long$fit, c("truth", "normal", "sparse"))
ggplot(effects_long, aes(feature, effect)) + geom_col(fill = "grey30") +
geom_hline(yintercept = 0) + facet_grid(factor ~ fit) + theme_minimal() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, size = 7)) +
labs(x = "simulated gene", y = "effect (simulated intensity units)")
Feature effects per factor (rows) under each fit (columns) for the 24 simulated genes. Simulated intensities, no biology. Factor order and sign are arbitrary across columns; the planted truth is one basis among rotations.
The sparse prior pushes the genes outside each planted block toward zero. The normal prior gives every gene a small effect. Both reconstruct the training matrix about equally well, as the next section shows.
Reconstruction and known signal
Both fits are scored on the training matrix and on the noise-free signal.
predictions <- lapply(views, function(v)
sweep(tcrossprod(v$activity, v$effects), 2, v$offset, "+"))
metrics <- function(observed, predicted) {
c(rmse = sqrt(mean((observed - predicted)^2)),
mae = mean(abs(observed - predicted)),
prediction_r2 = 1 - sum((observed - predicted)^2) /
sum((observed - mean(observed))^2))
}
scores <- rbind(normal_training = metrics(X, predictions$normal),
sparse_training = metrics(X, predictions$sparse),
normal_truth = metrics(signal, predictions$normal),
sparse_truth = metrics(signal, predictions$sparse))
vapply(fits, function(f) f$n_factors, numeric(1))## normal sparse
## 2 2
scores_long <- as.data.frame(as.table(scores))
names(scores_long) <- c("fit", "metric", "value")
scores_long$prior <- sub("_.*", "", scores_long$fit)
scores_long$target <- sub(".*_", "", scores_long$fit)
ggplot(scores_long, aes(target, value)) + geom_col(fill = "grey30", width = 0.6) +
geom_text(aes(label = round(value, 3)), vjust = -0.3, size = 3) +
facet_grid(metric ~ prior, scales = "free_y") +
scale_y_continuous(expand = expansion(mult = c(0, 0.25))) +
theme_minimal() + labs(x = "scored against", y = NULL)
Reconstruction of the training matrix and of the noise-free signal, one fit per matrix (no replicates, so no uncertainty is shown). Simulated data. The two priors are indistinguishable on this criterion.
round(scores, 3)## rmse mae prediction_r2
## normal_training 0.290 0.231 0.874
## sparse_training 0.292 0.233 0.872
## normal_truth 0.107 0.080 0.980
## sparse_truth 0.100 0.066 0.983
Training reconstruction rewards fitting observed noise. Truth recovery is measurable here because signal was simulated; real-data agreement cannot supply that truth. Inspect native convergence warnings and failures before ranking. Native ELBO is not automatically comparable across different prior/noise/objective settings; maximum ELBO over starts is a different question.
Identical held-out information
factor_holdout() splits donors into folds, refits on
training donors, and scores withheld entries. In masked mode held-out
activities are estimated from activity_features only, and
prediction is scored on the disjoint scoring_features.
folds <- data.frame(donor = paste0("d", 1:20), fold = rep(1:2, each = 10))
results <- lapply(priors, function(p) {
callback <- function(X, metadata, sample_side, seed, settings, observation_aux) {
fit_ebmf(X, sample_side = sample_side, ebnm_fn = settings$priors,
max_factors = 2, backfit = TRUE, nullcheck = FALSE,
seed = seed, verbose = 0, feature_scale = "simulated_intensity")
}
factor_holdout(X, metadata, unit_col = "donor", folds = folds, fit_fn = callback,
evaluation = "masked", activity_features = paste0("g", c(1:4, 9:12, 17:20)),
scoring_features = paste0("g", c(5:8, 13:16, 21:24)), seed = 7,
control = list(sample_side = "rows", settings = list(priors = p),
preprocessing_manifest = list(scope = "identity"), maxiter = 1000))
})
stopifnot(all(vapply(results, function(r) nrow(r$failures) == 0L, logical(1))))
holdout <- do.call(rbind, lapply(names(results), function(p) {
m <- results[[p]]$metrics
cbind(prior = p, m[m$weighting == "macro_unit", c("fold", "model", "rmse", "prediction_r2")])
}))
holdout_long <- rbind(
data.frame(holdout[, 1:3], metric = "rmse", value = holdout$rmse),
data.frame(holdout[, 1:3], metric = "prediction_r2", value = holdout$prediction_r2))
ggplot(holdout_long, aes(factor(fold), value, shape = model)) +
geom_point(size = 3) + scale_shape_manual(values = c(fixed_programs = 16, training_mean = 2)) +
facet_grid(metric ~ prior, scales = "free_y") + theme_minimal() +
labs(x = "donor fold", y = NULL, shape = NULL) + theme(legend.position = "bottom")
Held-out prediction per donor fold (10 donors, 30 samples per fold; macro-averaged over donors). Baseline is the training mean of each scoring feature. Two folds give no interval; each point is one refit.
holdout## prior fold model rmse prediction_r2
## 1.rmse22 normal 1 fixed_programs 0.3418776 0.6544313
## 1.rmse31 normal 1 training_mean 0.9032888 -0.4323584
## 2.rmse22 normal 2 fixed_programs 0.3349613 0.7763867
## 2.rmse31 normal 2 training_mean 0.8637124 -0.2685607
## 1.rmse221 sparse 1 fixed_programs 0.3332051 0.6644698
## 1.rmse311 sparse 1 training_mean 0.9032888 -0.4323584
## 2.rmse221 sparse 2 fixed_programs 0.3296349 0.7821567
## 2.rmse311 sparse 2 training_mean 0.8637124 -0.2685607
Donors never cross folds. Held-out activities use only permitted features; the same withheld entries score both models and a training-mean baseline. Real learned preprocessing needs paired training-fit/frozen-transform callbacks. Empirical-Bayes projection can recalibrate activity priors/noise on permitted query observations; this is not a fully frozen hyperparameter prediction experiment.
prediction_r2 is centred on the mean of the scored
held-out entries pooled over features, so a model that only reproduces
feature means already scores well above 0. The skill
column, 1 - SSE(fit) / SSE(training mean), is centred on
the baseline instead: 0 means no better than the training mean. Read the
fitted-programs row next to the training-mean row.
Program agreement and ambiguity
factor_replicability() matches factors across the two
fits by Tucker congruence (cosine similarity of effect vectors) with
one-to-one assignment.
alignment <- factor_replicability(views$normal, views$sparse, min_congruence = .8)
alignment$matches## reference_factor target_factor congruence similarity best_similarity sign
## 1 F1 F1 0.8597412 0.8597412 0.8597412 1
## 2 F2 F2 0.8586710 0.8586710 0.8586710 1
## matched candidate shared_features eligible status
## 1 TRUE TRUE 24 TRUE accepted
## 2 TRUE TRUE 24 TRUE accepted
congruence <- as.data.frame(as.table(alignment$congruence_matrix))
names(congruence) <- c("normal", "sparse", "congruence")
ggplot(congruence, aes(sparse, normal, fill = congruence)) + geom_tile() +
geom_text(aes(label = round(congruence, 2))) +
scale_fill_gradient2(low = "#D55E00", mid = "white", high = "#0072B2", limits = c(-1, 1)) +
theme_minimal() + coord_fixed()
Tucker congruence (cosine of effect vectors over the 24 shared genes) between the two fits. Acceptance threshold is 0.8; numbers are printed so colour is not the only encoding.
Inspect unmatched factors, feature coverage, and assignment margins as well as accepted matches. Assignment is one-to-one: splits/merges require inspecting the full matrix. Matching effects does not establish equivalent activity units.
Subspace agreement can survive changes in individual factors. Compute an orthonormal basis using numerical rank, including zero-rank results:
span <- function(M) {
s <- svd(M)
rank <- sum(s$d > max(dim(M)) * max(c(s$d, 0)) * .Machine$double.eps)
s$u[, seq_len(rank), drop = FALSE]
}
projector_distance <- function(left, right) {
U <- span(left); V <- span(right)
sqrt(sum((tcrossprod(U) - tcrossprod(V))^2))
}
# subspace distance of each prior's effects from the true effects
c(normal_vs_truth = projector_distance(views$normal$effects, B),
sparse_vs_truth = projector_distance(views$sparse$effects, B))## normal_vs_truth sparse_vs_truth
## 0.12456246 0.06156279
# a 45-degree rotation of the true factors
theta <- pi / 4
R <- matrix(c(cos(theta), -sin(theta), sin(theta), cos(theta)), 2)
rotated_A <- A %*% R
rotated_B <- B %*% t(solve(R))
# the rotated pair reconstructs the same signal
stopifnot(max(abs(tcrossprod(rotated_A, rotated_B) - signal)) < 1e-10)
# reconstruction difference and subspace distance after rotation, both near zero
c(reconstruction_difference = max(abs(tcrossprod(rotated_A, rotated_B) - signal)),
subspace_distance = projector_distance(B, rotated_B))## reconstruction_difference subspace_distance
## 2.220446e-16 4.232156e-16
# per-factor congruence between true and rotated effects
abs(crossprod(B, rotated_B) / sqrt(outer(colSums(B^2), colSums(rotated_B^2))))## [,1] [,2]
## F1 0.7071068 0.7071068
## F2 0.7071068 0.7071068
This rotation preserves signal/subspace exactly, while each pairwise congruence is about 0.707, below a 0.8 acceptance threshold. Individual-factor disagreement alone therefore cannot establish lost signal. A broader study must also assess weak, correlated, overlapping, nonnegative and spurious/missing programs with repeated seeds and explicit failure accounting.
Joint coverage of the two program sets
One-to-one matching asks “which factor is which”.
compare_prior_fits() asks a different question: can each
factor of one fit be rebuilt from all factors of the other? Span
coverage allows any signed combination; feasible coverage respects each
factor’s declared activity support. Both describe loading
representability only, never program usage or biology.
comparison <- compare_prior_fits(views$normal, views$sparse)
plot(comparison, "coverage")
Uncovered loading fraction of each normal-prior factor when rebuilt from the sparse-prior factors, over the 24 simulated genes. Points are the two observed activity poles (shape and colour); zero means fully representable. Simulated data, one fit per prior, no replication.
comparison## Saved program comparison: 2 reference factors; 2 target factors
## 24 shared features; 8 assessed directions
## Coverage describes loading representability. Evidence: not_assessed
comparison$coverage[, c("source", "factor", "pole", "span_residual", "feasible_residual", "feasible_status")]## source factor pole span_residual feasible_residual feasible_status
## 1 reference F1 -1 0.001386831 0.001386831 optimal_linear_span
## 2 reference F1 1 0.001386831 0.001386831 optimal_linear_span
## 3 reference F2 -1 0.003704567 0.003704567 optimal_linear_span
## 4 reference F2 1 0.003704567 0.003704567 optimal_linear_span
## 5 target F1 -1 0.001954497 0.001954497 optimal_linear_span
## 6 target F1 1 0.001954497 0.001954497 optimal_linear_span
## 7 target F2 -1 0.003136815 0.003136815 optimal_linear_span
## 8 target F2 1 0.003136815 0.003136815 optimal_linear_span
Credits
FLASH/EBNM authors are credited in Get
started. Matching delegates to William Revelle’s psych and Kurt
Hornik/Walter Böhm’s clue. SVD, metrics and the bounded coverage solver
(stats::optim) use R Core functions; the experiment and its
figures (ggplot2, Hadley Wickham and contributors) are independently
implemented. Full
credits.