Skip to content

SVD estimator

mtdr.svd_fit

Reduced-rank regression: the SVD estimator (docs/model.md § 3).

Per neuron, ordinary (or ridge) least squares of the observed responses on the design gives the unconstrained coefficients \(\hat B_p\), (M15)-(M16); each \(\hat B_p\) is truncated to rank \(r_p\) by its singular value decomposition, (M17)-(M18), optionally after weighting each neuron's row by its precision, (M18w); the intercept is refitted given the truncated blocks; the noise precision of each neuron is the inverse residual variance of that fit, computed with the aligned residual (M19b); and the fit is scored by the plug-in Gaussian log-likelihood and the textbook parameter count, (M21a)-(M21b). This is the reference's SVDRegressB, SVDRegress_S_Vdata and SVDRegB_AIC with the four SVDRegB_AIC defects corrected (it misaligns the residual, scrambles neurons when reshaping, counts regressors in place of observations and flips the sign of the log-precision term; see docs/differences-from-matlab.md) and the intercept refitted as above; the replica of the defective objective lives in the test suite (tests/matlab_compat.py).

Everything is computed from the SufficientStats (the reference's XX/XY block matrices, \(nPT\times nPT\) for XX, are never formed), batched over neurons; with the intercept, the solve and the residual use the moments about the neurons' means, so a shifted regressor or a large baseline costs no accuracy.

RANK_TOLERANCE = 1e-10 module-attribute

Threshold of the scale-invariant rank test.

A neuron's design is rank-deficient when the smallest eigenvalue of its unit-diagonal (equilibrated) Gram matrix is at or below this.

SVDFit dataclass

Result of fit_svd.

Per-regressor tuples are in X column order and exclude the intercept. Arrays are read-only, also after unpickling.

Attributes:

Name Type Description
W tuple of numpy.ndarray

(n_neurons, r_p) left factors \(U_p\Sigma_p^{1/2}\) of the truncated SVD of B_full[p], (M17); (n_neurons, 0) at rank 0. Signs are deterministic: the entry of largest absolute value of each column of \(U_p\) is positive. With precision_weighted, \(D^{-1}U_p\Sigma_p^{1/2}\) with \(U_p\), \(\Sigma_p\) from the SVD of \(D\,\)B_full[p].

S tuple of numpy.ndarray

(n_bins, r_p) temporal factors \(V_p\Sigma_p^{1/2}\), (M17), the reference's wt{p}; columns ordered by decreasing singular value.

B tuple of numpy.ndarray

(n_neurons, n_bins) rank-r_p coefficients W[p] @ S[p].T, (M18): the best rank-r_p approximation of B_full[p] in the Frobenius norm, or, with precision_weighted, in the row-weighted norm of (M18w).

B_full tuple of numpy.ndarray

(n_neurons, n_bins) unconstrained per-neuron least-squares coefficients, (M15)-(M16).

intercept ndarray or None

(n_neurons, n_bins) condition-independent term refitted given the truncated B, (M19b): \(\hat b_i=\frac{n_i}{n_i+\gamma}\big(\bar y_i-\sum_p\bar x_{ip}B_p[i,:]\big)\), the exact maximiser over \(b\) of the plug-in likelihood at B; None when fitted with condition_independent=False.

intercept_full ndarray or None

(n_neurons, n_bins) the intercept of the unconstrained fit, the coefficient of the appended column of ones (the reference's b0, \(\frac{n_i}{n_i+\gamma}(\bar y_i-\sum_p\bar x_{ip}\hat B_p[i,:])\)); equal to intercept at full rank. None without an intercept.

noise_precision ndarray

(n_neurons,), \(\hat\lambda_i=n_iT/\mathrm{RSS}_i\) with the aligned residual of the rank-truncated fit and intercept, (M19b).

log_likelihood float

Plug-in Gaussian log-likelihood of the observed entries at \((B, \hat b, \hat\lambda)\), fully normalised: \(-\tfrac12\sum_in_iT\,[\log(\mathrm{RSS}_i/n_iT)+1+\log2\pi]\), (M21a).

n_parameters int

aic.n_parameters_svd(ranks, ...), the textbook count (M21b).

aic float

2 * n_parameters - 2 * log_likelihood, (M21b).

rank_deficient_neurons ndarray

(n_flagged,) int, neurons whose observed design was rank-deficient and which got the minimum-norm least-squares solution.

ranks tuple of int

The ranks fitted, one per regressor.

precision_weighted bool

Whether B is the precision-weighted truncation.

fit_svd(stats, ranks, *, ridge=0.0, condition_independent=True, precision_weighted=False)

Fit the SVD / reduced-rank estimator, (M15)-(M21).

  1. Least squares, (M15)-(M16). For each neuron, with the design \(X^f_i=[X_i\ \mathbf 1]\) of its observed trials (the column of ones only when condition_independent=True), \(\hat\beta_i=(A^f_i+\gamma I)^{-1} \xi^f_i\) gives the rows B_full[p][i, :] and the intercept intercept_full[i, :]. The ridge \(\gamma\) is added to every coefficient, the intercept's included, as SVDRegressB does. With the intercept the system is solved in its exact centred form: the intercept is eliminated, leaving \((\tilde A_i+\gamma I+c_i\bar x_i\bar x_i^\top)\,\hat B_{\cdot,i}= \tilde\xi_i+c_i\bar x_i\bar y_i^\top\) with \(c_i=n_i\gamma/(n_i+\gamma)\) (\(c_i=0\) without a ridge), on the moments about the means.
  2. Rank-deficient neurons. When that system is numerically singular (the smallest eigenvalue of its unit-diagonal rescaling is at most RANK_TOLERANCE, a scale-invariant test that, on the centred moments, is also shift-invariant), the neuron gets the minimum-norm least-squares solution for its regressor coefficients, computed in the retained range, it is listed in rank_deficient_neurons, and one DesignWarning names such neurons. A ridge that is not negligible against the Gram removes the case.
  3. Truncation, (M17)-(M18). \(\hat B_p=U_p\Sigma_pV_p^\top\); W[p] \(=U_p[:, :r_p]\Sigma_p^{1/2}\), S[p] \(=V_p[:, :r_p]\Sigma_p^{1/2}\), B[p] = W[p] @ S[p].T. With precision_weighted=True, (M18w), the rows are weighted first: with \(d_i\propto\sqrt{\hat\lambda^{\rm OLS}_in_i}\) (scaled to unit root mean square), \(\hat\lambda^{\rm OLS}_i=n_iT/\mathrm{RSS}^{\rm full}_i\) from the residual of the unconstrained fit of step 1 and \(D=\mathrm{diag}(d)\), \(D\hat B_p=U_p\Sigma_pV_p^\top\), W[p] \(=D^{-1}U_p[:, :r_p]\Sigma_p^{1/2}\) and S[p] as above: B[p] is the best rank-\(r_p\) approximation of \(\hat B_p\) in the norm \(\sum_id_i^2\lVert B[i,:]\rVert^2\).
  4. Intercept. Refitted given the truncated blocks, \(\hat b_i=\frac{n_i}{n_i+\gamma}\big(\bar y_i-\sum_p\bar x_{ip}B_p[i,:]\big)\), the maximiser over \(b\) of the plug-in likelihood at B, so the score does not depend on where a regressor's zero is.
  5. Noise precision, (M19b). \(\mathrm{RSS}_i=\sum_{k\in\mathcal K_i} \lVert Y_{ki\cdot}-\hat b_i-\sum_px_{kp}B_p[i,:]\rVert^2\) from the sufficient statistics, and \(\hat\lambda_i=n_iT/\mathrm{RSS}_i\).
  6. Score, (M21a)-(M21b). The fully normalised plug-in log-likelihood, the textbook count n_parameters_svd and the AIC.

Parameters:

Name Type Description Default
stats SufficientStats required
ranks sequence of int or 1-D integer array

Rank of each regressor's coefficient matrix, in X column order, 0 <= r_p <= min(n_neurons, n_bins). Rank 0 removes the regressor's term from the fitted model (its B_full is still estimated). The intercept is not an entry.

required
ridge float

\(\gamma\ge0\), added to every neuron's \(A^f_i\) (the reference's ridgeparam).

0.0
condition_independent bool

Fit the full-rank intercept. With False, Y should already be centred per neuron and bin.

True
precision_weighted bool

Truncate in the row-weighted norm of step 3 instead of the Frobenius norm. Steps 4-6 are unchanged: the intercept, the residual, the precisions, the log-likelihood and the AIC are computed from the weighted B exactly as from the unweighted one. Off by default, which is the reference's estimator; the weighted truncation seeds the marginal-likelihood rank search.

False

Returns:

Type Description
SVDFit

Factors, coefficients, intercepts, noise precisions and scores.

Raises:

Type Description
ParameterError

If stats is not a SufficientStats, ranks has the wrong length or an entry outside [0, min(n_neurons, n_bins)] (bools and floats are rejected), ridge is not a finite real >= 0, or condition_independent or precision_weighted is not a bool.

ValidationError

If a neuron was never observed, or if a neuron's residual is zero to rounding: \(\mathrm{RSS}_i\le10^3\,\epsilon\,T\,E_i\), \(E_i\) its energy about its mean (its raw energy without the intercept), as for an exact fit, a neuron constant over its trials, or one observed on no more trials than it has coefficients; its noise precision would be unbounded. A neuron with zero energy, \(E_i=0\), is rejected whatever its truncated residual, which can be a rounding-level positive number on some platforms. With precision_weighted=True, also if a neuron's unconstrained residual \(\mathrm{RSS}^{\rm full}_i\) is zero to rounding by the same test (its weight would be infinite). The message lists the neurons and the remedies.

Warns:

Type Description
DesignWarning

Once, listing the neurons given the minimum-norm solution.

Notes

Cost: \(O(n\,P^3 + n\,P^2\,T)\) for the per-neuron solves, batched, plus one batched SVD of the \(P\) matrices \(n\times T\), \(O(P\,n\,T\min(n,T))\). No loop over neurons.

\(\mathrm{RSS}_i\) is computed from the statistics. With the intercept it uses the moments about the means, so its rounding error is about \(\epsilon\) times the energy about the mean, whatever the baseline; without it, about \(\epsilon\) times the raw energy.

The SVD of the least-squares solution is not the rank-constrained maximum-likelihood estimate under unequal precisions or a mask, so log_likelihood is a plug-in score at the truncated estimate, and it is not on the scale of the marginal likelihood (docs/model.md § 3.3). The weighted truncation is that estimate at the precisions \(\hat\lambda^{\rm OLS}\) when each neuron's regressors are uncorrelated over its trials, with variances that do not depend on the neuron, and close to it otherwise; in the demo's heterogeneous-noise regime its AIC search recovered the true ranks far more often than the unweighted one.

Examples:

>>> import numpy as np
>>> from mtdr import simulate
>>> from mtdr.stats import sufficient_statistics
>>> from mtdr.svd_fit import fit_svd
>>> sim = simulate(n_neurons=30, n_bins=10, n_trials=200, ranks=[2, 1],
...                drop_prob=0.2, seed=1)
>>> fit = fit_svd(sufficient_statistics(sim.Y, sim.X, sim.mask), [2, 1])
>>> fit
SVDFit(ranks=(2, 1), n_neurons=30, n_bins=10, intercept=True, ...)
>>> [s.shape for s in fit.S], fit.W[0].shape
([(10, 2), (10, 1)], (30, 2))
>>> err = np.linalg.norm(fit.B[0] - sim.B["x0"]) / np.linalg.norm(sim.B["x0"])
>>> bool(err < 0.1)
True