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
|
|
S |
tuple of numpy.ndarray
|
|
B |
tuple of numpy.ndarray
|
|
B_full |
tuple of numpy.ndarray
|
|
intercept |
ndarray or None
|
|
intercept_full |
ndarray or None
|
|
noise_precision |
ndarray
|
|
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 |
float
|
|
rank_deficient_neurons |
ndarray
|
|
ranks |
tuple of int
|
The ranks fitted, one per regressor. |
precision_weighted |
bool
|
Whether |
fit_svd(stats, ranks, *, ridge=0.0, condition_independent=True, precision_weighted=False)
¶
Fit the SVD / reduced-rank estimator, (M15)-(M21).
- 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 rowsB_full[p][i, :]and the interceptintercept_full[i, :]. The ridge \(\gamma\) is added to every coefficient, the intercept's included, asSVDRegressBdoes. 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. - 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 inrank_deficient_neurons, and oneDesignWarningnames such neurons. Aridgethat is not negligible against the Gram removes the case. - 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. Withprecision_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}\) andS[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\). - 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. - 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\).
- Score, (M21a)-(M21b). The fully normalised plug-in
log-likelihood, the textbook count
n_parameters_svdand the AIC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stats
|
SufficientStats
|
From |
required |
ranks
|
sequence of int or 1-D integer array
|
Rank of each regressor's coefficient matrix, in |
required |
ridge
|
float
|
\(\gamma\ge0\), added to every neuron's \(A^f_i\) (the reference's
|
0.0
|
condition_independent
|
bool
|
Fit the full-rank intercept. With |
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 |
False
|
Returns:
| Type | Description |
|---|---|
SVDFit
|
Factors, coefficients, intercepts, noise precisions and scores. |
Raises:
| Type | Description |
|---|---|
ParameterError
|
If |
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 |
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