HMM¶
Emission distributions and HiddenMarkovModel. Sequences is a list of arrays (one per hole) or one array with holes=; Rows is a list of arrays or one array, matching the input. See the guide.
Categorical
¶
Categorical emission over symbols 0..m-1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probabilities
|
array_like
|
Probability of each symbol, summing to 1. |
required |
pseudocount
|
float
|
Added to every symbol count in the M-step. |
0.0
|
frozen
|
bool
|
Keep the parameters fixed while fitting. |
False
|
Raises:
| Type | Description |
|---|---|
InvalidInput
|
When the probabilities are negative or do not sum to 1, or |
Examples:
>>> c = tg.Categorical([0.7, 0.2, 0.1])
>>> np.round(c.log_density([0, 2, -1]), 4)
array([-0.3567, -2.3026, 0. ])
>>> c.sample(5, seed=1).shape
(5,)
>>> tg.Categorical.from_json(c.to_json()) == c
True
Gaussian
¶
Gaussian emission.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
array_like
|
|
required |
covariance
|
array_like or float
|
|
required |
covariance_type
|
(full, diag, spherical)
|
|
"full"
|
frozen
|
bool
|
Keep the parameters fixed while fitting. |
False
|
Raises:
| Type | Description |
|---|---|
InvalidInput
|
When the covariance has the wrong shape for |
Examples:
>>> g = tg.Gaussian([0.0, 1.0], [1.0, 4.0], covariance_type="diag")
>>> np.round(g.log_density([[0.0, 1.0], [1.0, np.nan]]), 4)
array([-2.531 , -1.4189])
>>> g.sample(4, seed=1).shape
(4, 2)
>>> tg.Gaussian.from_json(g.to_json()) == g
True
Poisson
¶
Poisson emission with independent channels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rate
|
array_like
|
|
required |
frozen
|
bool
|
Keep the parameters fixed while fitting. |
False
|
Raises:
| Type | Description |
|---|---|
InvalidInput
|
When a rate is negative or not finite. |
Examples:
>>> p = tg.Poisson([2.0, 0.5])
>>> np.round(p.log_density([[2, 0], [0, 1]]), 4)
array([-1.8069, -3.1931])
>>> p.sample(3, seed=1).shape
(3, 2)
>>> tg.Poisson.from_json(p.to_json()) == p
True
GaussianMixture
¶
Mixture of Gaussians sharing one covariance type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
array_like
|
|
required |
means
|
array_like
|
|
required |
covariances
|
array_like
|
|
required |
covariance_type
|
(full, diag, spherical)
|
|
"full"
|
frozen
|
bool
|
Keep the parameters fixed while fitting. |
False
|
Raises:
| Type | Description |
|---|---|
InvalidInput
|
When the weights do not sum to 1, the shapes disagree or a covariance is not positive definite. |
Examples:
>>> m = tg.GaussianMixture([0.5, 0.5], [[0.0], [4.0]], [1.0, 1.0], covariance_type="spherical")
>>> np.round(m.log_density([0.0, 2.0]), 4)
array([-1.6118, -2.9189])
>>> m.sample(3, seed=1).shape
(3, 1)
>>> tg.GaussianMixture.from_json(m.to_json()) == m
True
HiddenMarkovModel
¶
Hidden Markov model of a geological state sequence observed through logs or assays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
distributions
|
int or sequence of distributions
|
The number of states, or one emission object per state ( |
required |
start
|
array_like
|
Start probabilities |
None
|
transition
|
array_like
|
Start probabilities |
None
|
emission
|
(gaussian, categorical, poisson, mixture)
|
Family fitted when |
"gaussian"
|
covariance_type
|
(full, diag, spherical)
|
|
"full"
|
n_symbols
|
int
|
Categorical symbols; the largest observed code plus 1 by default. |
None
|
n_mix
|
int
|
Components per state of a mixture. |
1
|
max_iter
|
int
|
Baum-Welch iterations, gain per observed step that stops it, seeded restarts. |
100
|
tol
|
float
|
Baum-Welch iterations, gain per observed step that stops it, seeded restarts. |
1e-06
|
n_init
|
int
|
Baum-Welch iterations, gain per observed step that stops it, seeded restarts. |
1
|
seed
|
int
|
Baum-Welch iterations, gain per observed step that stops it, seeded restarts. |
0
|
params
|
str
|
Letters of the parts fitted (s start, t transition, e emissions) and initialised; by
default |
'ste'
|
init_params
|
str
|
Letters of the parts fitted (s start, t transition, e emissions) and initialised; by
default |
None
|
start_prior
|
float
|
Dirichlet concentrations (>= 1) and the covariance shrinkage of the MAP M-step. |
1.0
|
transition_prior
|
float
|
Dirichlet concentrations (>= 1) and the covariance shrinkage of the MAP M-step. |
1.0
|
covariance_prior
|
float
|
Dirichlet concentrations (>= 1) and the covariance shrinkage of the MAP M-step. |
1e-06
|
pseudocount
|
float
|
Categorical emissions: added to symbol counts. |
0.0
|
direction
|
(up, down)
|
"up" runs each hole from its deepest row to its shallowest. |
"up"
|
implementation
|
(log, scaled)
|
Forward-backward arithmetic used while fitting. |
"log"
|
ordering
|
(none, mean, occupancy)
|
Relabel the fitted states by first-channel mean or by stationary occupancy. |
"none"
|
Raises:
| Type | Description |
|---|---|
InvalidInput
|
When an option is unknown, the given parts disagree in their number of states, or
|
Examples:
>>> truth = tg.HiddenMarkovModel(
... [tg.Gaussian([0.0], 1.0), tg.Gaussian([5.0], 1.0)],
... start=[0.5, 0.5], transition=[[0.9, 0.1], [0.1, 0.9]])
>>> states, logs = truth.sample([200, 200], seed=1)
>>> hmm = tg.HiddenMarkovModel(2, ordering="mean", seed=1).fit(logs)
>>> hmm.n_states, hmm.converged
(2, True)
>>> found = np.concatenate(hmm.predict(logs))
>>> bool(np.mean(found == np.concatenate(states)) > 0.95)
True
>>> hmm.predict_proba(logs)[0].shape
(200, 2)
>>> paths, log_p = hmm.viterbi(logs)
>>> len(paths), log_p.shape
(2, (2,))
>>> hmm.score_samples(logs).shape
(2,)
>>> bool(hmm.score(logs) < 0 and hmm.aic(logs) < hmm.bic(logs) <= hmm.icl(logs))
True
>>> hmm.sample_posterior(logs[0], n=3, seed=2).shape
(3, 200)
>>> tg.HiddenMarkovModel.from_json(hmm.to_json()) == hmm
True
start
property
¶
start: NDArray[float64]
(n_states,) initial state probabilities; InvalidInput before fitting.
transition
property
¶
transition: NDArray[float64]
(n_states, n_states) row-stochastic transition matrix; InvalidInput before fitting.
history
property
¶
history: NDArray[float64]
Objective (log-likelihood plus log prior) after each EM iteration.
fit
¶
fit(
sequences: Sequences,
*,
holes: ArrayLike | str | None = None,
labels: ArrayLike | str | None = None,
allowed: ArrayLike | None = None,
data: Mapping[str, ArrayLike] | None = None,
) -> HiddenMarkovModel
Baum-Welch (EM) fit over all holes, with seeded restarts.
Parameters¶
sequences : array_like, list of array_like or str
One array per hole (rows top-down, (t,) or (t, d)), or one array with
holes.
holes : array_like or str, optional
Per-row hole ids when sequences is one array.
labels : array_like or str, optional
Per-row known state, -1 where unknown (logged core intervals).
allowed : array_like, optional
(rows, K) booleans: the states each row may take.
data : mapping, optional
Strings above name its columns.
Returns¶
HiddenMarkovModel This model, fitted.
Raises¶
InvalidInput
When the sequences do not match the emissions or labels and allowed leave a
row no state.
ConvergenceError
When every restart degenerates.
score
¶
score(
sequences: Sequences,
*,
holes: ArrayLike | str | None = None,
data: Mapping[str, ArrayLike] | None = None,
) -> float
Total log-likelihood over holes (unclamped).
Parameters¶
sequences : array_like, list of array_like or str
One array per hole (rows top-down, (t,) or (t, d)), or one array with holes.
holes : array_like or str, optional
Per-row hole ids when sequences is one array.
data : mapping, optional
Strings above name its columns.
Returns¶
float
Raises¶
InvalidInput When the model is not fitted, or the sequences do not match its emissions.
score_samples
¶
score_samples(
sequences: Sequences,
*,
holes: ArrayLike | str | None = None,
data: Mapping[str, ArrayLike] | None = None,
) -> NDArray[np.float64]
Log-likelihood of each hole (unclamped).
Parameters¶
sequences : array_like, list of array_like or str
One array per hole (rows top-down, (t,) or (t, d)), or one array with holes.
holes : array_like or str, optional
Per-row hole ids when sequences is one array.
data : mapping, optional
Strings above name its columns.
Returns¶
numpy.ndarray
(n_holes,).
Raises¶
InvalidInput When the model is not fitted, or the sequences do not match its emissions.
predict
¶
predict(
sequences: Sequences,
*,
holes: ArrayLike | str | None = None,
labels: ArrayLike | str | None = None,
allowed: ArrayLike | None = None,
data: Mapping[str, ArrayLike] | None = None,
algorithm: Literal[
"viterbi", "map", "posterior_viterbi"
] = "viterbi",
) -> Rows
Most likely states per row.
Parameters¶
sequences : array_like, list of array_like or str
One array per hole (rows top-down, (t,) or (t, d)), or one array with holes.
holes : array_like or str, optional
Per-row hole ids when sequences is one array.
labels : array_like or str, optional
Per-row known state, -1 where unknown.
allowed : array_like, optional
(rows, K) booleans: the states each row may take.
data : mapping, optional
Strings above name its columns.
algorithm : {"viterbi", "map", "posterior_viterbi"}
Best joint path, per-row posterior argmax, or the best path through rows with
non-zero posterior.
Returns¶
numpy.ndarray or list of numpy.ndarray int64 states in input row order.
Raises¶
InvalidInput
When the model is not fitted, or the sequences do not match its emissions. Also when algorithm is unknown.
predict_proba
¶
predict_proba(
sequences: Sequences,
*,
holes: ArrayLike | str | None = None,
labels: ArrayLike | str | None = None,
allowed: ArrayLike | None = None,
data: Mapping[str, ArrayLike] | None = None,
) -> Rows
Posterior state probabilities per row.
Parameters¶
sequences : array_like, list of array_like or str
One array per hole (rows top-down, (t,) or (t, d)), or one array with holes.
holes : array_like or str, optional
Per-row hole ids when sequences is one array.
labels : array_like or str, optional
Per-row known state, -1 where unknown.
allowed : array_like, optional
(rows, K) booleans: the states each row may take.
data : mapping, optional
Strings above name its columns.
Returns¶
numpy.ndarray or list of numpy.ndarray
(rows, K), rows summing to 1.
Raises¶
InvalidInput When the model is not fitted, or the sequences do not match its emissions.
viterbi
¶
viterbi(
sequences: Sequences,
*,
holes: ArrayLike | str | None = None,
labels: ArrayLike | str | None = None,
allowed: ArrayLike | None = None,
data: Mapping[str, ArrayLike] | None = None,
) -> tuple[Rows, NDArray[np.float64]]
Viterbi path per row and its log-probability per hole.
Parameters¶
sequences : array_like, list of array_like or str
One array per hole (rows top-down, (t,) or (t, d)), or one array with holes.
holes : array_like or str, optional
Per-row hole ids when sequences is one array.
labels : array_like or str, optional
Per-row known state, -1 where unknown.
allowed : array_like, optional
(rows, K) booleans: the states each row may take.
data : mapping, optional
Strings above name its columns.
Returns¶
paths : numpy.ndarray or list of numpy.ndarray
int64 states in input row order.
log_probability : numpy.ndarray
(n_holes,).
Raises¶
InvalidInput When the model is not fitted, or the sequences do not match its emissions.
sample
¶
sample(
lengths: int | Sequence[int], *, seed: int = 0
) -> tuple[list[NDArray[np.int64]], list[NDArray]]
Seeded state paths and observations, one per length, rows top-down.
Parameters¶
lengths : sequence of int
Rows of each sampled hole.
seed : int
Seed in 0..2**64-1.
Returns¶
tuple of (list of numpy.ndarray, list of numpy.ndarray)
States (int64) and observations ((t, d); int64 (t,) codes when categorical).
Raises¶
InvalidInput
When the model is not fitted or seed is out of range.
sample_posterior
¶
sample_posterior(
sequences: Sequences,
*,
n: int = 100,
seed: int = 0,
holes: ArrayLike | str | None = None,
labels: ArrayLike | str | None = None,
allowed: ArrayLike | None = None,
data: Mapping[str, ArrayLike] | None = None,
) -> NDArray[np.int64]
Seeded state paths drawn from the posterior.
Parameters¶
sequences : array_like, list of array_like or str
One array per hole (rows top-down, (t,) or (t, d)), or one array with holes.
n : int
Number of paths.
seed : int
Seed in 0..2**64-1.
holes : array_like or str, optional
Per-row hole ids when sequences is one array.
labels : array_like or str, optional
Per-row known state, -1 where unknown.
allowed : array_like, optional
(rows, K) booleans: the states each row may take.
data : mapping, optional
Strings above name its columns.
Returns¶
numpy.ndarray
int64 (n, rows).
Raises¶
InvalidInput
When the model is not fitted, or the sequences do not match its emissions. Also when seed is out of range.
aic
¶
aic(
sequences: Sequences,
*,
holes: ArrayLike | str | None = None,
data: Mapping[str, ArrayLike] | None = None,
) -> float
Akaike information criterion (lower is better).
Parameters¶
sequences : array_like, list of array_like or str
One array per hole (rows top-down, (t,) or (t, d)), or one array with holes.
holes : array_like or str, optional
Per-row hole ids when sequences is one array.
data : mapping, optional
Strings above name its columns.
Returns¶
float
Raises¶
InvalidInput When the model is not fitted, or the sequences do not match its emissions.
bic
¶
bic(
sequences: Sequences,
*,
holes: ArrayLike | str | None = None,
data: Mapping[str, ArrayLike] | None = None,
) -> float
Bayesian information criterion (lower is better).
Depth samples are autocorrelated, so BIC tends to favour too many states on dense logs.
Parameters¶
sequences : array_like, list of array_like or str
One array per hole (rows top-down, (t,) or (t, d)), or one array with holes.
holes : array_like or str, optional
Per-row hole ids when sequences is one array.
data : mapping, optional
Strings above name its columns.
Returns¶
float
Raises¶
InvalidInput When the model is not fitted, or the sequences do not match its emissions.
icl
¶
icl(
sequences: Sequences,
*,
holes: ArrayLike | str | None = None,
data: Mapping[str, ArrayLike] | None = None,
) -> float
Integrated completed likelihood: BIC plus twice the path entropy (lower is better).
Parameters¶
sequences : array_like, list of array_like or str
One array per hole (rows top-down, (t,) or (t, d)), or one array with holes.
holes : array_like or str, optional
Per-row hole ids when sequences is one array.
data : mapping, optional
Strings above name its columns.
Returns¶
float
Raises¶
InvalidInput When the model is not fitted, or the sequences do not match its emissions.
to_json
¶
to_json() -> str