### Import Standard Datasets with tslearn Source: https://tslearn.readthedocs.io/en/stable/gettingstarted.html Illustrates how to load standard time series datasets like 'TwoPatterns' using the `UCR_UEA_datasets` class from `tslearn.datasets`. It returns training and testing sets for both data (X) and labels (y). ```python from tslearn.datasets import UCR_UEA_datasets X_train, y_train, X_test, y_test = UCR_UEA_datasets().load_dataset("TwoPatterns") print(X_train.shape) print(y_train.shape) ``` -------------------------------- ### MatrixProfile Initialization and Transformation Example Source: https://tslearn.readthedocs.io/en/stable/gen_modules/matrix_profile/tslearn.matrix_profile.MatrixProfile.html Demonstrates how to initialize the MatrixProfile class with custom parameters and then use it to transform a time series dataset. The example shows setting subsequence_length and scale, and then applying fit_transform. ```python >>> time_series = [0., 1., 3., 2., 9., 1., 14., 15., 1., 2., 2., 10., 7.] >>> ds = [time_series] >>> mp = MatrixProfile(subsequence_length=4, scale=False) >>> mp.fit_transform(ds)[0, :, 0] array([ 6.85..., 1.41..., 6.16..., 7.93..., 11.40..., 13.56..., 18. ..., 13.96..., 1.41..., 6.16...]) ``` -------------------------------- ### Load and Save Time Series from Text Files with tslearn Source: https://tslearn.readthedocs.io/en/stable/gettingstarted.html Provides examples for loading and saving time series data from text files using `load_time_series_txt` and `save_time_series_txt` from `tslearn.utils`. The text file format expects one time series per line, with modalities separated by '|' and observations by spaces. ```python from tslearn.utils import save_time_series_txt, load_time_series_txt time_series_dataset = load_time_series_txt("path/to/your/file.txt") save_time_series_txt("path/to/another/file.txt", dataset_to_be_saved) ``` -------------------------------- ### Setup for Early Classification Example (Python) Source: https://tslearn.readthedocs.io/en/stable/auto_examples/classification/plot_early_classification.html Sets up the necessary imports and a helper function for plotting partial time series in the early classification example. It imports numpy, matplotlib, TimeSeriesScalerMeanVariance, NonMyopicEarlyClassifier, and UCR_UEA_datasets. ```python # Author: Romain Tavenard # License: BSD 3 clause # sphinx_gallery_thumbnail_number = 2 import numpy import matplotlib.pyplot as plt from tslearn.preprocessing import TimeSeriesScalerMeanVariance from tslearn.early_classification import NonMyopicEarlyClassifier from tslearn.datasets import UCR_UEA_datasets def plot_partial(time_series, t, y_true=0, y_pred=0, color="k"): plt.plot(time_series[:t+1].ravel(), color=color, linewidth=1.5) plt.plot(numpy.arange(t+1, time_series.shape[0]), time_series[t+1:].ravel(), linestyle="dashed", color=color, linewidth=1.5) plt.axvline(x=t, color=color, linewidth=1.5) plt.text(x=t - 20, y=time_series.max() - .25, s="Prediction time") plt.title( "Sample of class {} predicted as class {}".format(y_true, y_pred) ) plt.xlim(0, time_series.shape[0] - 1) ``` -------------------------------- ### Cluster Time Series Data with tslearn Source: https://tslearn.readthedocs.io/en/stable/gettingstarted.html Demonstrates how to initialize and fit a `TimeSeriesKMeans` model from `tslearn.clustering` to a time series dataset. The model supports various distance metrics, such as 'dtw' (Dynamic Time Warping). ```python from tslearn.clustering import TimeSeriesKMeans km = TimeSeriesKMeans(n_clusters=3, metric="dtw") km.fit(X_train) ``` -------------------------------- ### KShape Clustering Example Source: https://tslearn.readthedocs.io/en/stable/gen_modules/clustering/tslearn.clustering.KShape.html Example demonstrating the usage of KShape for time series clustering. It involves generating random walks, scaling the data, and then fitting the KShape model to obtain cluster centers. Requires tslearn.generators and TimeSeriesScalerMeanVariance. ```python from tslearn.generators import random_walks X = random_walks(n_ts=50, sz=32, d=1) X = TimeSeriesScalerMeanVariance(mu=0., std=1.).fit_transform(X) ks = KShape(n_clusters=3, n_init=1, random_state=0).fit(X) ks.cluster_centers_.shape ``` -------------------------------- ### KShape Model Persistence Example Source: https://tslearn.readthedocs.io/en/stable/auto_examples/misc/plot_serialize_models.html An example demonstrating the persistence of a KShape model. It includes data loading, preprocessing, model training, saving to HDF5, loading the model from HDF5, and using the loaded model for predictions and visualization. ```python # Example using KShape import os import tempfile import numpy import matplotlib.pyplot as plt from tslearn.clustering import KShape from tslearn.datasets import CachedDatasets from tslearn.preprocessing import TimeSeriesScalerMeanVariance seed = 0 numpy.random.seed(seed) X_train, y_train, X_test, y_test = CachedDatasets().load_dataset("Trace") # Keep first 3 classes and 50 first time series X_train = X_train[y_train < 4] X_train = X_train[:50] numpy.random.shuffle(X_train) # For this method to operate properly, prior scaling is required X_train = TimeSeriesScalerMeanVariance().fit_transform(X_train) sz = X_train.shape[1] # Instantiate k-Shape model init=numpy.array([X_train[44], X_train[47], X_train[0]]) ks = KShape(n_clusters=3, verbose=True, init=init) # Train ks.fit(X_train) with tempfile.TemporaryDirectory() as tmpdir: # Save model filename = os.path.join(tmpdir, "ks_trained.hdf5") if not os.path.isfile(filename): ks.to_hdf5(filename) # Load model trained_ks = KShape.from_hdf5(filename) # Use loaded model to make predictions y_pred = trained_ks.predict(X_train) plt.figure() for yi in range(3): plt.subplot(3, 1, 1 + yi) for xx in X_train[y_pred == yi]: plt.plot(xx.ravel(), "k-", alpha=.2) plt.plot(ks.cluster_centers_[yi].ravel(), "r-") plt.xlim(0, sz) plt.ylim(-4, 4) plt.title("Cluster %d" % (yi + 1)) plt.tight_layout() plt.show() ``` -------------------------------- ### SoftDTWLossPyTorch Example in Python Source: https://tslearn.readthedocs.io/en/stable/gen_modules/metrics/tslearn.metrics.SoftDTWLossPyTorch.html Demonstrates the usage of SoftDTWLossPyTorch for calculating the Soft-DTW loss between two PyTorch tensors. It shows how to initialize the loss function, compute the loss, and backpropagate to get gradients. ```python import torch from tslearn.metrics import SoftDTWLossPyTorch soft_dtw_loss = SoftDTWLossPyTorch(gamma=0.1) x = torch.zeros((4, 3, 2), requires_grad=True) y = torch.arange(0, 24).reshape(4, 3, 2) soft_dtw_loss_mean_value = soft_dtw_loss(x, y).mean() print(soft_dtw_loss_mean_value) soft_dtw_loss_mean_value.backward() print(x.grad.shape) print(x.grad) ``` -------------------------------- ### Listing Available Datasets Source: https://tslearn.readthedocs.io/en/stable/gen_modules/datasets/tslearn.datasets.UCR_UEA_datasets.html Examples of how to retrieve lists of all, univariate, or multivariate datasets available in the archive. ```python from tslearn.datasets import UCR_UEA_datasets loader = UCR_UEA_datasets() # List all datasets all_ds = loader.list_datasets() # List only multivariate datasets multi_ds = loader.list_multivariate_datasets() # List only univariate datasets uni_ds = loader.list_univariate_datasets() ``` -------------------------------- ### Initialize and use TimeSeriesSVR Source: https://tslearn.readthedocs.io/en/stable/gen_modules/svm/tslearn.svm.TimeSeriesSVR.html This example demonstrates how to generate synthetic time-series data, initialize the TimeSeriesSVR model with a GAK kernel, and perform fit and predict operations. ```python from tslearn.generators import random_walk_blobs from tslearn.svm import TimeSeriesSVR import numpy # Generate synthetic data X, y = random_walk_blobs(n_ts_per_blob=10, sz=64, d=2, n_blobs=2) y = y.astype(float) + numpy.random.randn(20) * .1 # Initialize and train the model reg = TimeSeriesSVR(kernel="gak", gamma="auto") reg.fit(X, y) # Predict and inspect support vectors predictions = reg.predict(X) sv = reg.support_vectors_ ``` -------------------------------- ### Format Time Series Data with tslearn Source: https://tslearn.readthedocs.io/en/stable/gettingstarted.html Demonstrates how to format individual time series data into a tslearn-compatible numpy array using the `to_time_series` utility. The output is a 2D numpy array where the first dimension is the time axis and the second is the feature dimensionality. ```python from tslearn.utils import to_time_series my_first_time_series = [1, 3, 4, 2] formatted_time_series = to_time_series(my_first_time_series) print(formatted_time_series.shape) ``` -------------------------------- ### TimeSeriesMLPRegressor: Fit and Predict Example Source: https://tslearn.readthedocs.io/en/stable/gen_modules/neural_network/tslearn.neural_network.TimeSeriesMLPRegressor.html Demonstrates how to initialize, fit, and make predictions using the TimeSeriesMLPRegressor. It shows the expected shapes of coefficients and intercepts after fitting. ```python >>> mlp = TimeSeriesMLPRegressor(hidden_layer_sizes=(64, 64), ... random_state=0) >>> mlp.fit(X=[[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]], ... y=[0, 0, 1]) TimeSeriesMLPRegressor(...) >>> [c.shape for c in mlp.coefs_] [(3, 64), (64, 64), (64, 1)] >>> [c.shape for c in mlp.intercepts_] [(64,), (64,), (1,)] ``` -------------------------------- ### Load LearningShapelets Model from HDF5 Source: https://tslearn.readthedocs.io/en/stable/gen_modules/shapelets/tslearn.shapelets.LearningShapelets.html Load a previously saved LearningShapelets model from an HDF5 file using the `from_hdf5` class method. This requires the `h5py` library to be installed. ```python model = LearningShapelets.from_hdf5(path) ``` -------------------------------- ### Initialize and fit TimeSeriesKMeans with various metrics Source: https://tslearn.readthedocs.io/en/stable/gen_modules/clustering/tslearn.clustering.TimeSeriesKMeans.html This example demonstrates how to initialize the TimeSeriesKMeans model using different metrics such as Euclidean, DTW, and Soft-DTW. It shows how to fit the model to generated random walk data and handle variable-length time series. ```python from tslearn.generators import random_walks from tslearn.clustering import TimeSeriesKMeans from tslearn.utils import to_time_series_dataset # Generate random walk data X = random_walks(n_ts=50, sz=32, d=1) # Euclidean clustering km = TimeSeriesKMeans(n_clusters=3, metric="euclidean", max_iter=5, random_state=0).fit(X) # DTW clustering km_dba = TimeSeriesKMeans(n_clusters=3, metric="dtw", max_iter=5, max_iter_barycenter=5, random_state=0).fit(X) # Soft-DTW clustering km_sdtw = TimeSeriesKMeans(n_clusters=3, metric="softdtw", max_iter=5, max_iter_barycenter=5, metric_params={"gamma": .5}, random_state=0).fit(X) # Handling variable-length time series X_bis = to_time_series_dataset([[1, 2, 3, 4], [1, 2, 3], [2, 5, 6, 7, 8, 9]]) km_var = TimeSeriesKMeans(n_clusters=2, max_iter=5, metric="dtw", random_state=0).fit(X_bis) ``` -------------------------------- ### Build Documentation Locally with Make Source: https://tslearn.readthedocs.io/en/stable/contributing.html This snippet details the process of building the project's documentation locally. It involves installing required packages and running the 'make html' command within the 'docs' directory. ```bash $ pip install -e .[docs,all_features] $ cd docs $ make html ``` -------------------------------- ### Initialize and predict with KNeighborsTimeSeriesRegressor Source: https://tslearn.readthedocs.io/en/stable/gen_modules/neighbors/tslearn.neighbors.KNeighborsTimeSeriesRegressor.html Demonstrates how to instantiate the regressor with specific metrics and parameters, fit the model to time series data, and perform predictions. ```python from tslearn.neighbors import KNeighborsTimeSeriesRegressor # Basic usage clf = KNeighborsTimeSeriesRegressor(n_neighbors=2, metric="dtw") clf.fit([[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]], y=[0.1, 0.1, 1.1]) prediction = clf.predict([[1, 2.2, 3.5]]) # Usage with parallel jobs clf_parallel = KNeighborsTimeSeriesRegressor(n_neighbors=2, metric="dtw", n_jobs=2) clf_parallel.fit([[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]], y=[0.1, 0.1, 1.1]) # Usage with custom metric parameters clf_params = KNeighborsTimeSeriesRegressor(n_neighbors=2, metric="dtw", metric_params={"itakura_max_slope": 2.}, n_jobs=2) clf_params.fit([[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]], y=[0.1, 0.1, 1.1]) ``` -------------------------------- ### Format Time Series Datasets with tslearn Source: https://tslearn.readthedocs.io/en/stable/gettingstarted.html Shows how to format a collection of time series into a 3D numpy array using `to_time_series_dataset`. If time series have different lengths, NaN values are appended to shorter ones. The resulting shape is (n_ts, max_sz, d). ```python from tslearn.utils import to_time_series_dataset my_first_time_series = [1, 3, 4, 2] my_second_time_series = [1, 2, 4, 2] formatted_dataset = to_time_series_dataset([my_first_time_series, my_second_time_series]) print(formatted_dataset.shape) my_third_time_series = [1, 2, 4, 2, 2] formatted_dataset = to_time_series_dataset([my_first_time_series, my_second_time_series, my_third_time_series]) print(formatted_dataset.shape) ``` -------------------------------- ### Initialize and Train KNeighborsTimeSeriesClassifier Source: https://tslearn.readthedocs.io/en/stable/gen_modules/neighbors/tslearn.neighbors.KNeighborsTimeSeriesClassifier.html Demonstrates how to instantiate the classifier with specific metrics and parameters, fit it to time series training data, and perform predictions. The examples show usage with default settings, parallel processing, and custom metric parameters. ```python from tslearn.neighbors import KNeighborsTimeSeriesClassifier # Basic usage clf = KNeighborsTimeSeriesClassifier(n_neighbors=2, metric="dtw") clf.fit([[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]], y=[0, 0, 1]) prediction = clf.predict([[1, 2.2, 3.5]]) # Usage with parallel processing clf_parallel = KNeighborsTimeSeriesClassifier(n_neighbors=2, metric="dtw", n_jobs=2) clf_parallel.fit([[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]], y=[0, 0, 1]) # Usage with custom metric parameters clf_custom = KNeighborsTimeSeriesClassifier(n_neighbors=2, metric="dtw", metric_params={"itakura_max_slope": 2.}, n_jobs=2) clf_custom.fit([[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]], y=[0, 0, 1]) ``` -------------------------------- ### Run Tests and Code Coverage with Pytest Source: https://tslearn.readthedocs.io/en/stable/contributing.html This snippet shows how to install the necessary packages and run tests locally with code coverage using pytest and pytest-cov. This is essential for ensuring the quality and correctness of your contributions. ```bash $ pip install -e .[tests,all_features] $ pytest --cov ``` -------------------------------- ### Instantiate tslearn backends Source: https://tslearn.readthedocs.io/en/stable/backend.html Demonstrates how to use the instantiate_backend function to select between NumPy and PyTorch backends. The function accepts strings, arrays, tensors, or existing backend instances to determine the appropriate environment. ```python from tslearn.backend import instantiate_backend import numpy as np import torch # By string be_np = instantiate_backend("numpy") be_pt = instantiate_backend("pytorch") # By data type be_np_auto = instantiate_backend(np.array([0])) be_pt_auto = instantiate_backend(torch.tensor([0])) # Multiple inputs (first valid determines backend) be_multi = instantiate_backend(1, None, "Hello", torch.tensor([0]), "numpy") ``` -------------------------------- ### Clone tslearn Repository (Bash) Source: https://tslearn.readthedocs.io/en/stable/contributing.html Clones your fork of the tslearn repository to your local machine. This is the first step in setting up your development environment for contributing. ```bash $ git clone git@github.com:YourLogin/tslearn.git $ cd tslearn ``` -------------------------------- ### Initialize and Train LearningShapelets Source: https://tslearn.readthedocs.io/en/stable/gen_modules/shapelets/tslearn.shapelets.LearningShapelets.html Demonstrates how to generate synthetic time-series data, initialize the LearningShapelets model with specific shapelet parameters, and perform fitting, prediction, and transformation operations. ```python from tslearn.generators import random_walk_blobs from tslearn.shapelets import LearningShapelets # Generate synthetic data X, y = random_walk_blobs(n_ts_per_blob=10, sz=16, d=2, n_blobs=3) # Initialize model clf = LearningShapelets(n_shapelets_per_size={4: 5}, max_iter=1, verbose=0) # Fit model and inspect shapelets clf.fit(X, y) print(clf.shapelets_.shape) # Perform predictions and transformations predictions = clf.predict(X) probabilities = clf.predict_proba(X) transformed_data = clf.transform(X) ``` -------------------------------- ### get_params Source: https://tslearn.readthedocs.io/en/stable/gen_modules/matrix_profile/tslearn.matrix_profile.MatrixProfile.html Gets the parameters of the MatrixProfile estimator. ```APIDOC ## get_params ### Description Get parameters for this estimator. ### Method `get_params` ### Endpoint N/A (This is a method of the MatrixProfile class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **deep** (bool, optional) - If True, will return the parameters for this estimator and contained subobjects that are estimators. Defaults to True. ### Request Example ```python # Assuming mp is an instance of MatrixProfile parameters = mp.get_params(deep=True) ``` ### Response #### Success Response (200) * **params** (dict) - Parameter names mapped to their values. #### Response Example ```json { "params": { "subsequence_length": 4, "implementation": "numpy", "scale": false } } ``` ``` -------------------------------- ### TimeSeriesMLPClassifier Example: Training and Inspecting Coefficients Source: https://tslearn.readthedocs.io/en/stable/gen_modules/neural_network/tslearn.neural_network.TimeSeriesMLPClassifier.html This example demonstrates how to instantiate and train a TimeSeriesMLPClassifier with specified hidden layer sizes. It then shows how to access and inspect the learned coefficients and intercepts of the model. This is useful for understanding the model's internal structure after fitting. ```python from tslearn.generators import random_walk_blobs from tslearn.neural_network import TimeSeriesMLPClassifier X, y = random_walk_blobs(n_ts_per_blob=30, sz=16, d=2, n_blobs=3, random_state=0) lm = TimeSeriesMLPClassifier(hidden_layer_sizes=(64, 64), random_state=0) lm.fit(X, y) [c.shape for c in mlp.coefs_] [c.shape for c in mlp.intercepts_] ``` -------------------------------- ### NonMyopicEarlyClassifier Get Parameters API Source: https://tslearn.readthedocs.io/en/stable/gen_modules/early_classification/tslearn.early_classification.NonMyopicEarlyClassifier.html Retrieves the parameters of the estimator. ```APIDOC ## GET /get_params ### Description Get parameters for this estimator. ### Method GET ### Endpoint /get_params ### Parameters #### Query Parameters - **deep** (bool) - Optional - If True, will return the parameters for this estimator and contained subobjects that are estimators. ### Response #### Success Response (200) - **params** (dict) - Parameter names mapped to their values. #### Response Example ```json { "params": { "n_clusters": 3, "lamb": 1000.0, "cost_time_parameter": 0.1, "random_state": 0 } } ``` ``` -------------------------------- ### GET /get_params Source: https://tslearn.readthedocs.io/en/stable/gen_modules/preprocessing/tslearn.preprocessing.TimeSeriesScalerMeanVariance.html Retrieves the configuration parameters for the TimeSeriesScalerMeanVariance estimator. ```APIDOC ## GET /get_params ### Description Returns the current parameters of the estimator. ### Method GET ### Endpoint /get_params ### Parameters #### Query Parameters - **deep** (bool) - Optional - If True, returns parameters for this estimator and contained subobjects. ### Response #### Success Response (200) - **params** (dict) - Mapping of parameter names to their values. #### Response Example { "mu": 0.0, "std": 1.0, "per_timeseries": true, "per_feature": true } ``` -------------------------------- ### GET /kneighbors_graph Source: https://tslearn.readthedocs.io/en/stable/gen_modules/neighbors/tslearn.neighbors.KNeighborsTimeSeries.html Computes the weighted graph of k-Neighbors for points in X. ```APIDOC ## GET /kneighbors_graph ### Description Compute the (weighted) graph of k-Neighbors for points in X. This returns a sparse matrix representing the connectivity or distances between points. ### Method GET ### Endpoint /kneighbors_graph ### Parameters #### Query Parameters - **X** (array-like) - Optional - The query point or points. - **n_neighbors** (int) - Optional - Number of neighbors for each sample. - **mode** (string) - Optional - Type of returned matrix: 'connectivity' or 'distance'. ### Response #### Success Response (200) - **A** (sparse-matrix) - Sparse-matrix of shape (n_queries, n_samples_fit) representing the graph. ### Response Example { "A": [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 0.0, 1.0]] } ``` -------------------------------- ### KNeighborsTimeSeries Initialization and Usage Example Source: https://tslearn.readthedocs.io/en/stable/gen_modules/neighbors/tslearn.neighbors.KNeighborsTimeSeries.html Demonstrates how to initialize KNeighborsTimeSeries with different metrics and use it to find nearest neighbors in a time series dataset. It shows fitting the model and then querying for neighbors with and without returning distances. ```python >>> time_series = to_time_series_dataset([[1, 2, 3, 4], ... [3, 3, 2, 0], ... [1, 2, 2, 4]]) >>> knn = KNeighborsTimeSeries(n_neighbors=1).fit(time_series) >>> dataset = to_time_series_dataset([[1, 1, 2, 2, 2, 3, 4]]) >>> dist, ind = knn.kneighbors(dataset, return_distance=True) >>> dist array([[0.]]) >>> print(ind) [[0]] >>> knn2 = KNeighborsTimeSeries(n_neighbors=10, ... metric="euclidean").fit(time_series) >>> print(knn2.kneighbors(return_distance=False)) [[2 1] [2 0] [0 1]] ``` -------------------------------- ### Initialize and fit KernelKMeans clustering Source: https://tslearn.readthedocs.io/en/stable/gen_modules/clustering/tslearn.clustering.KernelKMeans.html Demonstrates how to generate random time series data and perform clustering using the KernelKMeans algorithm with the GAK kernel. ```python from tslearn.generators import random_walks from tslearn.clustering import KernelKMeans import numpy # Generate sample time series data X = random_walks(n_ts=50, sz=32, d=1) # Initialize and fit the model gak_km = KernelKMeans(n_clusters=3, kernel="gak", random_state=0) gak_km.fit(X) # Output cluster labels print(numpy.unique(gak_km.labels_)) ``` -------------------------------- ### GET /radius_neighbors Source: https://tslearn.readthedocs.io/en/stable/gen_modules/neighbors/tslearn.neighbors.KNeighborsTimeSeries.html Finds all neighbors within a specified radius of query points. ```APIDOC ## GET /radius_neighbors ### Description Find the neighbors within a given radius of a point or points. Returns indices and distances of points lying in a ball of size radius. ### Method GET ### Endpoint /radius_neighbors ### Parameters #### Query Parameters - **X** (array-like) - Optional - The query point or points. - **radius** (float) - Optional - Limiting distance of neighbors to return. - **return_distance** (bool) - Optional - Whether to return distances. - **sort_results** (bool) - Optional - Whether to sort results by distance. ### Response #### Success Response (200) - **neigh_dist** (ndarray) - Array of distances (if return_distance=True). - **neigh_ind** (ndarray) - Array of indices of the nearest points. ### Response Example { "neigh_dist": [[1.5, 0.5]], "neigh_ind": [[1, 2]] } ``` -------------------------------- ### Perform operations using backends Source: https://tslearn.readthedocs.io/en/stable/backend.html Shows how to utilize backend-specific methods and attributes to create arrays and perform linear algebra operations, maintaining consistency across different compute engines. ```python be = instantiate_backend("pytorch") mat = be.array([[0 , 1], [2, 3]], dtype=float) norm = be.linalg.norm(mat) print(norm) ``` -------------------------------- ### GET /generators/random_walk_blobs Source: https://tslearn.readthedocs.io/en/stable/gen_modules/tslearn.generators.html Generates a synthetic time series dataset based on blob-based random walks. ```APIDOC ## GET /generators/random_walk_blobs ### Description Generates a synthetic time series dataset using blob-based random walk routines. ### Method GET ### Endpoint /generators/random_walk_blobs ### Parameters #### Query Parameters - **n_ts_per_blob** (int) - Optional - Number of time series per blob. - **sz** (int) - Optional - Length of the time series. - **d** (int) - Optional - Dimensionality of the time series. ### Response #### Success Response (200) - **data** (array) - Generated time series dataset. ### Response Example { "data": [[0.1, 0.2], [0.3, 0.4]] } ``` -------------------------------- ### PiecewiseAggregateApproximation Initialization and Transformation Example (Python) Source: https://tslearn.readthedocs.io/en/stable/gen_modules/piecewise/tslearn.piecewise.PiecewiseAggregateApproximation.html Demonstrates how to initialize the PiecewiseAggregateApproximation transformer with a specified number of segments and then apply it to transform a dataset of time series. It also shows how to calculate distances between original and transformed time series and how to inverse transform the PAA representation back to the original time series format. ```python from tslearn.piecewise import PiecewiseAggregateApproximation paa = PiecewiseAggregateApproximation(n_segments=3) data = [[-1., 2., 0.1, -1., 1., -1.], [1., 3.2, -1., -3., 1., -1.]] paa_data = paa.fit_transform(data) print(paa_data.shape) print(paa_data) print(float(paa.distance_paa(paa_data[0], paa_data[1]))) print(float(paa.distance(data[0], data[1]))) print(paa.inverse_transform(paa_data)) ``` -------------------------------- ### GET /generators/random_walks Source: https://tslearn.readthedocs.io/en/stable/gen_modules/tslearn.generators.html Generates a synthetic time series dataset using standard random walk routines. ```APIDOC ## GET /generators/random_walks ### Description Generates a synthetic time series dataset using standard random walk routines. ### Method GET ### Endpoint /generators/random_walks ### Parameters #### Query Parameters - **n_ts** (int) - Optional - Number of time series to generate. - **sz** (int) - Optional - Length of the time series. - **d** (int) - Optional - Dimensionality of the time series. - **mu** (float) - Optional - Mean of the random walk steps. - **std** (float) - Optional - Standard deviation of the random walk steps. ### Response #### Success Response (200) - **data** (array) - Generated time series dataset. ### Response Example { "data": [[0.0, 0.1], [0.1, 0.2]] } ``` -------------------------------- ### NonMyopicEarlyClassifier Get Metadata Routing API Source: https://tslearn.readthedocs.io/en/stable/gen_modules/early_classification/tslearn.early_classification.NonMyopicEarlyClassifier.html Retrieves the metadata routing information for the object. ```APIDOC ## GET /get_metadata_routing ### Description Get metadata routing of this object. Please check User Guide on how the routing mechanism works. ### Method GET ### Endpoint /get_metadata_routing ### Parameters None ### Response #### Success Response (200) - **routing** (MetadataRequest) - A `MetadataRequest` encapsulating routing information. #### Response Example ```json { "routing": "MetadataRequest(...)" } ``` ``` -------------------------------- ### GET /datasets/baseline Source: https://tslearn.readthedocs.io/en/stable/gen_modules/datasets/tslearn.datasets.UCR_UEA_datasets.html Report baseline performance metrics for specified datasets and methods. ```APIDOC ## GET /datasets/baseline ### Description Retrieves baseline accuracy scores as provided by the UEA/UCR website for univariate datasets. ### Method GET ### Endpoint /baseline_accuracy ### Parameters #### Query Parameters - **list_datasets** (list) - Optional - List of dataset names to report. - **list_methods** (list) - Optional - List of baseline methods to report. ### Response #### Success Response (200) - **results** (dict) - Dictionary where keys are dataset names and values are accuracy scores per method. #### Response Example { "Adiac": {"C45": 0.5421} } ``` -------------------------------- ### Train and Predict with TimeSeriesSVC Source: https://tslearn.readthedocs.io/en/stable/gen_modules/svm/tslearn.svm.TimeSeriesSVC.html Demonstrates initializing a TimeSeriesSVC with a Global Alignment Kernel (GAK), fitting the model to generated time series data, and performing predictions and probability estimations. ```python from tslearn.generators import random_walk_blobs from tslearn.svm import TimeSeriesSVC # Generate synthetic time series data X, y = random_walk_blobs(n_ts_per_blob=10, sz=64, d=2, n_blobs=2) # Initialize and fit the SVM classifier clf = TimeSeriesSVC(kernel="gak", gamma="auto", probability=True) clf.fit(X, y) # Perform predictions and probability estimations predictions = clf.predict(X) proba = clf.predict_proba(X) log_proba = clf.predict_log_proba(X) # Access support vectors sv = clf.support_vectors_ ``` -------------------------------- ### Load LearningShapelets Model from Pickle Source: https://tslearn.readthedocs.io/en/stable/gen_modules/shapelets/tslearn.shapelets.LearningShapelets.html Load a LearningShapelets model from a pickle file using the `from_pickle` class method. This provides a straightforward way to save and load model states. ```python model = LearningShapelets.from_pickle(path) ``` -------------------------------- ### GET /datasets/load Source: https://tslearn.readthedocs.io/en/stable/gen_modules/datasets/tslearn.datasets.UCR_UEA_datasets.html Load a specific time series dataset into memory by its name. ```APIDOC ## GET /datasets/load ### Description Loads a dataset from the UCR/UEA archive using its unique identifier. ### Method GET ### Endpoint /load_dataset ### Parameters #### Query Parameters - **dataset_name** (str) - Required - The name of the dataset to load. ### Response #### Success Response (200) - **train_ts** (numpy.ndarray) - Training time series data. - **train_labels** (numpy.ndarray) - Training labels. - **test_ts** (numpy.ndarray) - Test time series data. - **test_labels** (numpy.ndarray) - Test labels. #### Response Example { "train_ts": "[...numpy array...]", "train_labels": "[...numpy array...]", "test_ts": "[...numpy array...]", "test_labels": "[...numpy array...]" } ``` -------------------------------- ### GET /KNeighborsTimeSeriesClassifier/load Source: https://tslearn.readthedocs.io/en/stable/gen_modules/neighbors/tslearn.neighbors.KNeighborsTimeSeriesClassifier.html Loads a pre-trained KNeighborsTimeSeriesClassifier model from a specified file format (HDF5 or JSON). ```APIDOC ## GET /KNeighborsTimeSeriesClassifier/load ### Description Restores a serialized model instance from a file path. Supports HDF5 and JSON formats. ### Method GET ### Endpoint /KNeighborsTimeSeriesClassifier/load ### Parameters #### Query Parameters - **path** (string) - Required - The full system path to the model file. - **format** (string) - Required - The file format ('hdf5' or 'json'). ### Request Example { "path": "/models/my_classifier.json", "format": "json" } ### Response #### Success Response (200) - **model** (object) - The loaded model instance. #### Response Example { "model": "KNeighborsTimeSeriesClassifier instance" } ``` -------------------------------- ### Initialize and Train NonMyopicEarlyClassifier Source: https://tslearn.readthedocs.io/en/stable/gen_modules/early_classification/tslearn.early_classification.NonMyopicEarlyClassifier.html Demonstrates how to instantiate the NonMyopicEarlyClassifier with specific hyperparameters, fit it to a time series dataset, and perform predictions including class labels and prediction timestamps. ```python from tslearn.early_classification import NonMyopicEarlyClassifier from tslearn.utils import to_time_series_dataset dataset = to_time_series_dataset([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1], [3, 2, 1, 1, 2, 3], [3, 2, 1, 1, 2, 3]]) y = [0, 0, 0, 1, 1, 1, 0, 0] model = NonMyopicEarlyClassifier(n_clusters=3, lamb=1000., cost_time_parameter=.1, random_state=0) model.fit(dataset, y) preds, pred_times = model.predict_class_and_earliness(dataset) print(preds) print(pred_times) ``` -------------------------------- ### NonMyopicEarlyClassifier Get Cluster Probabilities API Source: https://tslearn.readthedocs.io/en/stable/gen_modules/early_classification/tslearn.early_classification.NonMyopicEarlyClassifier.html Computes the probability of a time series belonging to each cluster. ```APIDOC ## POST /get_cluster_probas ### Description Compute cluster probability ๐‘ƒโก(๐‘๐‘˜|๐‘‹โข๐‘–). This quantity is computed using the following formula: ๐‘ƒโก(๐‘๐‘˜|๐‘‹โข๐‘–)=๐‘ ๐‘˜โก(๐‘‹โข๐‘–)โˆ‘๐‘—๐‘ ๐‘—โก(๐‘‹โข๐‘–) where ๐‘ ๐‘˜โก(๐‘‹โข๐‘–)=11+expโกโˆ’๐œ†โขฮ”๐‘˜โก(๐‘‹โข๐‘–) with ฮ”๐‘˜โก(๐‘‹โข๐‘–)=ยฏ๐ทโˆ’๐‘‘โก(๐‘‹โข๐‘–,๐‘๐‘˜)ยฏ๐ท and ยฏ๐ท is the average of the distances between Xi and the cluster centers. ### Method POST ### Endpoint /get_cluster_probas ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **Xi** (numpy array) - Required - A time series observed up to time t ### Request Example ```json { "Xi": "[[1, 2]]" } ``` ### Response #### Success Response (200) - **probas** (numpy array) - numpy array, shape (n_clusters, ) - Probability estimates for each cluster. #### Response Example ```json { "probas": "[0.33, 0.33, 0.33]" } ``` ``` -------------------------------- ### Compute Frechet Similarity with PyTorch Backend Source: https://tslearn.readthedocs.io/en/stable/gen_modules/metrics/tslearn.metrics.frechet.html Shows how to use the PyTorch backend to compute Frechet similarity, enabling gradient calculation for optimization tasks. ```python import torch from tslearn.metrics import frechet # 1D time series with gradients s1 = torch.tensor([[1.0], [2.0], [3.0]], requires_grad=True) s2 = torch.tensor([[3.0], [4.0], [-3.0]]) sim = frechet(s1, s2, be="pytorch") sim.backward() # 2D time series with gradients s1_2d = torch.tensor([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]], requires_grad=True) s2_2d = torch.tensor([[3.0, 3.0], [4.0, 4.0], [-3.0, -3.0]]) sim_2d = frechet(s1_2d, s2_2d, be="pytorch") sim_2d.backward() ``` -------------------------------- ### GET /utils/ts_zeros Source: https://tslearn.readthedocs.io/en/stable/gen_modules/utils/tslearn.utils.ts_zeros.html Generates a time series array of zeros based on specified size and dimensionality. ```APIDOC ## GET tslearn.utils.ts_zeros ### Description Returns a time series made of zero values as a numpy.ndarray. ### Method GET ### Endpoint tslearn.utils.ts_zeros(sz, d=1) ### Parameters #### Path Parameters - **sz** (int) - Required - Time series size. - **d** (int) - Optional (default: 1) - Time series dimensionality. ### Request Example ```python ts_zeros(3, 2) ``` ### Response #### Success Response (200) - **numpy.ndarray** - A time series made of zeros. #### Response Example ```json [ [0.0, 0.0], [0.0, 0.0], [0.0, 0.0] ] ``` ``` -------------------------------- ### GET /metrics/itakura_mask Source: https://tslearn.readthedocs.io/en/stable/gen_modules/metrics/tslearn.metrics.itakura_mask.html Computes the Itakura mask for two time series of given sizes, constrained by a maximum slope. ```APIDOC ## GET /metrics/itakura_mask ### Description Compute the Itakura mask, which defines a parallelogram constraint for time series alignment algorithms like Dynamic Time Warping. ### Method GET ### Endpoint /metrics/itakura_mask ### Parameters #### Query Parameters - **sz1** (int) - Required - The size of the first time series. - **sz2** (int) - Required - The size of the second time series. - **max_slope** (float) - Optional (default=2.0) - The maximum slope of the parallelogram. - **be** (string/object) - Optional - Backend identifier ('numpy', 'pytorch', or None). ### Request Example GET /metrics/itakura_mask?sz1=6&sz2=6&max_slope=3 ### Response #### Success Response (200) - **mask** (array-like) - A boolean array of shape (sz1, sz2) representing the Itakura mask. #### Response Example [ [true, false, false, false, false, false], [false, true, true, true, false, false], [false, true, true, true, true, false], [false, true, true, true, true, false], [false, false, true, true, true, false], [false, false, false, false, false, true] ] ``` -------------------------------- ### from_pickle Source: https://tslearn.readthedocs.io/en/stable/gen_modules/matrix_profile/tslearn.matrix_profile.MatrixProfile.html Loads a MatrixProfile model from a pickle file. ```APIDOC ## from_pickle ### Description Load a MatrixProfile model from a pickle file. ### Method `from_pickle` (classmethod) ### Endpoint N/A (This is a class method of the MatrixProfile class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **path** (str) - Required - The full path to the pickle file. ### Request Example ```python # Assuming 'model.pkl' is a saved MatrixProfile model loaded_mp = MatrixProfile.from_pickle('model.pkl') ``` ### Response #### Success Response (200) * **Model instance** (MatrixProfile) - An instance of the MatrixProfile model loaded from the file. #### Response Example ```json { "message": "Model loaded successfully from pickle", "model_type": "MatrixProfile" } ``` ``` -------------------------------- ### Transform and analyze time series using 1d-SAX in Python Source: https://tslearn.readthedocs.io/en/stable/gen_modules/piecewise/tslearn.piecewise.OneD_SymbolicAggregateApproximation.html This example demonstrates how to initialize the 1d-SAX transformer, fit it to time series data, perform transformations, calculate distances between representations, and invert the transformation back to time series space. ```python from tslearn.piecewise import OneD_SymbolicAggregateApproximation # Initialize 1d-SAX transformer one_d_sax = OneD_SymbolicAggregateApproximation(n_segments=3, alphabet_size_avg=2, alphabet_size_slope=2, sigma_l=1.) # Input data data = [[-1., 2., 0.1, -1., 1., -1.], [1., 3.2, -1., -3., 1., -1.]] # Fit and transform one_d_sax_data = one_d_sax.fit_transform(data) # Calculate distances dist = one_d_sax.distance_sax(one_d_sax_data[0], one_d_sax_data[1]) # Inverse transform original_approx = one_d_sax.inverse_transform(one_d_sax_data) ``` -------------------------------- ### GET /metrics/compute_mask Source: https://tslearn.readthedocs.io/en/stable/gen_modules/metrics/tslearn.metrics.compute_mask.html Computes the constraint region mask for two time series based on specified global constraints. ```APIDOC ## GET compute_mask ### Description Computes the mask (region constraint) for two time series or integer sizes to restrict admissible paths for Dynamic Time Warping (DTW). ### Method GET ### Endpoint tslearn.metrics.compute_mask ### Parameters #### Query Parameters - **s1** (array-like/int) - Required - A time series or integer size for the first dimension. - **s2** (array-like/int) - Required - A time series or integer size for the second dimension. - **global_constraint** (int) - Optional - 0: None, 1: Itakura, 2: Sakoe-Chiba. Default: 0. - **sakoe_chiba_radius** (int) - Optional - Radius for Sakoe-Chiba band. Default: None. - **itakura_max_slope** (float) - Optional - Maximum slope for Itakura parallelogram. Default: None. - **be** (object/str) - Optional - Backend object (numpy or pytorch). Default: None. ### Request Example { "s1": 4, "s2": 4, "sakoe_chiba_radius": 1 } ### Response #### Success Response (200) - **mask** (array-like) - A boolean matrix of shape (sz1, sz2) representing the constraint region. #### Response Example [ [true, true, false, false], [true, true, true, false], [false, true, true, true], [false, false, true, true] ] ``` -------------------------------- ### Accessing and Loading Datasets with tslearn Source: https://tslearn.readthedocs.io/en/stable/gen_modules/datasets/tslearn.datasets.UCR_UEA_datasets.html Demonstrates how to initialize the dataset manager, list available cached datasets, and load a specific dataset into memory. ```python from tslearn.datasets import UCR_UEA_datasets # Initialize the loader loader = UCR_UEA_datasets() # Load a specific dataset X_train, y_train, X_test, y_test = loader.load_dataset("BeetleFly") # List cached datasets cached = loader.list_cached_datasets() print(f"Is BeetleFly cached? {'BeetleFly' in cached}") ``` -------------------------------- ### KNeighborsTimeSeries Get Parameters Source: https://tslearn.readthedocs.io/en/stable/gen_modules/neighbors/tslearn.neighbors.KNeighborsTimeSeries.html Retrieves the parameters of the KNeighborsTimeSeries estimator. This method can optionally return parameters for contained sub-estimators. ```python get_params(_deep =True_)# Get parameters for this estimator. Parameters: **deep** bool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns: **params** dict Parameter names mapped to their values. ```