Marginal-likelihood estimator¶
mtdr.mmle
¶
Maximum marginal likelihood: the mTDR estimator (docs/model.md § 4-6).
The neuron weights are integrated out under the prior \(w_i\sim\mathcal N(0,I)\) of (M4), so the temporal bases \(S_p\), the noise precisions \(\lambda_i\) and the intercept \(b\) are the parameters. By the determinant lemma and Woodbury, each neuron's marginal likelihood reduces to one \(r_{tot}\times r_{tot}\) system, (M22)-(M25):
with \(A_i\) the neuron's Gram matrix (M6) and \(\xi_i(b)\), \(\upsilon_i(b)\) its
intercept-centred cross-moment and energy (M13)-(M14), all read from the
SufficientStats; the data are never touched.
The public log-likelihoods are fully normalised, \(-\mathcal L\) at \(g=0\) minus
\(\tfrac12\sum_in_iT\log2\pi\).
The estimator (docs/model.md § 5) is the reference's
MMLE_CoordAscentWrapper: fit_svd initialises
\((S,\lambda)\) and \(b=\bar y\) (M29); ecme takes closed-form
conditional-maximisation steps (M30)-(M33) in the consistent multicycle form
(each step built from the current iterate); refine
maximises the marginal likelihood directly, alternating L-BFGS over \(S\), a
bounded L-BFGS step over \(\log\lambda\) and the closed-form intercept;
posterior_weights gives the posterior of the
weights (M36). fit_mmle chains them and returns an
MMLEFit.
Everything works in the estimator's raw frame: the likelihood is invariant
only under orthogonal rotations \(S_p\to S_pQ_p\) (docs/model.md § 10.1), so
a canonicalised S_ of a fitted MTDR is not a valid S argument.
Every kernel is batched over neurons (stacks of (n, r_tot, r_tot)
matrices); no loop over neurons runs outside an error path.
MONOTONE_RTOL = 1e-10
module-attribute
¶
Relative rounding allowance for "no worse" in ecme and refine.
An ECME iteration counts as raising the marginal NLL when it rises by more than
this times max(|NLL|, number of observed entries); a refinement step's
L-BFGS-B result is installed only if it raises the objective by no more than
this times max(|objective|, number of observed entries).
LOG_PRECISION_BOUND = 23.0
module-attribute
¶
Half-width, in log units, of each refinement precision step's box.
The box is centred on the current \(\log\lambda_i\) (a factor of about \(10^{10}\) either way) and intersected with the finite positive float64 range; ending on it counts as an inner failure.
PRECISION_RESIDUAL_TOL = 1e-08
module-attribute
¶
Scale-free stationarity a rounding-level precision-step end must reach.
A precision step whose L-BFGS-B run ends with status 2 (an abnormal line-search
end at rounding level) is first polished by at most POLISH_MAX_ITER diagonal
Newton steps, and counts as a success iff the installed point satisfies
\(\max_i\lvert\lambda_i\mathcal E_i/(n_iT)-1\rvert\le\) this, the projected
\(\theta\)-gradient relative to \(n_iT/2\); otherwise it is an inner failure.
ROUNDING_PROGRESS_FACTOR = 100.0
module-attribute
¶
\(c\) of the basis rule: a rounding-level end is a success.
A basis-step L-BFGS-B run that ends with status 2 (its line search found no
further decrease) at an accepted point with a finite gradient counts as a
success iff its last accepted decrease \(\Delta_{\rm last}\) (\(f_{k-1}-f_k\), or
\(f_0-f_{\rm end}\) after no accepted iterate) is at most
\(c\max(\texttt{optimizer\_progtol},\epsilon M)\), with \(M=\sum_i\lvert\)terms\(_i\rvert\)
the objective's rounding scale at the returned point (_basis_magnitude):
minFunc ends such a run normally ("function value changing by less than
progTol").
BASIS_SPAN_SCALE = 30.0
module-attribute
¶
The basis_span_scale of MTDR(basis_preconditioning=True)'s cold fits.
The basis objective is flat along the gauge \(S_p\to S_pQ_p\) and soft along the
rest of the in-span directions \(\delta S_p=S_pM_p\), which only the weight prior
pins down: at the paper's scale the stiffest of them is 8 to 190 times below
the softest other direction, so L-BFGS-B spends the second half of a run
crawling along them. Scaling them by \(\alpha\) in the optimiser's variables cuts
a cold fit's basis evaluations 7-10x; every \(\alpha\) from 30 to 100 does about
as well. The MATLAB reference has no counterpart: its minFunc runs on the raw
bases, which is \(\alpha=1\). MTDR reads this value when mtdr.model is
imported, so changing it at run time does not reach the class; pass
basis_span_scale to fit_mmle instead.
POLISH_MAX_ITER = 3
module-attribute
¶
Most diagonal Newton steps that polish a status-2 precision-step end.
The precision problem is separable per neuron given the bases, so its Hessian
in \(\theta=\log\lambda\) is diagonal; see _precision_derivatives.
MMLEFit
dataclass
¶
Result of the marginal-likelihood estimator.
Returned by fit_mmle, ecme and
refine, and accepted by the last two as a starting
point; from_parameters builds one
at given \((S,\lambda,b)\). Everything is in the estimator's raw frame.
Per-regressor containers are tuples in X column order and every array is
a read-only float64 copy (rank_deficient_neurons is int64), also
after unpickling. The constructor checks that the fields are consistent
with ranks and with each other (ParameterError): the shapes, finite
numbers, positive precisions, a symmetric W_cov that is positive
definite to rounding, objective <= log_likelihood and the AIC
arithmetic. It does not evaluate anything against data, nor check the
value of n_parameters (a caller may carry another count); the validated
entry point is from_parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
S |
tuple of numpy.ndarray
|
|
noise_precision |
ndarray
|
|
intercept |
ndarray or None
|
|
ranks |
tuple of int
|
\(r_p\), the widths of |
W |
tuple of numpy.ndarray
|
|
W_cov |
ndarray
|
|
log_likelihood |
float
|
Marginal log-likelihood at the fitted parameters, fully normalised, without the ridge. |
objective |
float
|
|
n_parameters |
int
|
The identifiable parameter count (M38a),
|
aic |
float
|
|
n_iter |
Mapping of str to int
|
Iterations used by the stages that produced the fit, |
converged |
bool
|
Provenance, not a certificate of stationarity: |
rank_deficient_neurons |
ndarray
|
|
Examples:
>>> from mtdr import simulate
>>> from mtdr.mmle import MMLEFit
>>> from mtdr.stats import sufficient_statistics
>>> sim = simulate(n_neurons=8, n_bins=5, n_trials=40, ranks=[1, 2], seed=0)
>>> stats = sufficient_statistics(sim.Y, sim.X, sim.mask)
>>> fit = MMLEFit.from_parameters(stats, [sim.S["x0"], sim.S["x1"]],
... sim.noise_precision, sim.intercept)
>>> fit
MMLEFit(ranks=(1, 2), n_neurons=8, n_bins=5, intercept=True, ...)
>>> fit.B[1].shape, fit.n_parameters == 8 + (5 + 9) + 40
((8, 5), True)
B
property
¶
Per regressor, (n_neurons, n_bins) coefficients \(\hat W_pS_p^\top\), (M37).
Derived once on construction, read-only; frame-independent.
n_neurons
property
¶
Number of neurons.
n_bins
property
¶
Number of time bins.
total_rank
property
¶
\(r_{tot}=\sum_pr_p\).
from_parameters(stats, S, noise_precision, intercept, *, basis_ridge=0.0)
classmethod
¶
Build a fit at given parameters: posterior, likelihood and counts there.
Evaluates (M24) and (M36) at \((S,\lambda,b)\), so the result can start
ecme or refine from any point
or score a parameter set. n_iter is empty, converged is True (no
stage ran, so none failed; it does not say the point is stationary) and
rank_deficient_neurons is empty. This is the validated way to build an
MMLEFit: every field is computed from the statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stats
|
SufficientStats
|
The statistics the posterior and the likelihood are evaluated on. |
required |
S
|
sequence of array_like
|
Per regressor, the |
required |
noise_precision
|
array_like of shape (n_neurons,)
|
\(\lambda_i>0\), as |
required |
intercept
|
array_like of shape (n_neurons, n_bins), or None
|
\(b\); |
required |
basis_ridge
|
float
|
\(g\ge0\), for |
0.0
|
Returns:
| Type | Description |
|---|---|
MMLEFit
|
The fit at the given parameters. |
Raises:
| Type | Description |
|---|---|
ParameterError
|
As |
(ValidationError, LinAlgError)
|
marginal_log_likelihood(S, noise_precision, intercept, stats, basis_ridge=0.0)
¶
Marginal log-likelihood with the weights integrated out, (M22)-(M24).
the fully normalised Gaussian log-density of every neuron's observed
responses under
\(\mathcal N(\mathbf 1\otimes b_i,\ \lambda_i^{-1}I+\Phi_i\Phi_i^\top)\),
minus the ridge when basis_ridge \(=g>0\) (the value is then the penalised
objective, not a log-likelihood). A neuron never observed contributes 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
S
|
sequence of array_like
|
Per regressor, the |
required |
noise_precision
|
array_like of shape (n_neurons,)
|
\(\lambda_i>0\). |
required |
intercept
|
array_like of shape (n_neurons, n_bins), or None
|
\(b\); |
required |
stats
|
SufficientStats
|
From |
required |
basis_ridge
|
float
|
\(g\ge0\), the ridge on the bases. |
0.0
|
Returns:
| Type | Description |
|---|---|
float
|
The log-likelihood (or the penalised objective). |
Raises:
| Type | Description |
|---|---|
ParameterError
|
For a |
ValidationError
|
If the value is not representable in float64 at these parameters (it
overflows), naming the neurons; never a |
LinAlgError
|
If a posterior precision \(C_i\) is not finite or not numerically positive definite, naming the neurons. |
Notes
Cost: \(O(n\,r_{tot}^3+n\,P\,T\,r_{tot}+T\,r_{tot}^2)\) time (one batched
Cholesky factorisation and inverse) and \(O(n\,r_{tot}^2)\) memory. The
explained quadratic is evaluated as \(\lambda_i^2u_i^\top C_i^{-1}u_i=\lVert
z_i\rVert^2\) with the scaled solve \(z_i=L_i^{-1}(\lambda_iu_i)\),
\(C_i=L_iL_i^\top\), so that only the whitened products \(\lambda_iu_i\) and
\(\lambda_iK_i\) are formed, which are of ordinary size at any scaling of
\(Y\) and \(\lambda\) (docs/model.md § 10.2); \(u_i^\top C_i^{-1}u_i\) and
\(\lambda_i^2\) separately can overflow on finite, well-conditioned inputs.
The quadratic term \(\lambda_i\upsilon_i(b)-\lVert z_i\rVert^2\) is a
difference of terms of the size of the neuron's energy, so it loses about
\(\log_{10}\) of the signal-to-noise power ratio in digits, as the
reference's does.
Examples:
>>> import numpy as np
>>> from mtdr import simulate
>>> from mtdr.mmle import marginal_log_likelihood
>>> from mtdr.stats import sufficient_statistics
>>> sim = simulate(n_neurons=8, n_bins=5, n_trials=40, ranks=[1, 2], seed=0)
>>> stats = sufficient_statistics(sim.Y, sim.X, sim.mask)
>>> S = [sim.S["x0"], sim.S["x1"]]
>>> ll = marginal_log_likelihood(S, sim.noise_precision, sim.intercept, stats)
>>> bool(np.isfinite(ll))
True
marginal_nll_grad_S(S, noise_precision, intercept, stats, basis_ridge=0.0)
¶
Marginal NLL and its gradient with respect to the bases, (M24), (M26a)-(M26b).
with \(\mu_i\), \(\Omega_i\) the posterior mean and second moment of the weights (M25): (M26b), the expected complete-data gradient, equal to the reference's (M26a) identically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
S
|
sequence of array_like
|
Per regressor, the |
required |
noise_precision
|
array_like of shape (n_neurons,)
|
\(\lambda_i>0\), as |
required |
intercept
|
array_like of shape (n_neurons, n_bins), or None
|
\(b\); |
required |
stats
|
SufficientStats
|
The statistics. |
required |
basis_ridge
|
float
|
\(g\ge0\), the ridge on the bases. |
0.0
|
Returns:
| Name | Type | Description |
|---|---|---|
value |
float
|
|
gradient |
list of numpy.ndarray
|
Per regressor, |
Raises:
| Type | Description |
|---|---|
(ParameterError, ValidationError, LinAlgError)
|
As |
Examples:
>>> from mtdr import simulate
>>> from mtdr.mmle import marginal_nll_grad_S
>>> from mtdr.stats import sufficient_statistics
>>> sim = simulate(n_neurons=8, n_bins=5, n_trials=40, ranks=[1, 2], seed=0)
>>> stats = sufficient_statistics(sim.Y, sim.X, sim.mask)
>>> S = [sim.S["x0"], sim.S["x1"]]
>>> value, grad = marginal_nll_grad_S(S, sim.noise_precision, sim.intercept, stats)
>>> [g.shape for g in grad]
[(5, 1), (5, 2)]
marginal_nll_grad_noise(S, noise_precision, intercept, stats)
¶
Marginal NLL and its gradient in the noise precisions, (M27a)-(M27b).
\(\mathcal E_i\) being the posterior expected residual energy \(\mathbb E\lVert\tilde\zeta_i-\Phi_iw_i\rVert^2\). Each \(\lambda_i\) enters only neuron \(i\)'s term.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
S
|
sequence of array_like
|
Per regressor, the |
required |
noise_precision
|
array_like of shape (n_neurons,)
|
\(\lambda_i>0\), as |
required |
intercept
|
array_like of shape (n_neurons, n_bins), or None
|
\(b\); |
required |
stats
|
SufficientStats
|
The statistics. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
value |
float
|
The fully normalised marginal NLL, |
gradient |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
(ParameterError, ValidationError, LinAlgError)
|
As |
Examples:
>>> from mtdr import simulate
>>> from mtdr.mmle import marginal_nll_grad_noise
>>> from mtdr.stats import sufficient_statistics
>>> sim = simulate(n_neurons=8, n_bins=5, n_trials=40, ranks=[1, 2], seed=0)
>>> stats = sufficient_statistics(sim.Y, sim.X, sim.mask)
>>> S = [sim.S["x0"], sim.S["x1"]]
>>> value, grad = marginal_nll_grad_noise(S, sim.noise_precision,
... sim.intercept, stats)
>>> grad.shape
(8,)
posterior_weights(S, noise_precision, intercept, stats)
¶
Posterior of each neuron's stacked weight vector, (M25), (M36).
the reference's EBpost_W_uneqvar with the intercept-centred statistic
\(\xi_i(b)\), as demoLearning.m calls it (mTDRdemo.m:155 passes the raw
statistic, a bug; see docs/differences-from-matlab.md).
\(\hat W_p[i,:]=(\mu_i)_{[p]}\), and \(\hat B_p=\hat W_pS_p^\top\) is (M37).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
S
|
sequence of array_like
|
Per regressor, the |
required |
noise_precision
|
array_like of shape (n_neurons,)
|
\(\lambda_i>0\), as |
required |
intercept
|
array_like of shape (n_neurons, n_bins), or None
|
\(b\); |
required |
stats
|
SufficientStats
|
The statistics. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
W_mean |
list of numpy.ndarray
|
Per regressor, |
W_cov |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
(ParameterError, ValidationError, LinAlgError)
|
Examples:
>>> from mtdr import simulate
>>> from mtdr.mmle import posterior_weights
>>> from mtdr.stats import sufficient_statistics
>>> sim = simulate(n_neurons=8, n_bins=5, n_trials=40, ranks=[1, 2], seed=0)
>>> stats = sufficient_statistics(sim.Y, sim.X, sim.mask)
>>> S = [sim.S["x0"], sim.S["x1"]]
>>> W, W_cov = posterior_weights(S, sim.noise_precision, sim.intercept, stats)
>>> [w.shape for w in W], W_cov.shape
([(8, 1), (8, 2)], (8, 3, 3))
update_intercept(S, noise_precision, stats)
¶
Return the intercept maximising the marginal likelihood given \((S,\lambda)\).
docs/model.md (M32)-(M33).
(M33) is the generalised-least-squares mean of \(\zeta_i\sim\mathcal N(\mathbf 1\otimes b_i,\Sigma_i)\),
with the raw \(\xi_i\) of (M10), so no current intercept is needed. It is evaluated in the equivalent form
from the moments about the neuron's means (\(\tilde A_i\), \(\tilde\xi_i\)): the mean response minus the fit at the mean regressor, with the weights at their posterior mean under the model with the intercept profiled out. The forms are equal by Woodbury (\([I_T-\lambda_in_i\Psi_iC_i^{-1}\Psi_i^\top]^{-1}=I_T+\lambda_in_i\Psi_i \tilde C_i^{-1}\Psi_i^\top\) and \(C_i=\tilde C_i+\lambda_in_i\Psi_i^\top\Psi_i\)); this one needs no \(T\times T\) solve and has no cancellation with a large baseline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
S
|
sequence of array_like
|
Per regressor, the |
required |
noise_precision
|
array_like of shape (n_neurons,)
|
\(\lambda_i>0\), as |
required |
stats
|
SufficientStats
|
The statistics. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ParameterError
|
|
ValidationError
|
If a neuron was never observed (its intercept is undefined). |
Examples:
>>> from mtdr import simulate
>>> from mtdr.mmle import update_intercept
>>> from mtdr.stats import sufficient_statistics
>>> sim = simulate(n_neurons=8, n_bins=5, n_trials=40, ranks=[1, 2], seed=0)
>>> stats = sufficient_statistics(sim.Y, sim.X, sim.mask)
>>> b = update_intercept([sim.S["x0"], sim.S["x1"]], sim.noise_precision, stats)
>>> b.shape
(8, 5)
ecme(stats, init, *, max_iter=100, tol=1.0, convergence_eps=1e-12, condition_independent=True, matlab_compat=False, verbose=0)
¶
ECME: closed-form conditional maximisation, docs/model.md § C.6, (M30)-(M34).
One iteration maps \((\lambda,S,b)\mapsto(\lambda',S',b')\):
- E-step at \((\lambda,S,b)\): \(C_i\), \(u_i\), \(\mu_i\), \(\Omega_i\), (M22)-(M25).
- Precisions, (M30): \(\lambda'_i=n_iT/\mathcal E_i\) with \(\mathcal E_i=\upsilon_i(b)-2u_i^\top\mu_i +\mathrm{tr}(\Phi_i^\top\Phi_i\Omega_i)\).
- Bases, (M31), the multicycle form: the E-step is redone at \((\lambda',S)\) and the expected complete-data likelihood maximised over \(S\), one symmetric positive-definite \(r_{tot}\times r_{tot}\) system.
- Intercept, (M33): the exact maximiser of the marginal likelihood
given \((\lambda',S')\), in the centred form of
update_intercept(skipped without the intercept). - Stop when \(\max_j(\theta'_j-\theta_j)^2/(\theta_j^2+\epsilon)<\)
tolover \(\theta=(\lambda;s;\mathrm{vec}\,b)\), (M34) with the floor \(\epsilon=\)convergence_epsfor entries near zero, or aftermax_iteriterations.
Each step conditionally maximises the expected complete-data or the marginal likelihood, so the marginal NLL (M24) does not increase; the returned trace shows it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stats
|
SufficientStats
|
The statistics. |
required |
init
|
MMLEFit
|
The starting point, from
|
required |
max_iter
|
int
|
Iteration cap, |
100
|
tol
|
float
|
Stopping threshold, finite and |
1.0
|
convergence_eps
|
float
|
\(\epsilon>0\), the floor of the stopping test's denominator. |
1e-12
|
condition_independent
|
bool
|
Whether the model has the intercept; must match |
True
|
matlab_compat
|
bool
|
Reproduce the reference's stale-variable S- and b-steps ( |
False
|
verbose
|
int
|
|
0
|
Returns:
| Name | Type | Description |
|---|---|---|
fit |
MMLEFit
|
The fit after the last iteration, with its posterior and likelihood;
|
trace |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ParameterError
|
For bad arguments, or an |
ValidationError
|
For a neuron never observed; observed once while the model has an
intercept ( |
LinAlgError
|
If a posterior precision is not positive definite. |
Warns:
| Type | Description |
|---|---|
ConvergenceWarning
|
When this call hit its cap or raised the NLL. |
Notes
Cost per iteration: three batched factorisations of (n, r_tot, r_tot)
precisions ((M22) at the current point, again at \(\lambda'\), and the
centred one of the intercept step) and one \(r_{tot}\times r_{tot}\) solve,
\(O(n\,r_{tot}^3+n\,P\,T\,r_{tot}+r_{tot}^2T)\).
Examples:
>>> import numpy as np
>>> from mtdr import simulate
>>> from mtdr.mmle import MMLEFit, ecme
>>> from mtdr.stats import sufficient_statistics
>>> from mtdr.svd_fit import fit_svd
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=60, ranks=[1, 2], seed=0)
>>> stats = sufficient_statistics(sim.Y, sim.X, sim.mask)
>>> svd = fit_svd(stats, [1, 2])
>>> init = MMLEFit.from_parameters(stats, svd.S, svd.noise_precision, stats.Y_mean)
>>> fit, trace = ecme(stats, init) # the reference's loose tol = 1.0
>>> bool(np.all(np.diff(trace) <= 0)), fit.n_iter["ecme"] == trace.size - 1
(True, True)
>>> fit.converged
True
refine(stats, init, *, max_iter=10, tol=0.0001, convergence_eps=1e-12, optimizer_max_iter=2000, optimizer_tol=1e-06, optimizer_progtol=1e-09, basis_ridge=0.0, basis_span_scale=1.0, condition_independent=True, verbose=0)
¶
Coordinate ascent on the marginal likelihood, docs/model.md § C.7.
Repeats, from init:
- the intercept-centred statistics at the current \(b\), (M13)-(M14);
- \(S\leftarrow\arg\min_S\,\mathcal L(\lambda,S;b)+\tfrac g2\lVert s\rVert^2\)
by L-BFGS-B with the analytic gradient (M26b) (the reference's
minFunc); - \(\lambda\leftarrow\arg\min_\lambda\mathcal L(\lambda,S;b)\) by L-BFGS-B over
\(\log\lambda\), with the gradient \(\lambda_i\,\partial\mathcal
L/\partial\lambda_i\) of (M27b), within
LOG_PRECISION_BOUNDof the current \(\log\lambda_i\) (the reference's unconstrainedfminunccan make \(\lambda_i\le0\); seedocs/differences-from-matlab.md); - \(b\leftarrow\) (M33) at the new \((S,\lambda)\) (skipped without the intercept);
- stop when the change (M34) of \((\lambda;s;\mathrm{vec}\,b)\), floored as
in
ecme, falls belowtol, or aftermax_iteriterations.
An L-BFGS-B result is installed only if its objective (the ridge included)
is finite and no higher than at the current point, within MONOTONE_RTOL
times \(\max(\lvert f\rvert,\sum_in_iT)\); otherwise the current point is
kept and the run counts as a failure. The intercept step is the exact
conditional maximiser. So the result is never worse than init
re-evaluated at basis_ridge, to that rounding allowance. The inner
problems minimise (M24) as the reference computes it, without the
\(\tfrac12\sum_in_iT\log2\pi\) constant, so L-BFGS-B's relative
function-decrease test sees the reference's function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stats
|
SufficientStats
|
The statistics. |
required |
init
|
MMLEFit
|
The starting point, usually the output of |
required |
max_iter
|
int
|
Iteration cap, |
10
|
tol
|
float
|
Stopping threshold on the change (M34), as in |
0.0001
|
convergence_eps
|
float
|
\(\epsilon>0\), the floor of the stopping test's denominator. |
1e-12
|
optimizer_max_iter
|
int
|
|
2000
|
optimizer_tol
|
float
|
Finite and |
1e-06
|
optimizer_progtol
|
float
|
Finite and |
1e-09
|
basis_ridge
|
float
|
\(g\ge0\), the ridge on the bases; |
0.0
|
basis_span_scale
|
float
|
Finite and |
1.0
|
condition_independent
|
bool
|
Whether the model has the intercept; must match |
True
|
verbose
|
int
|
|
0
|
Returns:
| Type | Description |
|---|---|
MMLEFit
|
The refined fit. |
Raises:
| Type | Description |
|---|---|
(ParameterError, ValidationError, LinAlgError)
|
As |
Warns:
| Type | Description |
|---|---|
ConvergenceWarning
|
When this call hit its cap or an inner call failed (a rounding-level
line-search end is not a failure). Each failure names the iteration and
the step, with SciPy's message, status, iteration count ( |
Notes
Cost: an inner evaluation is one evaluation of (M24) with its gradient, \(O(n\,r_{tot}^3+n\,P\,T\,r_{tot}+T\,r_{tot}^2)\); an iteration is two L-BFGS-B runs (tens of evaluations each) and one intercept step.
Examples:
>>> from mtdr import simulate
>>> from mtdr.mmle import MMLEFit, ecme, refine
>>> from mtdr.stats import sufficient_statistics
>>> from mtdr.svd_fit import fit_svd
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=60, ranks=[1, 2], seed=0)
>>> stats = sufficient_statistics(sim.Y, sim.X, sim.mask)
>>> svd = fit_svd(stats, [1, 2])
>>> init = MMLEFit.from_parameters(stats, svd.S, svd.noise_precision, stats.Y_mean)
>>> warm, _ = ecme(stats, init)
>>> fit = refine(stats, warm)
>>> bool(fit.log_likelihood >= warm.log_likelihood), fit.converged
(True, True)
fit_mmle(stats, ranks, init=None, *, condition_independent=True, ecme_max_iter=100, ecme_tol=1.0, refine_max_iter=10, refine_tol=0.0001, convergence_eps=1e-12, optimizer_max_iter=2000, optimizer_tol=1e-06, optimizer_progtol=1e-09, ridge=0.0, basis_ridge=0.0, basis_span_scale=1.0, verbose=0)
¶
Fit the marginal-likelihood estimator at fixed ranks, docs/model.md § 5.
The reference's MMLE_CoordAscentWrapper:
- Initialise, (M29):
fit_svdat the same ranks (the intercept handled inside it as a full-rank regressor), then \(S^{(0)}_p=\hat S^{svd}_p\), \(\lambda^{(0)}=\hat\lambda^{svd}\) and \(b^{(0)}_i=\bar y_i\) (the SVD's own intercept is discarded, as in the reference). ecmeto the loose toleranceecme_tol.refinetorefine_tol.- The posterior of the weights (M36) and the scores at the result, with the identifiable count (M38a).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stats
|
SufficientStats
|
The statistics. |
required |
ranks
|
sequence of int or 1-D integer array
|
\(r_p\) per regressor, |
required |
init
|
(MMLEFit, SVDFit or None)
|
|
None
|
condition_independent
|
bool
|
Fit the intercept. |
True
|
ecme_max_iter
|
int
|
ECME's cap, |
100
|
ecme_tol
|
float
|
ECME's stopping threshold on the change (M34): |
1.0
|
refine_max_iter
|
int
|
The refinement's cap: |
10
|
refine_tol
|
float
|
The refinement's stopping threshold on the change (M34): |
0.0001
|
convergence_eps
|
float
|
The stopping test's \(\epsilon\), shared by both loops. |
1e-12
|
optimizer_max_iter
|
int
|
|
2000
|
optimizer_tol
|
float
|
Their projected-gradient test |
1e-06
|
optimizer_progtol
|
float
|
The absolute function change at which the basis step stops. |
1e-09
|
ridge
|
float
|
The SVD initializer's ridge, |
0.0
|
basis_ridge
|
float
|
\(g\), the ridge on the bases in the refinement. |
0.0
|
basis_span_scale
|
float
|
\(\alpha\) of the refinement's basis-step preconditioning: |
1.0
|
verbose
|
int
|
|
0
|
Returns:
| Type | Description |
|---|---|
MMLEFit
|
The fit; |
Raises:
| Type | Description |
|---|---|
ParameterError
|
For bad arguments or ranks, or an |
(ValidationError, LinAlgError)
|
Warns:
| Type | Description |
|---|---|
DesignWarning
|
From |
ConvergenceWarning
|
From |
Notes
The 05_benchmarks example times fits at the demo's and the paper's scale.
Examples:
>>> import numpy as np
>>> from mtdr import simulate
>>> from mtdr.mmle import fit_mmle
>>> from mtdr.stats import sufficient_statistics
>>> sim = simulate(n_neurons=30, n_bins=10, n_trials=200, ranks=[2, 1],
... drop_prob=0.2, seed=1)
>>> stats = sufficient_statistics(sim.Y, sim.X, sim.mask)
>>> fit = fit_mmle(stats, [2, 1])
>>> fit
MMLEFit(ranks=(2, 1), n_neurons=30, n_bins=10, intercept=True, ...)
>>> err = np.linalg.norm(fit.B[0] - sim.B["x0"]) / np.linalg.norm(sim.B["x0"])
>>> bool(err < 0.1), fit.converged
(True, True)