The MTDR estimator¶
converged_=False: what it means and what to do¶
For MMLE, converged_=False means that at least one optimisation step did not pass
the package's convergence checks. The fitted parameters are still returned, but
inspect the ConvergenceWarning and check the fit before interpreting the results.
The flag stays False if an earlier step failed, even when later steps finish
normally. True means the checks passed; it does not guarantee a global optimum.
The warning identifies the step and the reason. Start with the corresponding action:
| Warning mentions | Meaning and action |
|---|---|
| An iteration cap | Raise the named limit: ecme_max_iter, refine_max_iter or optimizer_max_iter, then refit. |
ABNORMAL or L-BFGS-B status 2 |
The optimiser could not find an acceptable next step. Check input conditioning with check_design, then assess a refit as below. |
| A result was not finite or raised the objective | That inner optimiser result was discarded and the previous parameters kept. Check input scales and design conditioning before refitting. |
| A neuron ended on the precision step bound | Its estimated noise precision reached the step limit. Inspect the named neurons for very small residual variation. |
| ECME raised the marginal NLL | An ECME update worsened the fit beyond the rounding allowance. Assess a refit; this warning is not covered by the inner optimiser's rule for discarding steps. |
Line searches that stop because further improvement is below numerical precision can pass the convergence checks without a warning. The criteria are in model §E.3.
In a rank search, converged_ describes the selected fit. The warning also lists
other candidate fits that failed. Their failures can affect rank selection even
when the selected fit converged.
To assess the result, fit again at the selected ranks with a tighter stopping tolerance and more refinement iterations. Use the same data and mask, and preserve the original settings, including regularisation and preconditioning:
params = model.get_params()
params.update(
ranks=model.ranks_,
refine_tol=min(model.refine_tol, 1e-8),
refine_max_iter=max(model.refine_max_iter, 50),
)
refit = MTDR(**params).fit(Y, X, mask, regressor_names=model.regressor_names_)
print(model.objective_, refit.objective_) # higher is better
Also raise any limit named in the warning. Compare objective_ and the coefficient
matrices B_, and inspect any new warnings. At basis_ridge=0, objective_ equals
the marginal training log_likelihood_; otherwise it includes the penalty.
A substantial objective gain shows that the original fit could be improved.
Similar objectives and coefficients provide evidence of stability, rather than
proof of an optimum.
This is a new fit, not a continuation. A fixed-rank fit starts from its own SVD
estimate, whereas the default rank search starts candidates from the preceding
accepted fit. The refit can therefore reach a different result, including a lower
objective. A substantial difference warrants checking sensitivity to initialisation;
rank_search_warm_start=False makes each search candidate start from its own SVD
estimate too. A fixed-rank check assesses the fit at those ranks; it does not check
whether failed candidates changed the rank-search outcome.
Plain per-neuron least squares¶
The natural baseline, ordinary least squares per neuron with the intercept, is the
"svd" estimator at full rank, where the truncation removes nothing:
P = X.shape[1]
ols = MTDR(ranks=[min(n_neurons, n_bins)] * P, estimator="svd").fit(Y, X, mask)
ols.B_ # each neuron's least-squares coefficients, regressor by regressor
The full rank is min(n_neurons, n_bins), not n_bins: a rank above it is a
ParameterError, so [n_bins] * P fails when there are fewer neurons than bins. Under
a mask each neuron's fit uses only its observed trials; with ridge > 0 it is ridge
regression.
Reference¶
mtdr.model
¶
The MTDR estimator.
MTDR composes the package's functional building blocks:
validate_inputs, the sufficient statistics of
mtdr.stats, the SVD estimator of mtdr.svd_fit,
the marginal-likelihood estimator of mtdr.mmle and the greedy
AIC search of mtdr.rank_search. It fits
(M1)-(M4), under the observation mask (M3), and derives from the fit the
projections (M49)-(M49a), the plug-in decoder (M46)-(M48c) and the held-out
plug-in likelihood. Per-regressor results are dicts keyed by regressor name, in
X column order.
MTDR
¶
Model-based targeted dimensionality reduction.
Fits, for every regressor \(p\), a low-rank coefficient matrix
\(B_p=W_pS_p^\top\) ((n_neurons, n_bins), rank \(r_p\)), a per-neuron noise
precision \(\lambda_i\) and, by default, a full-rank condition-independent
intercept, (M1)-(M4). estimator="mmle" (the default, the estimator of the
paper) integrates the weights out under \(w_i\sim\mathcal N(0,I)\) and
maximises the marginal likelihood (M24) by ECME and coordinate ascent
(docs/model.md § 5), then sets W_ to the posterior mean (M36);
estimator="svd" is reduced-rank regression, (M15)-(M18). ranks="aic"
chooses the ranks by the greedy AIC search (M39).
The constructor only stores and checks hyper-parameters (sklearn style);
fit learns, and fitted attributes end in _.
Fitting is deterministic: there is no random state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ranks
|
"aic", sequence of int or mapping of str to int
|
|
'aic'
|
estimator
|
('mmle', 'svd')
|
The marginal-likelihood estimator (default) or reduced-rank regression. |
"mmle"
|
condition_independent
|
bool
|
Fit the full-rank intercept. |
True
|
max_rank
|
int
|
Largest rank the search may assign (and a bound on fixed ranks);
|
None
|
min_observations
|
int
|
A neuron observed on fewer trials is a |
2
|
ridge
|
float
|
L2 penalty on every neuron's \(X_i^\top X_i\) in the least-squares stage. |
0.0
|
basis_ridge
|
float
|
L2 penalty \(\tfrac g2\lVert S\rVert^2\) on the bases ( |
0.0
|
rank_search_init
|
('svd_weighted', 'svd', 'ones')
|
Where the search starts: |
"svd_weighted"
|
rank_search_threshold
|
float
|
\(\delta\ge0\): a step is accepted only if it lowers the AIC by more. |
0.0
|
rank_search_warm_start
|
bool
|
Start each candidate of the MMLE search from the accepted fit instead of
from its own SVD fit: the accepted bases, noise precisions and
intercept, plus, for the raised regressor, the last component of the
unweighted SVD fit at the candidate's ranks. The search's first fit
stays cold. About 6x fewer basis-step evaluations per candidate at the
paper's scale and no change in any selected rank vector measured, so the
default; |
True
|
ecme_max_iter
|
int
|
ECME's iteration cap ( |
100
|
ecme_tol
|
float
|
ECME's threshold on the largest squared relative change of a parameter
in an iteration, (M34) with |
1.0
|
refine_max_iter
|
int
|
The coordinate ascent's iteration cap ( |
10
|
refine_tol
|
float
|
The coordinate ascent's threshold on the same change
( |
0.0001
|
convergence_eps
|
float
|
The term added to each \(\theta_j^2\) in that change, in both loops, so that a parameter that is exactly zero does not make it infinite. |
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 inner basis step stops,
minFunc's |
1e-09
|
canonicalize
|
bool
|
Rotate each \((W_p,S_p)\) into the PC orientation after fitting
( |
True
|
verbose
|
int
|
|
0
|
n_jobs
|
int or None
|
Worker processes for the candidate fits of each round of the MMLE
rank search: |
None
|
basis_preconditioning
|
bool
|
Speed up the MMLE refinement's basis step in every cold fit, one that
starts from its own SVD fit: the fixed-rank fit, the MMLE search's first
fit and, with |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
regressor_names_ |
tuple of str
|
Names in |
n_trials_ |
int
|
Trials seen in |
n_neurons_ |
int
|
Neurons seen in |
n_bins_ |
int
|
Time bins seen in |
n_regressors_ |
int
|
Columns of |
n_observations_ |
ndarray
|
|
ranks_ |
dict of str to int
|
The rank \(r_p\) of every regressor, chosen or fixed. |
total_rank_ |
int
|
\(\sum_pr_p\). |
W_ |
dict of str to numpy.ndarray
|
|
S_ |
dict of str to numpy.ndarray
|
|
B_ |
dict of str to numpy.ndarray
|
|
intercept_ |
ndarray or None
|
|
noise_precision_ |
ndarray
|
|
weight_posterior_cov_ |
ndarray or None
|
|
log_likelihood_ |
float
|
The training log-likelihood at the fit, fully normalised, in the
raw frame. Under |
objective_ |
float
|
What the fit maximised: |
n_parameters_ |
int
|
The count in |
aic_ |
float
|
|
rank_search_history_ |
RankSearchHistory or None
|
The record of the greedy AIC search (M39); |
estimator_ |
str
|
The estimator that produced the parameters, |
converged_ |
bool
|
Whether every stage of the selected MMLE fit passed its convergence
checks. |
n_iter_ |
dict of str to int
|
Iterations of |
condition_independent_ |
bool
|
Whether the model has the intercept. |
Raises:
| Type | Description |
|---|---|
ParameterError
|
For an invalid hyper-parameter (checks that need the data happen in
|
Notes
get_params / set_params follow the sklearn contract, so
sklearn.base.clone works; sklearn's cross-validation utilities do not
(fit(Y, X) takes the 3-D activity first). Fitted models pickle.
Examples:
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=40, n_bins=8, n_trials=200, ranks=[2, 1],
... drop_prob=0.2, seed=0)
>>> model = MTDR(ranks=[2, 1]).fit(sim.Y_masked, sim.X,
... regressor_names=["stim", "choice"])
>>> model.ranks_, model.W_["stim"].shape, model.B_["choice"].shape
({'stim': 2, 'choice': 1}, (40, 2), (40, 8))
>>> MTDR(ranks="aic", estimator="svd", max_rank=4)
MTDR(estimator='svd', max_rank=4)
get_params(deep=True)
¶
Return the hyper-parameters, as passed to the constructor (sklearn).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
deep
|
bool
|
Ignored (no nested estimators); accepted for sklearn compatibility. |
True
|
Returns:
| Type | Description |
|---|---|
dict of str to object
|
Every constructor argument by name. |
Examples:
>>> from mtdr import MTDR
>>> MTDR(ranks=[1, 2]).get_params()["ranks"]
[1, 2]
set_params(**params)
¶
Set hyper-parameters by name and check them (sklearn).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**params
|
Any
|
Constructor arguments to change. |
{}
|
Returns:
| Type | Description |
|---|---|
MTDR
|
|
Raises:
| Type | Description |
|---|---|
ParameterError
|
For an unknown name or an invalid value (the previous values are kept). |
Examples:
>>> from mtdr import MTDR
>>> MTDR().set_params(estimator="svd", max_rank=3)
MTDR(estimator='svd', max_rank=3)
fit(Y, X, mask=None, regressor_names=None)
¶
Fit the model to Y given X.
In order: validate_inputs with the
fit-only checks; the sufficient statistics (M6), (M10)-(M14); for
ranks="aic" the greedy AIC search (M39) of the estimator(s) chosen by
rank_search_init, else one fit at the fixed ranks; then the posterior
weights (M36) ("mmle"), the coefficient matrices (M37), the raw-frame
likelihood and AIC, and canonicalisation.
The MMLE search selects with the reference count (M38),
\(n+T\sum_pr_p+nT\), and n_parameters_ / aic_ report the identifiable
count (M38a); its history records the selection scores. The
DesignWarnings of the candidate fits (rank-deficient neurons) are
aggregated into one, and so are the ConvergenceWarnings of a search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
array_like
|
|
required |
X
|
array_like
|
|
required |
mask
|
array_like
|
|
None
|
regressor_names
|
sequence of str
|
Unique names; |
None
|
Returns:
| Type | Description |
|---|---|
MTDR
|
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
For invalid or degenerate data, including neurons below the
observation floor, zero-variance neurons, a rank-deficient pooled
|
ParameterError
|
For names of the wrong length or repeated; a |
LinAlgError
|
If a posterior precision \(C_i\) fails its Cholesky. |
Warns:
| Type | Description |
|---|---|
ConvergenceWarning
|
When a loop hit its cap or an inner optimiser failed. |
DesignWarning
|
For rank-deficient neurons, trials with no observed neuron,
near-collinear columns, column-scale disparities when
|
Notes
fit cannot tell the neuron axis from the bin axis: Y laid out
(n_trials, n_bins, n_neurons) fits without an error, with neurons and
bins swapped, so check model.n_neurons_ and model.n_bins_ after
fitting. The observation unit is the neuron-trial: without a
mask, one NaN bin makes the whole neuron-trial unobserved, its
finite bins included; impute partial NaNs first to keep those bins
(with a mask, a NaN under True is an error).
Examples:
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=60, n_bins=10, n_trials=300, ranks=[2, 1],
... drop_prob=0.2, seed=3)
>>> model = MTDR(ranks="aic", max_rank=5).fit(sim.Y_masked, sim.X)
>>> model.ranks_, model.rank_search_history_.stop_reason
({'x0': 2, 'x1': 1}, 'no_improvement')
predict(X)
¶
Return the expected response intercept_ + sum_p X[k, p] B_[p], (M1).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
array_like
|
|
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
NotFittedError
|
Before |
Examples:
>>> import numpy as np
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> model = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X)
>>> model.predict(sim.X[:3]).shape
(3, 20, 6)
log_likelihood(Y, X, mask=None, per_trial=False)
¶
log_likelihood(Y: ArrayLike, X: ArrayLike, mask: ArrayLike | None = ..., per_trial: Literal[False] = ...) -> float
log_likelihood(Y: ArrayLike, X: ArrayLike, mask: ArrayLike | None = ..., *, per_trial: Literal[True]) -> FloatArray
Plug-in Gaussian log-likelihood of Y under the fit, fully normalised.
\(\ell=\sum_{(k,i):\,h_{ki}}\sum_t\big[\tfrac12\log\lambda_i-\tfrac12\log2\pi
-\tfrac{\lambda_i}2(Y_{kit}-\hat Y_{kit})^2\big]\) with \(\hat Y\) from
predict: (M46) with \(x\) the trial's
regressors, summed over observed entries. Comparable across
estimators, unlike log_likelihood_. Neurons must be the fitted ones in
the same order; a neuron never observed in Y is allowed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
array_like
|
|
required |
X
|
array_like
|
|
required |
mask
|
array_like
|
|
None
|
per_trial
|
bool
|
Return the |
False
|
Returns:
| Type | Description |
|---|---|
float or ndarray
|
The log-likelihood. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
On a shape mismatch with the fit, or invalid data. |
NotFittedError
|
Before |
Examples:
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> model = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X)
>>> bool(abs(model.log_likelihood(sim.Y, sim.X) - model.log_likelihood_) < 1e-6)
True
score(Y, X, mask=None)
¶
Return the plug-in log-likelihood (M46) summed over trials.
The same number as log_likelihood,
for sklearn's convention (higher is better).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
array_like
|
|
required |
X
|
array_like
|
|
required |
mask
|
array_like
|
|
None
|
Returns:
| Type | Description |
|---|---|
float
|
The plug-in log-likelihood. |
Examples:
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> model = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X)
>>> model.score(sim.Y, sim.X) == model.log_likelihood(sim.Y, sim.X)
True
aic()
¶
Return aic_, 2 * n_parameters_ - 2 * log_likelihood_.
There is no data-taking form: an "AIC" from the plug-in likelihood and
the "mmle" count would not be an AIC.
Returns:
| Type | Description |
|---|---|
float
|
The training AIC ((M21b) for |
Examples:
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> model = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X)
>>> model.aic() == model.aic_
True
project(Y, regressor, mask=None, remove_intercept=True, weighted=True, method='gls', basis=None)
¶
project(Y: ArrayLike, regressor: str, mask: ArrayLike | None = ..., remove_intercept: bool = ..., weighted: bool = ..., method: Literal['gls', 'paper'] = ..., basis: Mapping[str, ArrayLike] | None = ...) -> FloatArray
project(Y: ArrayLike, regressor: None, mask: ArrayLike | None = ..., remove_intercept: bool = ..., weighted: bool = ..., method: Literal['gls', 'paper'] = ..., basis: Mapping[str, ArrayLike] | None = ...) -> dict[str, FloatArray]
Project activity onto regressor subspaces: trajectories.
method="gls" (default, (M49a)): per trial \(k\) and bin \(t\), the
weighted least-squares coordinates
\(z=(U^\top D_kU)^{-1}U^\top D_k(y-\hat b)\) over the neurons observed on
trial \(k\), \(U\) the basis (W_[regressor] in the model's frame, or
basis), \(D_k\) their precisions (identity with weighted=False).
method="paper": \(U^\top D(y-\hat b)\) (M49), without normalisation,
over the observed neurons
(Nature Neuroscience supplement, §7).
regressor=None solves jointly on the concatenated bases of every
regressor ("gls" only) and returns a dict.
A trial whose observed (weighted) basis lacks full column rank, at
tolerance \(\sqrt\epsilon\) relative to its largest singular value,
gets NaN coordinates and one
ProjectionWarning counts them
("gls" only, where the inverse is taken). A trial with no observed
neuron gives NaN without a warning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
array_like
|
|
required |
regressor
|
str or None
|
A regressor name, or |
required |
mask
|
array_like
|
|
None
|
remove_intercept
|
bool
|
Subtract |
True
|
weighted
|
bool
|
Weight neurons by |
True
|
method
|
('gls', 'paper')
|
See above. |
"gls"
|
basis
|
mapping of str to array_like
|
|
None
|
Returns:
| Type | Description |
|---|---|
numpy.ndarray or dict of str to numpy.ndarray
|
|
Raises:
| Type | Description |
|---|---|
ParameterError
|
For an unknown regressor, a rank-0 regressor without a |
SingularDesignError
|
For |
ValidationError
|
On a shape mismatch or invalid data. |
Warns:
| Type | Description |
|---|---|
ProjectionWarning
|
Once, with the number of trials whose basis was singular. |
Examples:
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=30, n_bins=6, n_trials=150, ranks=[2, 1], seed=0)
>>> model = MTDR(ranks=[2, 1], estimator="svd").fit(sim.Y, sim.X)
>>> model.project(sim.Y, "x0").shape
(150, 6, 2)
>>> {k: v.shape for k, v in model.project(sim.Y, None).items()}
{'x0': (150, 6, 2), 'x1': (150, 6, 1)}
decode(Y, regressor=None, mask=None, known=None, levels=None, bins=None, return_log_likelihood=False, return_llr=False)
¶
decode(Y: ArrayLike, regressor: str | Sequence[str] | None = ..., mask: ArrayLike | None = ..., known: Mapping[str, ArrayLike] | None = ..., levels: Mapping[str, Sequence[float]] | None = ..., bins: int | slice | Sequence[int] | None = ..., return_log_likelihood: Literal[False] = ..., return_llr: Literal[False] = ...) -> dict[str, FloatArray]
decode(Y: ArrayLike, regressor: str | Sequence[str] | None = ..., mask: ArrayLike | None = ..., known: Mapping[str, ArrayLike] | None = ..., levels: Mapping[str, Sequence[float]] | None = ..., bins: int | slice | Sequence[int] | None = ..., *, return_log_likelihood: Literal[True], return_llr: Literal[False] = ...) -> tuple[dict[str, FloatArray], FloatArray]
decode(Y: ArrayLike, regressor: str | Sequence[str] | None = ..., mask: ArrayLike | None = ..., known: Mapping[str, ArrayLike] | None = ..., levels: Mapping[str, Sequence[float]] | None = ..., bins: int | slice | Sequence[int] | None = ..., *, return_log_likelihood: Literal[False] = ..., return_llr: Literal[True]) -> tuple[dict[str, FloatArray], FloatArray]
decode(Y: ArrayLike, regressor: str | Sequence[str] | None = ..., mask: ArrayLike | None = ..., known: Mapping[str, ArrayLike] | None = ..., levels: Mapping[str, Sequence[float]] | None = ..., bins: int | slice | Sequence[int] | None = ..., *, return_log_likelihood: Literal[True], return_llr: Literal[True]) -> tuple[dict[str, FloatArray], FloatArray, FloatArray]
Model-based maximum-likelihood decoding.
Following the
Nature Neuroscience supplement, §6,
for each trial return the regressor values that maximise the plug-in
log-likelihood (M46) of its observed activity over the selected
bins, given B_, intercept_ and noise_precision_. Every
regressor (of positive rank) is either decoded or known. Continuous
unknowns are solved jointly in closed form, (M47), or (M47a) given the
known ones. Discrete unknowns (in levels) are decoded by the profile
likelihood (M48a): for every combination of their levels (in
itertools.product order over the decoded regressors, each in the
given level order; at most 64), the continuous unknowns are re-solved
and (M46) evaluated; the first maximising combination wins. With
one two-level discrete regressor [a, b], the log-likelihood ratio
\(\ell(b,\hat x_-\mid b)-\ell(a,\hat x_-\mid a)\) of (M48b) is available;
scipy.special.expit(llr) is the supplement's normalised profile
likelihood for level b. The decoder depends only on B_, so it is
frame-independent.
A trial whose continuous-unknown normal matrix
\(\Xi_\mathcal U^\top\Lambda\Xi_\mathcal U\) is singular or has a
condition number above \(\epsilon^{-1/2}\) gets NaN outputs, and one
DecodingWarning gives the count and
the bins. A trial with no observed neuron is NaN too.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
array_like
|
|
required |
regressor
|
str, sequence of str or None
|
The regressors to decode; |
None
|
mask
|
array_like
|
|
None
|
known
|
mapping of str to array_like
|
|
None
|
levels
|
mapping of str to sequence of float
|
Candidate values of decoded discrete regressors. |
None
|
bins
|
int, slice, sequence of int or None
|
The evidence window: one bin (the paper's instantaneous decoder), a
slice, a list, or |
None
|
return_log_likelihood
|
bool
|
Also return the maximised log-likelihood |
False
|
return_llr
|
bool
|
Also return the LLR |
False
|
Returns:
| Type | Description |
|---|---|
dict of str to numpy.ndarray, or tuple
|
|
Raises:
| Type | Description |
|---|---|
ParameterError
|
If a name is both decoded and known, a regressor is in neither,
|
ValidationError
|
On a shape mismatch or invalid data. |
Warns:
| Type | Description |
|---|---|
DecodingWarning
|
Once, when some trials' systems are singular. |
Examples:
>>> import numpy as np
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=40, n_bins=8, n_trials=300, ranks=[2, 1],
... levels=[[-1, 0, 1], [-1, 1]], seed=0)
>>> model = MTDR(ranks=[2, 1], estimator="svd").fit(sim.Y, sim.X,
... regressor_names=["s", "c"])
>>> out, llr = model.decode(sim.Y, ["s", "c"], levels={"c": [-1, 1]},
... return_llr=True)
>>> bool(np.mean(out["c"] == sim.X[:, 1]) > 0.9), llr.shape
(True, (300,))
explained_variance(Y, X, mask=None, per_bin=False)
¶
explained_variance(Y: ArrayLike, X: ArrayLike, mask: ArrayLike | None = ..., per_bin: Literal[False] = ...) -> dict[str, float]
explained_variance(Y: ArrayLike, X: ArrayLike, mask: ArrayLike | None = ..., *, per_bin: Literal[True]) -> dict[str, FloatArray]
Fraction of observed variance each term explains.
For each term, \(1-\lVert Y-\hat Y_p\rVert^2/\lVert Y-\bar Y\rVert^2\) over
the observed entries, with \(\bar Y_i\) neuron \(i\)'s mean over its
observed trials and all bins and \(\hat Y_p\) the prediction that
keeps only term \(p\): \(\bar Y+X_{:p}B_p\) for a regressor, intercept_
alone for "intercept" (present only when the model has one), and the
full prediction (M1) for "total". Terms are not orthogonal, so the
regressors' values need not add up to "total". On held-out trials
\(\bar Y_i\) is the held-out data's own mean, not the training one, so the
baseline is the best flat prediction of those trials and a held-out
"total" is not a training-mean comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Y
|
array_like
|
|
required |
X
|
array_like
|
|
required |
mask
|
array_like
|
|
None
|
per_bin
|
bool
|
Return |
False
|
Returns:
| Type | Description |
|---|---|
dict of str to float or numpy.ndarray
|
Keys: the regressor names, |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If an observed total variance it divides by is zero (naming the bins), on a shape mismatch, or for invalid data. |
Examples:
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> model = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X)
>>> ev = model.explained_variance(sim.Y, sim.X)
>>> sorted(ev), bool(0 < ev["total"] < 1)
(['intercept', 'total', 'x0'], True)
orthogonalize(order)
¶
Ordered Gram-Schmidt of the PC-oriented bases, for display.
Following the
Nature Neuroscience supplement, §4.2,
the PC bases \(U_p\) of B_ (docs/model.md § 10.1, computed whatever
frame the model holds) are concatenated in order and orthonormalised
by rank-revealing modified Gram-Schmidt, column by column with
re-orthogonalisation: the first regressor's basis is unchanged, and a
later column whose residual after removing every earlier direction has
norm at most \(\sqrt\epsilon\) (its norm before is 1) is dropped. So the
width of regressor \(p\) is \(0\le r^{\rm disp}_p\le r_p\), and a subspace
inside the earlier ones returns (n_neurons, 0). Not a model frame;
feed it to project(..., basis=...), never to subspace_angles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
sequence of str
|
Regressor names, the first kept intact; others are omitted and rank-0 ones skipped. |
required |
Returns:
| Type | Description |
|---|---|
dict of str to numpy.ndarray
|
|
Raises:
| Type | Description |
|---|---|
ParameterError
|
For an unknown or repeated name. |
Examples:
>>> import numpy as np
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=30, n_bins=6, n_trials=150, ranks=[2, 1], seed=0)
>>> model = MTDR(ranks=[2, 1], estimator="svd").fit(sim.Y, sim.X)
>>> Q = model.orthogonalize(["x1", "x0"])
>>> Q["x1"].shape, Q["x0"].shape
((30, 1), (30, 2))
>>> bool(np.allclose(Q["x1"].T @ Q["x0"], 0))
True
subspace_angles(a, b)
¶
Principal angles between the column spaces of W_[a] and W_[b].
scipy.linalg.subspace_angles on orthonormalised copies, so the result
does not depend on canonicalize; the cosines are the canonical
correlations of the
Nature Neuroscience supplement, §8.2
(docs/model.md § 9.3). Do not use the output of orthogonalize
here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
str
|
A regressor name. |
required |
b
|
str
|
Another (or the same) regressor name. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ParameterError
|
For an unknown name. |
Examples:
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=30, n_bins=6, n_trials=150, ranks=[2, 1], seed=0)
>>> model = MTDR(ranks=[2, 1], estimator="svd").fit(sim.Y, sim.X)
>>> model.subspace_angles("x0", "x1").shape
(1,)
>>> model.subspace_angles("x0", "x0").round(6)
array([0., 0.])
to_xarray()
¶
Return the fit as an xarray.Dataset (optional extra).
Dims regressor, neuron, time, component; variables B, W,
S (padded with NaN beyond each rank), rank, intercept (absent
without one) and noise_precision; attributes estimator, aic,
log_likelihood, n_parameters and mtdr_version. See
mtdr.xarray_io.to_dataset.
Returns:
| Type | Description |
|---|---|
Dataset
|
The dataset. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If xarray is not installed ( |
NotFittedError
|
Before |
Examples:
>>> from mtdr import MTDR, simulate
>>> sim = simulate(n_neurons=20, n_bins=6, n_trials=120, ranks=[1], seed=0)
>>> ds = MTDR(ranks=[1], estimator="svd").fit(sim.Y, sim.X).to_xarray()
>>> dict(ds.sizes)
{'regressor': 1, 'neuron': 20, 'time': 6, 'component': 1}
canonical_factors(B, rank=None)
¶
Factor a coefficient matrix in the paper's PC orientation.
The frame MTDR reports W_ and S_ in
(canonicalize=True; docs/model.md § 10.1;
Nature Neuroscience supplement, §4.1),
for any (n_neurons, n_bins) matrix: with the thin SVD
\(B=U\Sigma V^\top\) truncated to rank components,
the columns ordered by decreasing singular value, W orthonormal, and the
column norms of S the singular values. Each column's sign is fixed so
that the entry of W of largest absolute value is positive;
of entries exactly equal in absolute value the first (lowest neuron
index) decides, but entries equal in exact arithmetic usually differ at
rounding level in the computed SVD, so for such a column the sign is
arbitrary. Use it to put a known coefficient matrix, such as a
simulation's true B[p], into the frame of a fit before comparing time
components column by column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
B
|
array_like
|
|
required |
rank
|
int
|
Number of components, |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
W |
ndarray
|
|
S |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ParameterError
|
If |
Notes
Components whose singular values are equal, or nearly so, are determined
only up to a rotation within their block, not merely up to sign: compare
such components as a subspace (principal angles), not column by column.
The frame is a display convention; it is not a symmetry of the marginal
likelihood, so canonical factors are not inputs for
mtdr.mmle (docs/model.md § 10.1).
Examples:
>>> import numpy as np
>>> from mtdr import canonical_factors
>>> B = np.outer([1.0, -3.0, 2.0], [1.0, 0.5]) # rank 1
>>> W, S = canonical_factors(B)
>>> W.shape, S.shape
((3, 1), (2, 1))
>>> bool(W[1, 0] > 0), bool(np.allclose(W @ S.T, B))
(True, True)