nmfre: Non-negative Matrix Factorization with Random Effects

View source: R/nmfre.R

nmfreR Documentation

Non-negative Matrix Factorization with Random Effects

Description

Estimates the NMF-RE model

Y = X(\Theta A + U) + \mathcal{E}

where Y (P \times N) is a non-negative observation matrix, X (P \times Q) is a non-negative basis matrix learned from the data, \Theta (Q \times K) is a non-negative coefficient matrix capturing systematic covariate effects on latent scores, A (K \times N) is a covariate matrix, and U (Q \times N) is a random effects matrix capturing unit-specific deviations in the latent score space.

NMF-RE can be viewed as a mixed-effects latent-variable model defined on a reconstruction (mean) structure. The non-negativity constraint on X induces sparse, parts-based loadings, achieving measurement-side variable selection without an explicit sparsity penalty. Inference on \Theta provides covariate-side variable selection by identifying which covariates significantly affect which components.

Estimation is an outer–inner ECM: an inner loop (fixed \lambda) runs a ridge/BLUP update for U, an update for X (by default the exact minimization under the column sums; see X.update), and a fixed-effect update for \Theta; an outer loop runs the EM M-steps for (\sigma^2, \tau^2). The variance components are estimated from the data; the effective degrees of freedom df_U are reported only as a diagnostic.

nmfre() performs optimization only. Hypothesis tests and standard errors for \Theta are obtained separately with nmfre.inference (sandwich SE + wild bootstrap), mirroring the nmfkc / nmfkc.inference split.

Usage

nmfre(
  Y,
  A = NULL,
  rank = 2,
  C.signed = TRUE,
  X.update = c("exact", "semi"),
  epsilon = 1e-05,
  maxit = 5000,
  ...
)

Arguments

Y

Observation matrix (P x N), non-negative.

A

Covariate matrix (K x N). Default is a row of ones (intercept only).

rank

Integer. Rank of the basis matrix X. Default is 2. For backward compatibility, Q is accepted via ....

C.signed

Logical. Whether the fixed-effect coefficients C (= \Theta in the paper) are sign-free; the single switch that selects the whole estimation scheme. TRUE (default, recommended, matches the paper) treats C as real-valued and updates it by exact least squares, with a two-sided test (interior null). FALSE constrains C \ge 0, updated by an exact non-negative least squares (see C.nonneg.update under ...), with a one-sided test (boundary null). The basis X is always non-negative (see X.update). A character value ("signed" / "nonneg") is also accepted for backward compatibility.

X.update

The X-step. "exact" (default): the X-block is minimized exactly under X\ge0 and \mathbf 1^\top X=\mathbf 1^\top (a convex quadratic program, solved through the multipliers of the column sums), with no renormalization; with the exact U- and C-steps every block update is an exact minimization, the objective decreases monotonically and the fit stops at a KKT point of the likelihood. "semi": the complete-EM semi-NMF multiplicative step (Ding, Li and Jordan, 2010) followed by the column renormalization X\to XD^{-1}, (C,U)\to(DC,DU), which keeps the fitted mean but not the likelihood, so the fit can stop short of a stationary point; the default of nmfkc 1.0.3 and earlier, kept to reproduce those fits. On the package's examples "exact" took as long as "semi" or less and reached the same best point from every start. A "semi" fit checks how far it is from a stationary point (kkt.check under ...). "exact" is not available with X.L2.ortho or X.L2.smooth.

epsilon

Convergence tolerance for relative change in objective (default 1e-5).

maxit

Maximum number of iterations. Default 5000 (matches nmfkc and the other MU functions in the package). When the cap is hit without meeting the relative- tolerance criterion, a "maximum iterations (...) reached..." warning is emitted so users notice unconverged fits.

...

Additional arguments for initialization, variance control, dfU control, optimization, and inference settings.

  • X.init: Start of the basis. "mix2" (default; also NULL): fit from the k-means start and from the SPA start and keep the smaller marginal NLL; while the kept fit is degenerate (see degeneracy in the return value), refit from k-means starts with seeds seed + 1, seed + 2, ... (at most mix.restarts, default 20) and keep the smallest NLL. The fits are returned as X.init.search; only the kept fit's messages and warnings are shown. This takes about twice the time of one fit, and up to 22 times when every start ends degenerate (e.g. a rank the data do not support). A method name ("kmeans", "spa", "nndsvd", "kmeans++", ...) fits once from that start of nmfkc ("kmeans" is the single start of nmfkc 1.0.3 and earlier); a basis matrix (P x Q) is used as given. With X.anchor the anchors build the start instead.

  • mix.restarts: Most k-means restarts after a degenerate fit with X.init = "mix2" (default 20; 0 for none).

  • X.anchor: anchor rows of X, imposed as in nmfkc: NULL (default), "spa", or one row of Y per basis. The zeros are kept for the whole fit, including through the floor this function applies to X. There is no rank <= nrow(A) limit here: the random effects give the scores full rank. The rows used are returned as X.anchor. Fewer rows than bases (indices or row names) anchor the first bases only: row X.anchor[q] carries basis q alone and the other bases are free. Which basis an anchor row belongs to is then chosen by likelihood: a free fit (from X.init, by default "mix2"), a refit from it for every assignment of the anchor rows to bases (rank refits for one anchor row), and the refit with the smallest marginal NLL. The search is returned as X.anchor.search and the free fit's marginal NLL as nll.free; their difference is the cost of the anchors. For rank = 3 one exact anchor row already fixes the rotation that leaves the likelihood unchanged, so impose only anchors the design supports. With C.signed = TRUE and a Y with negative entries, "spa" chooses the rows on Y - min(Y), the same shifted Y the initialisation sees (as X.init = "spa" does); the shift is a device for the start, so the rows chosen are then only approximately those of the non-negative case.

  • C.init: Initial coefficient matrix (Q x K), or NULL. When NULL, nmfkc is called internally to generate initial values.

  • U.init: Initial random effects matrix (Q x N), or NULL (all zeros).

  • prefix: Prefix for basis names (default "Basis").

  • sigma2: Initial residual variance. By default (when \sigma^2 is updated) it starts from the residual covariance of Y on A, \tau^2 XX' + \sigma^2 I, as in probabilistic PCA: \sigma^2 at the mean of its eigenvalues beyond the Q-th, \tau^2 at U's share (the top Q eigenvalues in excess of \sigma^2) over \mathrm{tr}(X'X) of the start basis. Returned as variance.start. nmfkc 1.0.3 and earlier started at \sigma^2 = \tau^2 = 1 (\lambda = 1 whatever the scale of Y), from which data-driven starts could fall into a degenerate fit; give sigma2 = 1, tau2 = 1 to reproduce them. With sigma2.update = FALSE the default stays 1.

  • sigma2.update: Logical. Update \sigma^2 during iterations (default TRUE).

  • tau2: Initial random effect variance (default: from the residual covariance, see sigma2; 1 with tau2.update = FALSE).

  • tau2.update: Logical. Update \tau^2 by moment matching (default TRUE).

  • x.postvar: Logical. Include the posterior-variance term in the X-step (default TRUE; advanced). Applies to every X-step except the positive-part multiplicative one used with C.nonneg.update = "mu" and X.update = "semi".

  • kkt.check: Logical (default TRUE). With X.update = "semi", run 50 iterations of X.update = "exact" from the fit and record the decrease of 2\timesNLL as kkt$improvement; a message suggests X.update = "exact" when it exceeds kkt.tol (default 0.1). Skipped with anchor rows and with the X penalties.

  • C.nonneg.update: Updates used with C.signed = FALSE. "exact" (default): the C-step is an exact non-negative least squares (Lawson and Hanson's active-set method) and the X-step is that of the sign-free path (X.update), so every block update is exact or monotone and the fit stops at a KKT point of the likelihood. "mu": the positive-part multiplicative updates of nmfkc 1.0.3 and earlier, kept to reproduce those fits; their fixed points need not be stationary.

  • X.L2.smooth: Non-negative row-smoothness penalty on the basis X (default 0), adding (\lambda/2)\,\mathrm{tr}(X^\top L X) with L the path-graph Laplacian over rows (squared adjacent-row differences). Well suited to ordered rows (e.g.\ longitudinal / spatial bases). Injected into the X-step for both C.signed = TRUE/FALSE; leaves the random-effect variance updates unchanged.

  • X.L2.ortho: Non-negative column-orthogonality penalty on X (default 0), penalizing (\lambda/2)\lVert\mathrm{offdiag}(X^\top X)\rVert^2.

  • C.L2: Non-negative ridge penalty on \Theta = C (default 0), adding \lambda\lVert C\rVert^2. A Gaussian prior on the fixed effects; for C.signed = TRUE the C-step stays a closed-form Sylvester ridge-LS solve, for C.signed = FALSE it is added to the non-negative least squares (or, with C.nonneg.update = "mu", to the multiplicative-update denominator).

  • dfU.control: Deprecated and inert. The algorithm imposes no cap on df_U ("off", the only behaviour); df_U is reported as a diagnostic only.

  • print.trace: Logical. If TRUE, print progress every 100 iterations (default FALSE).

  • seed: Integer seed for reproducibility (default 1).

  • nstart: Number of random restarts for the nmfkc() initialisation step (passed to the k-means initialiser). Default 1 (single start; historical behaviour). A larger value (e.g.\ 10-20) gives a more stable initialisation.

  • inner.maxit, outer.maxit: Maximum inner (fixed-\lambda block-coordinate) and outer (EM variance) iterations (defaults 10000 and 500).

  • epsilon.outer: Convergence tolerance for the outer EM loop on \lambda (default 1e-6).

  • orient: Representation reported within the identification region (see the return value): "geomin" (default; the geomin member of the local region) or "none" (the point where the algorithm stopped, as up to 1.0.2).

  • orient.eps: \varepsilon of the geomin criterion (default 0.01).

  • ident.search: For Q\ge4, search the identification region numerically when, after the bases pinned by anchors are removed, between 4 and 7 remain (default TRUE; see the return value).

  • ident.dirs, ident.draws: Directions followed from the fit and random draws over the whole family in that search (defaults 300 and 20000).

  • ident.zero.tol: Entries of X (and of C for C.signed = FALSE) at most this value count as zeros when looking for anchors (default 0: exact zeros only, which the exact updates return for active constraints). A positive value makes the pinning a numerical diagnostic, not an exact result.

Value

A list of class "nmfre" with components. The model is Y = X(\Theta A + U) + \mathcal{E}.

Core matrices

X

Basis matrix X (P \times Q), columns normalized to sum to 1.

X.prob

Row-wise soft-clustering probabilities from the non-negative X (each row normalized to sum to 1), as in nmfkc.

X.cluster

Hard-clustering label for each row of X (argmax over X.prob).

C

Coefficient matrix \Theta (Q \times K).

U

Random effects matrix U (Q \times N).

Variance components

sigma2

Residual variance \hat{\sigma}^2.

tau2

Random effect variance \hat{\tau}^2.

lambda

Ridge penalty \lambda = \sigma^2 / \tau^2.

Convergence diagnostics

converged

Logical. Whether the algorithm converged.

stop.reason

Character string describing why iteration stopped.

iter

Number of iterations performed.

maxit

Maximum iterations setting used.

epsilon

Convergence tolerance used.

objfunc

Final objective function value \|Y - X(\Theta A + U)\|^2 + \lambda \|U\|^2.

rel.change.final

Final relative change in objective.

objfunc.iter

Numeric vector of the fixed-\lambda penalized objective \|Y - X(\Theta A + U)\|^2 + \lambda\|U\|^2 per iteration. Monotone within an inner loop but not across outer iterations (the penalty jumps when \lambda is updated).

rss.trace

Numeric vector of \|Y - X(\Theta A + U)\|^2 per iteration.

nll.trace

Numeric vector of the marginal negative log-likelihood \ell(X,\Theta,\sigma^2,\tau^2) per iteration (random effects integrated out). This is the ECM-monotone quantity and is what plot.nmfre displays.

Degeneracy diagnostic

degeneracy

A list for detecting a degenerate fit, in which two columns of X approach each other while the corresponding rows of C grow with opposite signs (with Q \ge 2 and a signed C: two bases suffice, so it can happen at Q = 2 as well, e.g. when the rank exceeds what the data support; the fit does not settle and those rows of C are not interpretable). In simulations such fits usually had a clearly lower marginal likelihood than a fit from another start, so the default X.init = "mix2" refits from other starts while flag is TRUE and keeps the fit with the larger likelihood: max.cosine (largest cosine similarity between two columns of X) and its pair; cancellation (\max_k \sum_q |c_{qk}| / \|X c_{\cdot k}\|_1, large when a composite effect is a difference of large opposite terms); kappa.X (condition number of X); and flag (max.cosine >= 0.9 or cancellation >= 5). The thresholds were set on two simulation designs; read the measures as well. summary() prints a line when flag is TRUE.

X.init.search

With X.init = "mix2": one row per fit (start, seed, marginal nll, degenerate, converged, chosen). summary() prints the start kept and how far the others stopped from it.

Effective degrees of freedom (dfU) diagnostics

dfU

Final effective degrees of freedom \mathrm{df}_U = N \sum_q d_q / (d_q + \lambda), where d_q are eigenvalues of X'X.

dfU.cap

Upper bound imposed on \mathrm{df}_U.

dfU.cap.rate

Rate used to compute the cap.

lambda.enforced

Final \lambda enforced to satisfy the cap.

dfU.hit.cap

Logical. Whether the cap was binding.

dfU.hit.iter

Iteration at which the cap first bound.

dfU.frac

\mathrm{df}_U / (NQ), fraction of maximum df.

dfU.cap.frac

\mathrm{df}_U^{\mathrm{cap}} / (NQ).

Fitted matrices

B

Fixed-effect scores \Theta A (Q \times N).

B.prob

Column-normalized probabilities from \max(\Theta A, 0).

B.blup

BLUP scores \Theta A + U (Q \times N).

B.blup.pos

Non-negative BLUP scores \max(\Theta A + U, 0) (Q \times N).

B.blup.prob

Column-normalized probabilities from \max(\Theta A + U, 0).

XB

Fitted values from fixed effects X \Theta A (P \times N).

XB.blup

Fitted values including random effects X(\Theta A + U) (P \times N).

Fit statistics

r.squared

Pearson \mathrm{cor}(Y, X(\Theta A + U))^2 (BLUP prediction).

r.squared.uncentered

Uncentered 1 - \|Y - X(\Theta A + U)\|_F^2 / \|Y\|_F^2 (BLUP; baseline = zero matrix).

r.squared.centered

Row-mean centered 1 - \|Y - X(\Theta A + U)\|_F^2 / \|Y - \bar Y_{p\cdot}\|_F^2 (BLUP; baseline = per-row mean).

r.squared.fixed

Pearson \mathrm{cor}(Y, X\Theta A)^2 (fixed-only prediction).

r.squared.fixed.uncentered, r.squared.fixed.centered

Uncentered and centered R^2 for the fixed-only prediction.

ICC

Trace-based Intraclass Correlation Coefficient. In the NMF-RE model, the conditional covariance of the n-th observation column is \mathrm{Var}(Y_n) = \tau^2 X X^\top + \sigma^2 I_P, a P \times P matrix. Unlike a standard random intercept model where the design matrix Z is a simple indicator (so the ICC reduces to \tau^2 / (\sigma^2 + \tau^2)), the basis matrix X plays the role of Z in a random slopes model, making the variance contribution of U depend on X. To obtain a scalar summary, we take the trace of each component:

\mathrm{ICC} = \frac{\tau^2 \, \mathrm{tr}(X^\top X)} {\tau^2 \, \mathrm{tr}(X^\top X) + \sigma^2 P}.

This equals the average (over P dimensions) proportion of per-column variance attributable to the random effects.

Sign convention

C.signed

Logical. Whether C was sign-free (TRUE) or non-negative (FALSE).

Identification region and orientation

Under the working model the fits giving the same distribution are (XO, O^\top\Theta) with O orthogonal, O\mathbf 1=\mathbf 1 and XO\ge0 (and O^\top\Theta\ge0 for C.signed = FALSE): the identification region. X\Theta is constant on it. For Q=3 the O form a circle, and the arc through the fit is the local identification region. The ends of the arc are found numerically (a grid of 7200 angles refined by root finding, constraints met to 10^{-10}; an arc shorter than 10^{-7} is reported as a point); the range of each entry of \Theta and of X over the arc is then computed in closed form. A width of 0 means the fit cannot be moved within the region, to this resolution (a row of X on one basis only pins it). For Q\le2 the region is a point up to relabelling. For Q\ge4 the bases pinned by anchors are removed one at a time: if a row of X is non-zero, outside the bases already removed, on one basis only (and, for C.signed = FALSE, if a column of C is), every admissible O keeps that basis, because a non-negative row of O with sum 1 and length 1 is a unit vector. Zeros are exact zeros unless ident.zero.tol is set. If at most two bases remain the region is a point up to relabelling; if three remain their local region (an arc, a point, or the whole circle) is computed as for Q=3; if 4 to 7 remain it is searched numerically (ident.search): the ranges then come from points reached along paths from the fit that are feasible at each step, and are approximate, not certified bounds (finding no other representation is evidence, not a proof). Feasible transformations found elsewhere in the family show that the fit is not unique globally; they are counted (identification$search$global.nonperm) but not used in the ranges, since they need not belong to the local region. The geomin orientation and the profile intervals' use of the region are for Q=3 only. By default (orient = "geomin") the representation returned is the member of the local region that minimizes the geomin criterion on the row shares of X (rows of zeros left out; as rotated loadings in exploratory factor analysis), which defines the reported coefficients when the region has positive width; nothing moves when the region is a point. The search is local: it finds the minimizer over the whole identification region only when the local region contains it. With orient = "none" the representation returned is the point where the algorithm stopped, which depends on the start. The likelihood and X\Theta do not change.

C.ident.lower, C.ident.upper, C.ident.width

Range of each entry of C over the local identification region and its width (Q x K matrices; absent when the region is not computed).

X.ident.lower, X.ident.upper, X.ident.width

The same for X (P x Q matrices).

identification

List: width (largest entry of C.ident.width; NA when not computed), arc and full.circle of the region, method ("exact", "anchors", "anchors+exact", "search", "anchors+search" or "none"; "exact" means the arc computed as above, in closed form over an arc whose ends are found numerically, not a certified computation), pinned (bases pinned by anchors, Q\ge4), Q.rest (bases left after them), search (counts of the numerical search), and orient, the orientation applied (rule, angle, O, moved: largest change of C, the geomin criterion before and after, eps, note). nmfre.inference adds its identifiability diagnostic to this list.

Standard errors, z-values, p-values, and confidence intervals for \Theta are not computed here; obtain them by passing the fit to nmfre.inference.

References

Satoh, K. (2026). Wild Bootstrap Inference for Non-Negative Matrix Factorization with Random Effects. arXiv:2603.01468. https://arxiv.org/abs/2603.01468

See Also

nmfre.inference, nmfkc.DOT, summary.nmfre

Examples

# Example 1. cars data
Y <- matrix(cars$dist, nrow = 1)
A <- rbind(intercept = 1, speed = cars$speed)
res <- nmfre(Y, A, rank = 1, maxit = 5000)
summary(res)


# Example 2. Orthodont data (nlme)
if (requireNamespace("nlme", quietly = TRUE)) {
  Y <- matrix(nlme::Orthodont$distance, 4, 27)
  male <- ifelse(nlme::Orthodont$Sex[seq(1, 108, 4)] == "Male", 1, 0)
  A <- rbind(intercept = 1, male = male)

  # Fit (sign-free Theta by default; variances estimated by EM/ECM)
  res <- nmfre(Y, A, rank = 1)
  summary(res)
}


nmfkc documentation built on Nov. 30, 2026, 1:06 a.m.