HMMSegmenter¶
- class HMMSegmenter(emission_funcs: list, transition_prob_mat: ndarray, initial_probs: ndarray | None = None)[source]¶
Implements a simple HMM fitted with Viterbi algorithm.
The HMM annotation estimator uses the the Viterbi algorithm to fit a sequence of ‘hidden state’ class annotations (represented by an array of integers the same size as the observation) to a sequence of observations.
This is done by finding the most likely path given the emission probabilities - (ie the probability that a particular observation would be generated by a given hidden state), the transition prob (ie the probability of transitioning from one state to another or staying in the same state) and the initial probabilities - ie the belief of the probability distribution of hidden states at the start of the observation sequence).
- Current assumptions/limitations of this implementation:
the spacing of time series points is assumed to be equivalent.
it only works on univariate data.
- the emission parameters and transition probabilities are
assumed to be known.
- if no initial probs are passed, uniform probabilities are
assigned (ie rather than the stationary distribution.)
requires and returns np.ndarrays.
_fit is currently empty as the parameters of the probability distribution are required to be passed to the algorithm.
_predict - first the transition_probability and transition_id matrices are calculated - these are both nxm matrices, where n is the number of hidden states and m is the number of observations. The transition probability matrices record the probability of the most likely sequence which has observation m being assigned to hidden state n. The transition_id matrix records the step before hidden state n that proceeds it in the most likely path. This logic is mostly carried out by helper function _calculate_trans_mats. Next, these matrices are used to calculate the most likely path (by backtracing from the final mostly likely state and the id’s that proceeded it.) This logic is done via a helper func hmm_viterbi_label.
- Parameters:
- emission_funcslist, shape = [num hidden states]
List should be of length n (the number of hidden states) Either a list of callables [fx_1, fx_2] with signature fx_1(X) -> float or a list of callables and matched keyword arguments for those callables [(fx_1, kwarg_1), (fx_2, kwarg_2)] with signature fx_1(X, **kwargs) -> float (or a list with some mixture of the two). The callables should take a value and return a probability when passed a single observation. All functions should be properly normalized PDFs over the same space as the observed data.
- transition_prob_mat: 2D np.ndarry, shape = [num_states, num_states]
Each row should sum to 1 in order to be properly normalized (ie the j’th column in the i’th row represents the probability of transitioning from state i to state j.)
- initial_probs: 1D np.ndarray, shape = [num hidden states], optional
A array of probabilities that the sequence of hidden states starts in each of the hidden states. If passed, should be of length n the number of hidden states and should match the length of both the emission funcs list and the transition_prob_mat. The initial probs should be reflective of prior beliefs. If none is passed will each hidden state will be assigned an equal inital prob.
- Attributes:
- emission_funcslist, shape = [num_hidden_states]
The functions to use in calculating the emission probabilities. Taken from the __init__ param of same name.
- transition_prob_mat: 2D np.ndarry, shape = [num_states, num_states]
Matrix of transition probabilities from hidden state to hidden state. Taken from the __init__ param of same name.
- initial_probs1D np.ndarray, shape = [num_hidden_states]
Probability over the hidden state identity of the first state. If the __init__ param of same name was passed it will take on that value. Otherwise it is set to be uniform over all hidden states.
- num_statesint
The number of hidden states. Set to be the length of the emission_funcs parameter which was passed.
- stateslist
A list of integers from 0 to num_states-1. Integer labels for the hidden states.
- num_obsint
The length of the observations data. Extracted from data.
- trans_prob2D np.ndarray, shape = [num_observations, num_hidden_states]
Shape [num observations, num hidden states]. The max probability that that observation is assigned to that hidden state. Calculated in _calculate_trans_mat and assigned in _predict.
- trans_id2D np.ndarray, shape = [num_observations, num_hidden_states]
Shape [num observations, num hidden states]. The state id of the state proceeding the observation is assigned to that hidden state in the most likely path where that occurs. Calculated in _calculate_trans_mat and assigned in _predict.
Examples
>>> from aeon.segmentation import HMMSegmenter >>> from scipy.stats import norm >>> from numpy import asarray >>> # define the emission probs for our HMM model: >>> centers = [3.5,-5] >>> sd = [.25 for i in centers] >>> emi_funcs = [(norm.pdf, {'loc': mean, ... 'scale': sd[ind]}) for ind, mean in enumerate(centers)] >>> hmm = HMMSegmenter(emi_funcs, asarray([[0.25,0.75], [0.666, 0.333]])) >>> # generate synthetic data (or of course use your own!) >>> obs = asarray([3.7,3.2,3.4,3.6,-5.1,-5.2,-4.9]) >>> hmm.fit_predict(obs) array([0., 0., 0., 0., 1., 1., 1.])
Methods
clone
([random_state])Obtain a clone of the object with the same hyperparameters.
fit
(X[, y, axis])Fit time series segmenter to X.
fit_predict
(X[, y, axis])Fit segmentation to data and return it.
get_class_tag
(tag_name[, raise_error, ...])Get tag value from estimator class (only class tags).
Get class tags from estimator class and all its parent classes.
get_fitted_params
([deep])Get fitted parameters.
Sklearn metadata routing.
get_params
([deep])Get parameters for this estimator.
get_tag
(tag_name[, raise_error, ...])Get tag value from estimator class.
get_tags
()Get tags from estimator.
predict
(X[, axis])Create amd return segmentation of X.
reset
([keep])Reset the object to a clean post-init state.
set_params
(**params)Set the parameters of this estimator.
set_tags
(**tag_dict)Set dynamic tags to given values.
to_classification
(change_points, length)Convert change point locations to a classification vector.
to_clusters
(change_points, length)Convert change point locations to a clustering vector.
- clone(random_state=None)[source]¶
Obtain a clone of the object with the same hyperparameters.
A clone is a different object without shared references, in post-init state. This function is equivalent to returning
sklearn.clone
of self. Equal in value totype(self)(**self.get_params(deep=False))
.- Parameters:
- random_stateint, RandomState instance, or None, default=None
Sets the random state of the clone. If None, the random state is not set. If int, random_state is the seed used by the random number generator. If RandomState instance, random_state is the random number generator.
- Returns:
- estimatorobject
Instance of
type(self)
, clone of self (see above)
- fit(X, y=None, axis=1)[source]¶
Fit time series segmenter to X.
If the tag
fit_is_empty
is true, this just sets theis_fitted
tag to true. Otherwise, it checksself
can handleX
, formatsX
into the structure required byself
then passesX
(and possiblyy
) to_fit
.- Parameters:
- XOne of
VALID_SERIES_INPUT_TYPES
Input time series to fit a segmenter.
- yOne of
VALID_SERIES_INPUT_TYPES
or None, default None Training time series, a labeled 1D series same length as X for supervised segmentation.
- axisint, default = None
Axis along which to segment if passed a multivariate X series (2D input). If axis is 0, it is assumed each column is a time series and each row is a time point. i.e. the shape of the data is
(n_timepoints, n_channels)
.axis == 1
indicates the time series are in rows, i.e. the shape of the data is(n_channels, n_timepoints)`.``axis is None
indicates that the axis of X is the same asself.axis
.
- XOne of
- Returns:
- self
Fitted estimator
- classmethod get_class_tag(tag_name, raise_error=True, tag_value_default=None)[source]¶
Get tag value from estimator class (only class tags).
- Parameters:
- tag_namestr
Name of tag value.
- raise_errorbool, default=True
Whether a ValueError is raised when the tag is not found.
- tag_value_defaultany type, default=None
Default/fallback value if tag is not found and error is not raised.
- Returns:
- tag_value
Value of the
tag_name
tag in cls. If not found, returns an error ifraise_error
is True, otherwise it returnstag_value_default
.
- Raises:
- ValueError
if
raise_error
is True andtag_name
is not inself.get_tags().keys()
Examples
>>> from aeon.classification import DummyClassifier >>> DummyClassifier.get_class_tag("capability:multivariate") True
- classmethod get_class_tags()[source]¶
Get class tags from estimator class and all its parent classes.
- Returns:
- collected_tagsdict
Dictionary of tag name and tag value pairs. Collected from
_tags
class attribute via nested inheritance. These are not overridden by dynamic tags set byset_tags
or class__init__
calls.
- get_fitted_params(deep=True)[source]¶
Get fitted parameters.
- State required:
Requires state to be “fitted”.
- Parameters:
- deepbool, default=True
If True, will return the fitted parameters for this estimator and contained subobjects that are estimators.
- Returns:
- fitted_paramsdict
Fitted parameter names mapped to their values.
- get_params(deep=True)[source]¶
Get parameters for this estimator.
- Parameters:
- deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns:
- paramsdict
Parameter names mapped to their values.
- get_tag(tag_name, raise_error=True, tag_value_default=None)[source]¶
Get tag value from estimator class.
Includes dynamic and overridden tags.
- Parameters:
- tag_namestr
Name of tag to be retrieved.
- raise_errorbool, default=True
Whether a ValueError is raised when the tag is not found.
- tag_value_defaultany type, default=None
Default/fallback value if tag is not found and error is not raised.
- Returns:
- tag_value
Value of the
tag_name
tag in self. If not found, returns an error ifraise_error
is True, otherwise it returnstag_value_default
.
- Raises:
- ValueError
if raise_error is
True
andtag_name
is not inself.get_tags().keys()
Examples
>>> from aeon.classification import DummyClassifier >>> d = DummyClassifier() >>> d.get_tag("capability:multivariate") True
- get_tags()[source]¶
Get tags from estimator.
Includes dynamic and overridden tags.
- Returns:
- collected_tagsdict
Dictionary of tag name and tag value pairs. Collected from
_tags
class attribute via nested inheritance and then any overridden and new tags from__init__
orset_tags
.
- predict(X, axis=1)[source]¶
Create amd return segmentation of X.
- Parameters:
- XOne of
VALID_SERIES_INPUT_TYPES
Input time series
- axisint, default = None
Axis along which to segment if passed a multivariate series (2D input) with
n_channels
time series. If axis is 0, it is assumed each row is a time series and each column is a time point. i.e. the shape of the data is(n_timepoints,n_channels)
.axis == 1
indicates the time series are in rows, i.e. the shape of the data is(n_channels, n_timepoints)`.``axis is None
indicates that the axis of X is the same asself.axis
.
- XOne of
- Returns:
- List
Either a list of indexes of X indicating where each segment begins or a list of integers of
len(X)
indicating which segment each time point belongs to.
- reset(keep=None)[source]¶
Reset the object to a clean post-init state.
After a
self.reset()
call, self is equal or similar in value totype(self)(**self.get_params(deep=False))
, assuming no other attributes were kept usingkeep
.- Detailed behaviour:
- removes any object attributes, except:
hyper-parameters (arguments of
__init__
) object attributes containing double-underscores, i.e., the string “__”
runs
__init__
with current values of hyperparameters (result ofget_params
)- Not affected by the reset are:
object attributes containing double-underscores class and object methods, class attributes any attributes specified in the
keep
argument
- Parameters:
- keepNone, str, or list of str, default=None
If None, all attributes are removed except hyperparameters. If str, only the attribute with this name is kept. If list of str, only the attributes with these names are kept.
- Returns:
- selfobject
Reference to self.
- set_params(**params)[source]¶
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline
). The latter have parameters of the form<component>__<parameter>
so that it’s possible to update each component of a nested object.- Parameters:
- **paramsdict
Estimator parameters.
- Returns:
- selfestimator instance
Estimator instance.
- set_tags(**tag_dict)[source]¶
Set dynamic tags to given values.
- Parameters:
- **tag_dictdict
Dictionary of tag name and tag value pairs.
- Returns:
- selfobject
Reference to self.
- classmethod to_classification(change_points: list[int], length: int)[source]¶
Convert change point locations to a classification vector.
Change point detection results can be treated as classification with true change point locations marked with 1’s at position of the change point and remaining non-change point locations being 0’s.
For example change points [2, 8] for a time series of length 10 would result in: [0, 0, 1, 0, 0, 0, 0, 0, 1, 0].
- classmethod to_clusters(change_points: list[int], length: int)[source]¶
Convert change point locations to a clustering vector.
Change point detection results can be treated as clustering with each segment separated by change points assigned a distinct dummy label.
For example change points [2, 8] for a time series of length 10 would result in: [0, 0, 1, 1, 1, 1, 1, 1, 2, 2].