NaiveSubsequenceSearch¶
- class NaiveSubsequenceSearch(length: int, normalize: bool | None = False, distance: str | Callable = 'squared', distance_params: dict | None = None, n_jobs: int | None = 1)[source]¶
Bases:
BaseDistanceProfileSearchNaive subsequence nearest neighbor search.
This estimator searches for the k nearest neighbor subsequences across a collection of time series using exhaustive pairwise distance computation. Given a query subsequence, it computes distance profiles against all series in the fitted collection and returns the best matches with their
(case_index, timestamp)locations.- Parameters:
- lengthint
The length of the subsequences to use for the search. The query provided to
predictmust have exactly this many timepoints.- normalizebool, default=False
Whether the subsequences should be z-normalized before distance computation. This results in scale-independent matching.
- distancestr or callable, default=”squared”
Distance measure between subsequences. A list of valid strings can be found in the documentation for
aeon.distances.get_distance_functionor through callingaeon.distances.get_distance_function_names. If a callable is passed it must be a function that takes two 2d numpy arrays of shape(n_channels, length)as input and returns a float.- distance_paramsdict, default=None
Dictionary of distance parameters for the case that
distanceis a str.- n_jobsint, default=1
Number of parallel threads to use for distance computation.
- Attributes:
- X_np.ndarray of shape (n_cases, n_channels, n_timepoints)
The fitted collection of time series.
- X_subs_np.ndarray of shape (n_cases, n_candidates, n_channels, length)
Precomputed subsequences for each series in the collection, where
n_candidatesequalsn_timepoints - length + 1.- n_cases_int
Number of time series in the fitted collection.
- n_channels_int
Number of channels in the fitted time series.
- n_timepoints_int
Number of timepoints in each fitted time series.
Notes
Capabilities ¶ Missing Values
No
Multithreading
Yes
Univariate
Yes
Multivariate
Yes
Unequal Length
No
Examples
>>> import numpy as np >>> from aeon.similarity_search.subsequence import NaiveSubsequenceSearch >>> X_fit = np.random.rand(5, 1, 100) >>> query = np.random.rand(1, 20) >>> searcher = NaiveSubsequenceSearch(length=20, normalize=False) >>> searcher.fit(X_fit) NaiveSubsequenceSearch(length=20) >>> indexes, distances = searcher.predict(query, k=3)
Methods
clone([random_state])Obtain a clone of the object with the same hyperparameters.
Compute the distance profile of X to all subsequences in X_.
fit(X[, y])Fit estimator to X.
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.
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[, k, axis])Find the k nearest neighbors to X in the fitted collection.
reset([keep])Reset the object to a clean post-init state.
set_params(**params)Set the parameters of this estimator.
set_predict_request(*[, axis, k])Configure whether metadata should be requested to be passed to the
predictmethod.set_tags(**tag_dict)Set dynamic tags to given values.
- 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.cloneofself. 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. Ifint,random_stateis the seed used by the random number generator. IfRandomStateinstance,random_stateis the random number generator.
- Returns:
- estimatorobject
Instance of
type(self), clone of self (see above)
- compute_distance_profile(X: ndarray)[source]¶
Compute the distance profile of X to all subsequences in X_.
- Parameters:
- Xnp.ndarray, 2D array of shape (n_channels, length)
The query to use to compute the distance profiles.
- Returns:
- distance_profilesnp.ndarray, 2D array of shape (n_cases, n_candidates)
The distance profile of X to all subsequences in all series of X_. The
n_candidatesvalue is equal ton_timepoints - length + 1.
- fit(X: ndarray, y=None)[source]¶
Fit estimator to X.
- Parameters:
- Xnp.ndarray shape (n_cases, n_channels, n_timepoints)
Input data to store and use as database against the query given when calling predict.
- y: ignored, exists for API consistency reasons.
- Returns:
- selfa fitted instance of the 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
ValueErroris 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_nametag in cls. If not found, returns an error ifraise_errorisTrue, otherwise it returnstag_value_default.
- Raises:
- ValueError
if
raise_errorisTrueandtag_nameis 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
_tagsclass attribute via nested inheritance. These are not overridden by dynamic tags set byset_tagsor 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)¶
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
ValueErroris 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_nametag in self. If not found, returns an error ifraise_errorisTrue, otherwise it returnstag_value_default.
- Raises:
- ValueError
if raise_error is
Trueandtag_nameis 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
_tagsclass attribute via nested inheritance and then any overridden and new tags from__init__orset_tags.
- predict(X: ndarray, k: int = 1, axis: int = 1, **kwargs)[source]¶
Find the k nearest neighbors to X in the fitted collection.
Returns the indexes and distances of the best matches to X. It is possible that fewer than k indexes are returned if fewer than k admissible matches exist.
- Parameters:
- Xnp.ndarray, 2D array of shape (n_channels, n_timepoints)
Query series for which to find the nearest neighbors in the database. For subsequence search,
n_timepointsshould equal thelengthparameter. For whole series search,n_timepointsshould match the series length in the fitted collection.- kint or np.inf, default=1
Number of best matches to return. Must be a positive integer, or the sentinel
np.infto return all matches (supported by whole series estimators).- axisint, default=1
The time point axis of the input series if it is 2D. If
axis==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==1indicates the time series are in rows, i.e. the shape of the data is(n_channels, n_timepoints).- **kwargsdict, optional
Additional search options passed to the estimator’s
_predictmethod. The accepted options (e.g.dist_threshold,inverse_distance,X_index,allow_trivial_matches,exclusion_factor) and their defaults differ per estimator; see the docstring of each concrete estimator for the options it supports.
- Returns:
- indexesnp.ndarray
Indexes of the best matches. The shape and meaning depend on the search type:
Subsequence search: shape
(n_matches, 2)with(i_case, i_timestamp)pairs indicating which series and at what position the match was found.Whole series search: shape
(n_matches,)with case indices indicating which series in the fitted collection are nearest neighbors.
- distancesnp.ndarray, shape (n_matches,)
Distances of the matches to the query. Lower values indicate better matches (unless
inverse_distance=Trueis used).
- reset(keep=None)[source]¶
Reset the object to a clean post-init state.
After a
self.reset()call,selfis 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
keepargument
- Parameters:
- keepNone, str, or list of str, default=None
If
None, all attributes are removed except hyperparameters. Ifstr, only the attribute with this name is kept. Iflistofstr, only the attributes with these names are kept.
- Returns:
- selfobject
Reference to self.
- Raises:
- TypeError
If ‘keep’ is not a string or a list of strings.
- set_params(**params)¶
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_predict_request(*, axis: bool | None | str = '$UNCHANGED$', k: bool | None | str = '$UNCHANGED$') NaiveSubsequenceSearch¶
Configure whether metadata should be requested to be passed to the
predictmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed topredictif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topredict.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.
- Parameters:
- axisstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
axisparameter inpredict.- kstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
kparameter inpredict.
- Returns:
- selfobject
The updated object.