Skip to content

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):

\[ C_i=I+\lambda_i\Phi_i^\top\Phi_i,\qquad (\Phi_i^\top\Phi_i)_{[pq]}=[A_i]_{pq}\,S_p^\top S_q,\qquad (u_i)_{[p]}=S_p^\top\xi_i(b)_{\langle p\rangle}, \]
\[ \mathcal L(\lambda,S;b)=\frac12\sum_{i=1}^n\Big[-n_iT\log\lambda_i +\log\lvert C_i\rvert+\lambda_i\upsilon_i(b)-\lambda_i^2\,u_i^\top C_i^{-1}u_i\Big] +\frac g2\lVert s\rVert^2 , \]

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

(n_bins, r_p) temporal bases, the fitted parameters.

noise_precision ndarray

(n_neurons,) noise precisions \(\lambda_i>0\).

intercept ndarray or None

(n_neurons, n_bins) intercept \(b\), or None without one.

ranks tuple of int

\(r_p\), the widths of S[p] and W[p].

W tuple of numpy.ndarray

(n_neurons, r_p) posterior means of the weights at the fitted parameters, (M36).

W_cov ndarray

(n_neurons, total_rank, total_rank) posterior covariances \(C_i^{-1}\) of the stacked weight vectors, (M36); blocks in regressor order.

log_likelihood float

Marginal log-likelihood at the fitted parameters, fully normalised, without the ridge.

objective float

log_likelihood - basis_ridge / 2 * sum(||S_p||^2), what the refinement maximised (equal to log_likelihood at basis_ridge=0).

n_parameters int

The identifiable parameter count (M38a), n_parameters_mmle.

aic float

2 * n_parameters - 2 * log_likelihood.

n_iter Mapping of str to int

Iterations used by the stages that produced the fit, "ecme" and "refine", summed over repeated calls of a stage (read-only; empty for a fit built from parameters).

converged bool

Provenance, not a certificate of stationarity: True iff no stage that produced the fit failed, that is, no ECME or refinement loop hit its cap, no ECME iteration raised the marginal NLL (not checked under matlab_compat), and every inner optimiser call succeeded with an accepted result and off its precision bound. A fit from from_parameters, or from zero-iteration stages, is True; one failed stage keeps every later fit built on it False.

rank_deficient_neurons ndarray

(n_flagged,) int, the neurons the SVD initializer solved by minimum norm; empty when the fit did not start from fit_svd.

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 (n_bins, r_p) bases, as marginal_log_likelihood; each r_p at most min(n_neurons, n_bins), as the count (M38a) requires.

required
noise_precision array_like of shape (n_neurons,)

\(\lambda_i>0\), as marginal_log_likelihood.

required
intercept array_like of shape (n_neurons, n_bins), or None

\(b\); None without the intercept.

required
basis_ridge float

\(g\ge0\), for objective.

0.0

Returns:

Type Description
MMLEFit

The fit at the given parameters.

Raises:

Type Description
ParameterError

As marginal_log_likelihood, or for a rank above min(n_neurons, n_bins).

(ValidationError, LinAlgError)

marginal_log_likelihood(S, noise_precision, intercept, stats, basis_ridge=0.0)

Marginal log-likelihood with the weights integrated out, (M22)-(M24).

\[ \ell(S,\lambda,b)=-\mathcal L(\lambda,S;b)\big|_{g=0}-\tfrac12\sum_in_iT\log2\pi -\tfrac g2\sum_p\lVert S_p\rVert_F^2 , \]

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 (n_bins, r_p) bases in X column order, in the estimator's raw frame; r_p may be 0.

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\); None for a model without the intercept.

required
stats SufficientStats 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 stats that is not a SufficientStats; an S with the wrong number of blocks or a block that is not a finite real (n_bins, r_p) array; a noise_precision that is not a finite positive (n_neurons,) array; a bad intercept; a negative basis_ridge.

ValidationError

If the value is not representable in float64 at these parameters (it overflows), naming the neurons; never a NaN.

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).

\[ \frac{\partial\mathcal L}{\partial S_p}=\sum_{i=1}^n\lambda_i\Big[\sum_q[A_i]_{pq}\, S_q\,(\Omega_i)_{[qp]}-\xi_i(b)_{\langle p\rangle}(\mu_i)_{[p]}^\top\Big]+g\,S_p , \]

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 (n_bins, r_p) bases, as marginal_log_likelihood.

required
noise_precision array_like of shape (n_neurons,)

\(\lambda_i>0\), as marginal_log_likelihood.

required
intercept array_like of shape (n_neurons, n_bins), or None

\(b\); None without the intercept.

required
stats SufficientStats

The statistics.

required
basis_ridge float

\(g\ge0\), the ridge on the bases.

0.0

Returns:

Name Type Description
value float

-marginal_log_likelihood(S, noise_precision, intercept, stats, basis_ridge): the fully normalised NLL plus \(\tfrac g2\lVert s\rVert^2\), the function the gradient is of.

gradient list of numpy.ndarray

Per regressor, (n_bins, r_p), \(\partial(\text{value})/\partial S_p\).

Raises:

Type Description
(ParameterError, ValidationError, LinAlgError)

As marginal_log_likelihood; the ValidationError also if the gradient overflows.

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).

\[ \frac{\partial\mathcal L}{\partial\lambda_i} =\frac12\Big[-\frac{n_iT}{\lambda_i}+\mathcal E_i\Big],\qquad \mathcal E_i=\upsilon_i(b)-2u_i^\top\mu_i +\mathrm{tr}\big(\Phi_i^\top\Phi_i\,\Omega_i\big), \]

\(\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 (n_bins, r_p) bases, as marginal_log_likelihood.

required
noise_precision array_like of shape (n_neurons,)

\(\lambda_i>0\), as marginal_log_likelihood.

required
intercept array_like of shape (n_neurons, n_bins), or None

\(b\); None without the intercept.

required
stats SufficientStats

The statistics.

required

Returns:

Name Type Description
value float

The fully normalised marginal NLL, -marginal_log_likelihood(S, noise_precision, intercept, stats) (no ridge: it does not depend on \(\lambda\)).

gradient ndarray

(n_neurons,), \(\partial(\text{value})/\partial\lambda_i\); 0 for a neuron never observed.

Raises:

Type Description
(ParameterError, ValidationError, LinAlgError)

As marginal_log_likelihood; the ValidationError also if the gradient overflows.

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).

\[ w_i\mid\zeta_i,S,\lambda,b\sim\mathcal N\big(\mu_i,\ C_i^{-1}\big),\qquad \mu_i=\lambda_iC_i^{-1}u_i,\qquad C_i=I+\lambda_i\Phi_i^\top\Phi_i , \]

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 (n_bins, r_p) bases, as marginal_log_likelihood.

required
noise_precision array_like of shape (n_neurons,)

\(\lambda_i>0\), as marginal_log_likelihood.

required
intercept array_like of shape (n_neurons, n_bins), or None

\(b\); None without the intercept.

required
stats SufficientStats

The statistics.

required

Returns:

Name Type Description
W_mean list of numpy.ndarray

Per regressor, (n_neurons, r_p) posterior means.

W_cov ndarray

(n_neurons, total_rank, total_rank) posterior covariances \(C_i^{-1}\), blocks in regressor order; the identity for a neuron never observed (its posterior is the prior).

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)\),

\[ b_i=\big[I_T-\lambda_in_i\Psi_iC_i^{-1}\Psi_i^\top\big]^{-1} \big(\bar y_i-\lambda_i\Psi_iC_i^{-1}\mathbf S\xi_i\big),\qquad \Psi_i=\big[\bar x_{i1}S_1,\dots,\bar x_{iP}S_P\big], \]

with the raw \(\xi_i\) of (M10), so no current intercept is needed. It is evaluated in the equivalent form

\[ b_i=\bar y_i-\Psi_i\tilde\mu_i,\qquad \tilde\mu_i=\lambda_i\tilde C_i^{-1}\mathbf S\tilde\xi_i,\qquad \tilde C_i=I+\lambda_i\mathbf S(\tilde A_i\otimes I_T)\mathbf S^\top , \]

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 (n_bins, r_p) bases, as marginal_log_likelihood.

required
noise_precision array_like of shape (n_neurons,)

\(\lambda_i>0\), as marginal_log_likelihood.

required
stats SufficientStats

The statistics.

required

Returns:

Type Description
ndarray

(n_neurons, n_bins), the intercept \(b\).

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')\):

  1. E-step at \((\lambda,S,b)\): \(C_i\), \(u_i\), \(\mu_i\), \(\Omega_i\), (M22)-(M25).
  2. 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)\).
  3. 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.
  4. Intercept, (M33): the exact maximiser of the marginal likelihood given \((\lambda',S')\), in the centred form of update_intercept (skipped without the intercept).
  5. Stop when \(\max_j(\theta'_j-\theta_j)^2/(\theta_j^2+\epsilon)<\) tol over \(\theta=(\lambda;s;\mathrm{vec}\,b)\), (M34) with the floor \(\epsilon=\) convergence_eps for entries near zero, or after max_iter iterations.

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 MMLEFit.from_parameters or a previous fit; its sizes and intercept must match stats and condition_independent.

required
max_iter int

Iteration cap, >= 0; 0 returns the starting point re-evaluated (docs/model.md § C.6: zero steps return the initial state), which is not reported as non-convergence.

100
tol float

Stopping threshold, finite and > 0 (the reference's stopcrit, loose by default on purpose: ECME is a warm start).

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 init.intercept.

True
matlab_compat bool

Reproduce the reference's stale-variable S- and b-steps (ECMEtdr.m) instead of (M31) and (M33): the S-step's right-hand side and second moment mix \(C_i(\lambda)\) and \(C_i(\lambda')\), its system is assembled with transposed diagonal blocks and solved as a general matrix, and the b-step uses \(C_i^\times=I+\lambda'_i\mathbf S_{\rm old}K_i\mathbf S_{\rm new}^\top\) with \((C^\times_i)^{-\top}\) on its right-hand side. One sweep and the whole loop agree with the reference's ECMEtdr iterate by iterate to \(10^{-12}\), with the same number of sweeps, on the reference run recorded in tests/fixtures/mmle.mat. For parity fixtures only: the trace is not guaranteed monotone, and an increase is not reported.

False
verbose int

0 silent; 1 one summary line; 2 also one line per iteration.

0

Returns:

Name Type Description
fit MMLEFit

The fit after the last iteration, with its posterior and likelihood; n_iter["ecme"] adds this call's iterations to init's count, and converged is False if the cap was hit, an iteration raised the marginal NLL by more than MONOTONE_RTOL (relative to max(|NLL|, number of observed entries)), or init.converged was False. Under matlab_compat=True rises are not checked, so converged=True there does not certify a monotone trace.

trace ndarray

(n_iter + 1,) fully normalised marginal NLL at the start and after each iteration (no ridge: ECME has none).

Raises:

Type Description
ParameterError

For bad arguments, or an init that is not an MMLEFit or does not match stats or condition_independent.

ValidationError

For a neuron never observed; observed once while the model has an intercept (docs/model.md § 10.3); with zero energy about its mean (zero raw energy without the intercept); without residual degrees of freedom, its unconstrained least-squares residual on \([X_i\ \mathbf 1]\) (\(X_i\) without the intercept) zero to rounding, as whenever \(n_i\le\operatorname{rank}[X_i\ \mathbf 1]\) (its marginal likelihood is unbounded); or whose expected residual \(\mathcal E_i\) of (M30) is zero to rounding, \(\mathcal E_i\le10^3\epsilon T\upsilon_i(b)\). Also when the basis system (M31) is singular because a regressor is zero on every observed trial, and when the likelihood is not representable in float64.

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:

  1. the intercept-centred statistics at the current \(b\), (M13)-(M14);
  2. \(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);
  3. \(\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_BOUND of the current \(\log\lambda_i\) (the reference's unconstrained fminunc can make \(\lambda_i\le0\); see docs/differences-from-matlab.md);
  4. \(b\leftarrow\) (M33) at the new \((S,\lambda)\) (skipped without the intercept);
  5. stop when the change (M34) of \((\lambda;s;\mathrm{vec}\,b)\), floored as in ecme, falls below tol, or after max_iter iterations.

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 ecme.

required
max_iter int

Iteration cap, >= 0 (0 returns init re-evaluated).

10
tol float

Stopping threshold on the change (M34), as in ecme, finite and > 0.

0.0001
convergence_eps float

\(\epsilon>0\), the floor of the stopping test's denominator.

1e-12
optimizer_max_iter int

maxiter of each scipy.optimize.minimize call, positive (default 2000: the first basis step at the paper's scale needs 582-909 iterations; the reference's minFunc stops at 500, which the parity tests pass explicitly).

2000
optimizer_tol float

Finite and > 0: L-BFGS-B's projected-gradient test gtol (minFunc's optTol in the reference).

1e-06
optimizer_progtol float

Finite and > 0: the absolute function change at which an inner run stops, minFunc's progTol, applied as L-BFGS-B's ftol = optimizer_progtol / max(|f0|, 1) with f0 the objective at the run's start, in the basis step (the precision step keeps a fixed relative ftol = 1e-11).

1e-09
basis_ridge float

\(g\ge0\), the ridge on the bases; objective includes it, log_likelihood does not.

0.0
basis_span_scale float

Finite and > 0: \(\alpha\) of the basis step's preconditioning. Each basis run's L-BFGS-B works in variables in which every block's component in the span of the run's start \(S_p\) is scaled by \(\alpha\), stiffening the soft in-span directions \(S_pM_p\); 1 (the default) is the plain run, the MATLAB reference's (minFunc on the raw bases). From a cold start (the SVD fit) BASIS_SPAN_SCALE reaches the same optimum in about 7-10x fewer evaluations; from a warm start whose new columns are not yet in their final span it can take more. It changes the optimiser's path, not its objective: optimizer_tol then applies to the scaled gradient, and a failure's projected-gradient entry is the scaled one.

1.0
condition_independent bool

Whether the model has the intercept; must match init.intercept.

True
verbose int

0 silent; 1 one summary line; 2 also one line per iteration.

0

Returns:

Type Description
MMLEFit

The refined fit. n_iter["refine"] adds this call's iterations to init's count; converged is False if the cap was hit, an inner call reported failure, had its result rejected or ended on its precision bound in any iteration, or init.converged was False.

Raises:

Type Description
(ParameterError, ValidationError, LinAlgError)

As ecme; the ValidationError for an expected residual zero to rounding is also raised at the refined point, so no stage returns a fit at a diverging precision.

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 (nit) and the largest projected-gradient entry; a failed basis step at an accepted point also gives its last accepted decrease, and a failed precision step names the neurons with the largest \(\lvert\lambda_i\mathcal E_i/(n_iT)-1\rvert\). Contact with the precision box is reported with its iteration; only contact in the final iteration is reported as a possibly unbounded likelihood.

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:

  1. Initialise, (M29): fit_svd at 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).
  2. ecme to the loose tolerance ecme_tol.
  3. refine to refine_tol.
  4. 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, 0 <= r_p <= min(n_neurons, n_bins).

required
init (MMLEFit, SVDFit or None)

None runs fit_svd (with ridge); an SVDFit is used as step 1's initializer; an MMLEFit skips step 1 and starts ECME from it. Its ranks must equal ranks and its intercept match condition_independent.

None
condition_independent bool

Fit the intercept.

True
ecme_max_iter int

ECME's cap, >= 0: max_iter of ecme.

100
ecme_tol float

ECME's stopping threshold on the change (M34): tol of ecme.

1.0
refine_max_iter int

The refinement's cap: max_iter of refine.

10
refine_tol float

The refinement's stopping threshold on the change (M34): tol of refine.

0.0001
convergence_eps float

The stopping test's \(\epsilon\), shared by both loops.

1e-12
optimizer_max_iter int

maxiter of every L-BFGS-B call of refine (default 2000).

2000
optimizer_tol float

Their projected-gradient test gtol.

1e-06
optimizer_progtol float

The absolute function change at which the basis step stops.

1e-09
ridge float

The SVD initializer's ridge, ridge of fit_svd.

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 (the default) is off, the MATLAB reference's basis step; BASIS_SPAN_SCALE suits a fit from its SVD start (init None or an SVDFit), not a warm MMLEFit start whose new columns are far from their final span. See refine.

1.0
verbose int

0, 1 or 2, passed to ecme and refine.

0

Returns:

Type Description
MMLEFit

The fit; n_iter holds "ecme" and "refine" (added to an MMLEFit start's counts), and converged covers both loops and every inner optimiser call; it reports that no stage failed, not that the result is stationary (zero caps return the start with True).

Raises:

Type Description
ParameterError

For bad arguments or ranks, or an init that does not match.

(ValidationError, LinAlgError)

As fit_svd and ecme.

Warns:

Type Description
DesignWarning

From fit_svd, for rank-deficient neurons.

ConvergenceWarning

From ecme or refine.

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)