tskmeans module
TSGlobalKmeans class
- class tscluster.tskmeans.TSGlobalKmeans(n_clusters=8, *, init='k-means++', n_init='auto', max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True, algorithm='lloyd')
Applies sklearn’s K-Means clustering to the version of a data reshaped from a 3D array of shape T x N x F to a 2D array of shape (TxN) x F
Read more in the Sklearn’s user guide. The follow parameters are from sklearn’s K-Means constructor.
- Parameters:
- n_clustersint, default=8
The number of clusters to form as well as the number of centroids to generate.
For an example of how to choose an optimal value for n_clusters refer to sphx_glr_auto_examples_cluster_plot_kmeans_silhouette_analysis.py.
- init{‘k-means++’, ‘random’}, callable or array-like of shape (n_clusters, n_features), default=’k-means++’
Method for initialization:
- ‘k-means++’selects initial cluster centroids using sampling based on an empirical probability distribution of the points’ contribution to the overall inertia. This technique speeds up convergence. The algorithm implemented is “greedy k-means++”. It differs from the vanilla k-means++ by making several trials at each sampling step and choosing the best centroid among them.
- ‘random’: choose n_clusters observations (rows) at random from data for the initial centroids.
- If an array is passed, it should be of shape (n_clusters, n_features) and gives the initial centers.
- If a callable is passed, it should take arguments X, n_clusters and a random state and return an initialization.
For an example of how to use the different init strategy, see the example entitled sphx_glr_auto_examples_cluster_plot_kmeans_digits.py.
- n_init‘auto’ or int, default=’auto’
Number of times the k-means algorithm is run with different centroid seeds. The final results is the best output of n_init consecutive runs in terms of inertia. Several runs are recommended for sparse high-dimensional problems (see kmeans_sparse_high_dim).
When n_init=’auto’, the number of runs depends on the value of init: 10 if using init=’random’ or init is a callable; 1 if using init=’k-means++’ or init is an array-like.
- max_iterint, default=300
Maximum number of iterations of the k-means algorithm for a single run.
- tolfloat, default=1e-4
Relative tolerance with regards to Frobenius norm of the difference in the cluster centers of two consecutive iterations to declare convergence.
- verboseint, default=0
Verbosity mode.
- random_stateint, RandomState instance or None, default=None
Determines random number generation for centroid initialization. Use an int to make the randomness deterministic. See Glossary <random_state>.
- copy_xbool, default=True
When pre-computing distances it is more numerically accurate to center the data first. If copy_x is True (default), then the original data is not modified. If False, the original data is modified, and put back before the function returns, but small numerical differences may be introduced by subtracting and then adding the data mean. Note that if the original data is not C-contiguous, a copy will be made even if copy_x is False. If the original data is sparse, but not in CSR format, a copy will be made even if copy_x is False.
- algorithm{“lloyd”, “elkan”}, default=”lloyd”
K-means algorithm to use. The classical EM-style algorithm is “lloyd”. The “elkan” variation can be more efficient on some datasets with well-defined clusters, by using the triangle inequality. However it’s more memory intensive due to the allocation of an extra array of shape (n_samples, n_clusters).
- Attributes:
cluster_centers_returns the cluster centers. If scheme is fixed centers, returns a k x F 2D array. Where k is the number of clusters and F is the number of features. If scheme is changing centers, returns a T x k x F 3D array. Where T is the number of time stesp, k is the number of clusters and F is the number of features.
fitted_data_shape_returns a tuple of the shape of the fitted data in TNF format. E.g (T, N, F) where T, N, and F are the number of timesteps, observations, and features respectively.
labels_returns the assignment labels. values are integers in range [0, k-1], where k is the number of clusters. If scheme is fixed assignment, returns a 1D array of size N. Where N is the number of entities. A value of j at the i-th index means that entity i is assigned to the j-th cluster at all time steps. If scheme is changing assignment, returns a N x T 2D array. Where N is the number of entities and T is the number of time steps. A value of j at the i-th row and t-th column means that entity i is assigned to the j-th cluster at the t-th time step.
label_dict_returns a dictionary of the labels whose keys are ‘T’, ‘N’, and ‘F’ (which are the number of time steps, entities, and features respectively). Value of each key is a list such that the value of key:
n_changes_returns the total number of label changes
Methods
fit(X[, label_dict])Method for fitting the model on the data.
returns the dynamic entities and their number of changes.
get_named_cluster_centers([label_dict])Method to return the cluster centers with custom names of time steps and features.
get_named_labels([label_dict])Method to return the a data frame of the label assignments with custom names of time steps and entities.
set_label_dict(value)Method to manually set the label_dict_.
- fit(X: npt.NDArray[np.float64], label_dict: dict | None = None, **kwargs) TSGlobalKmeans
Method for fitting the model on the data.
- Parameters:
- Xnumpy array
Input time series data. Should be a 3 dimensional array in TNF fromat.
- label_dictdict, default=None
- A dictionary of the labels of X. Keys should be ‘T’, ‘N’, and ‘F’ (which are the number of time steps, entities, and features respectively). Value of each key is a list such that the value of key:
‘T’ is a list of names/labels of each time step used as index of each dataframe during fit. Default is range(0, T). Where T is the number of time steps in the fitted data
‘N’ is a list of names/labels of each entity used as index of the dataframe. Default is range(0, N). Where N is the number of entities/observations in the fitted data
‘F’ is a list of names/labels of each feature used as column of each dataframe. Default is range(0, F). Where F is the number of features in the fitted data
data_loader function from tscluster.preprocessing.utils can help in getting label_dict of a data.
- **kwargs keyword arguments to be passed to skleanr’s kmeans fit method
- Returns:
- self:
The fitted TSGlobalKmeans object.
- get_dynamic_entities() Tuple[List[int64], List[int64]]
returns the dynamic entities and their number of changes. Both lists are sorted by the number of cluster changes in descending order.
- Returns:
- dynamic entitieslist
a 1-D array of the indexes of the entities that change cluster at least once.
- number of changeslist
a 1-D array of the number of changes for each dynamic entity such that the i-th element is the number of cluster changes for the i-th dynamic entity
- get_named_cluster_centers(label_dict: dict | None = None) List[pd.DataFrame]
Method to return the cluster centers with custom names of time steps and features.
- Parameters:
- label_dict dict, default=None
a dictionary whose keys are ‘T’, ‘N’, and ‘F’ (which are the number of time steps, entities, and features respectively). Value of each key is a list such that the value of key: - ‘T’ is a list of names/labels of each time step to be used as index of each dataframe. If None, range(0, T) is used. Where T is the number of time steps in the fitted data - ‘N’ is a list of names/labels of each entity to be used as index of the dataframe. If None, range(0, N) is used. Where N is the number of entities/observations in the fitted data - ‘F’ is a list of names/labels of each feature to be used as column of each dataframe. If None, range(0, F) is used. Where F is the number of features in the fitted data If label_dict is None, the result of self.label_dict_ is used.
- Returns
- ——
- list
A list of k pandas DataFrames. Where k is the number of clusters. The i-th dataframe in the list is a T x F dataframe of the values of the cluster centers of the i-th cluster.
- get_named_labels(label_dict: dict | None = None) pd.DataFrame
Method to return the a data frame of the label assignments with custom names of time steps and entities.
- Parameters:
- label_dictdict, default=None
a dictionary whose keys are ‘T’, ‘N’, and ‘F’ (which are the number of time steps, entities, and features respectively). Value of each key is a list such that the value of key: - ‘T’ is a list of names/labels of each time step to be used as index of each dataframe. If None, range(0, T) is used. Where T is the number of time steps in the fitted data - ‘N’ is a list of names/labels of each entity to be used as index of the dataframe. If None, range(0, N) is used. Where N is the number of entities/observations in the fitted data - ‘F’ is a list of names/labels of each feature to be used as column of each dataframe. If None, range(0, F) is used. Where F is the number of features in the fitted data If label_dict is None, the result of self.label_dict_ is used.
- Returns:
- pd.DataFrame
A pandas DataFrame with shape (N, T). The value in the n-th row and t-th column is an integer indicating the custer assignment of the n-th entity/observation at time t.
- set_label_dict(value: dict) None
Method to manually set the label_dict_.
- Parameters:
- valuedict
the value to set as label_dict_. Should be a dict with all of ‘T’, ‘N’, and ‘F’ (case sensitive, which are number of time steps, entities, and features respectively) as key. The value of each key is a list of labels for the key in the data. If your data don’t have values for any of the keys, set its value to None.
- Returns:
- dict
a dictionary whose keys are ‘T’, ‘N’, and ‘F’; and values are lists of the labels of each key.
TSKmeans class
- class tscluster.tskmeans.TSKmeans(n_clusters=3, max_iter=50, tol=1e-06, n_init=1, metric='euclidean', max_iter_barycenter=100, metric_params=None, n_jobs=None, dtw_inertia=False, verbose=0, random_state=None, init='k-means++')
Applies tslearn’s TimeSeriesKMeans clustering to the data.
Read more in the tslearn’s user guide. The follow parameters are from tslearn’s TimeSeriesKMeans constructor.
- Parameters:
- n_clustersint (default: 3)
Number of clusters to form.
- max_iterint (default: 50)
Maximum number of iterations of the k-means algorithm for a single run.
- tolfloat (default: 1e-6)
Inertia variation threshold. If at some point, inertia varies less than this threshold between two consecutive iterations, the model is considered to have converged and the algorithm stops.
- n_initint (default: 1)
Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia.
- metric{“euclidean”, “dtw”, “softdtw”} (default: “euclidean”)
Metric to be used for both cluster assignment and barycenter computation. If “dtw”, DBA is used for barycenter computation.
- max_iter_barycenterint (default: 100)
Number of iterations for the barycenter computation process. Only used if metric=”dtw” or metric=”softdtw”.
- metric_paramsdict or None (default: None)
Parameter values for the chosen metric. For metrics that accept parallelization of the cross-distance matrix computations, n_jobs key passed in metric_params is overridden by the n_jobs argument.
- n_jobsint or None, optional (default=None)
The number of jobs to run in parallel for cross-distance matrix computations. Ignored if the cross-distance matrix cannot be computed using parallelization. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See scikit-learns’ Glossary <https://scikit-learn.org/stable/glossary.html#term-n-jobs>_ for more details.
- dtw_inertia: bool (default: False)
Whether to compute DTW inertia even if DTW is not the chosen metric.
- verboseint (default: 0)
If nonzero, print information about the inertia while learning the model and joblib progress messages are printed.
- random_stateinteger or numpy.RandomState, optional
Generator used to initialize the centers. If an integer is given, it fixes the seed. Defaults to the global numpy random number generator.
- init{‘k-means++’, ‘random’ or an ndarray} (default: ‘k-means++’)
Method for initialization: ‘k-means++’ : use k-means++ heuristic. See scikit-learn’s k_init_ <https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/ cluster/k_means_.py>_ for more. ‘random’: choose k observations (rows) at random from data for the initial centroids. If an ndarray is passed, it should be of shape (n_clusters, ts_size, d) and gives the initial centers.
- Attributes:
cluster_centers_returns the cluster centers. If scheme is fixed centers, returns a k x F 2D array. Where k is the number of clusters and F is the number of features. If scheme is changing centers, returns a T x k x F 3D array. Where T is the number of time stesp, k is the number of clusters and F is the number of features.
fitted_data_shape_returns a tuple of the shape of the fitted data in TNF format. E.g (T, N, F) where T, N, and F are the number of timesteps,
labels_Returns the assignment labels.
label_dict_returns a dictionary of the labels whose keys are ‘T’, ‘N’, and ‘F’ (which are the number of time steps, entities, and features respectively). Value of each key is a list such that the value of key:
n_changes_returns the total number of label changes
Methods
fit(X[, label_dict])Method for fitting the model on the data.
returns the dynamic entities and their number of changes.
get_named_cluster_centers([label_dict])Method to return the cluster centers with custom names of time steps and features.
get_named_labels([label_dict])Method to return the a data frame of the label assignments with custom names of time steps and entities.
set_label_dict(value)Method to manually set the label_dict_.
- fit(X: npt.NDArray[np.float64], label_dict: dict | None = None, **kwargs) TSKmeans
Method for fitting the model on the data.
- Parameters:
- Xnumpy array
Input time series data.Should be a 3 dimensional array in TNF fromat.
- label_dictdict, default=None
- A dictionary of the labels of X. Keys should be ‘T’, ‘N’, and ‘F’ (which are the number of time steps, entities, and features respectively). Value of each key is a list such that the value of key:
‘T’ is a list of names/labels of each time step used as index of each dataframe during fit. Default is range(0, T). Where T is the number of time steps in the fitted data
‘N’ is a list of names/labels of each entity used as index of the dataframe. Default is range(0, N). Where N is the number of entities/observations in the fitted data
‘F’ is a list of names/labels of each feature used as column of each dataframe. Default is range(0, F). Where F is the number of features in the fitted data
data_loader function from tscluster.preprocessing.utils can help in getting label_dict of a data.
- **kwargs keyword arguments to be passed to tslearn’s kmeans fit method
- Returns:
- self:
The fitted TSKmeans object.
- get_dynamic_entities() Tuple[List[int64], List[int64]]
returns the dynamic entities and their number of changes. Both lists are sorted by the number of cluster changes in descending order.
- Returns:
- dynamic entitieslist
a 1-D array of the indexes of the entities that change cluster at least once.
- number of changeslist
a 1-D array of the number of changes for each dynamic entity such that the i-th element is the number of cluster changes for the i-th dynamic entity
- get_named_cluster_centers(label_dict: dict | None = None) List[pd.DataFrame]
Method to return the cluster centers with custom names of time steps and features.
- Parameters:
- label_dict dict, default=None
a dictionary whose keys are ‘T’, ‘N’, and ‘F’ (which are the number of time steps, entities, and features respectively). Value of each key is a list such that the value of key: - ‘T’ is a list of names/labels of each time step to be used as index of each dataframe. If None, range(0, T) is used. Where T is the number of time steps in the fitted data - ‘N’ is a list of names/labels of each entity to be used as index of the dataframe. If None, range(0, N) is used. Where N is the number of entities/observations in the fitted data - ‘F’ is a list of names/labels of each feature to be used as column of each dataframe. If None, range(0, F) is used. Where F is the number of features in the fitted data If label_dict is None, the result of self.label_dict_ is used.
- Returns
- ——
- list
A list of k pandas DataFrames. Where k is the number of clusters. The i-th dataframe in the list is a T x F dataframe of the values of the cluster centers of the i-th cluster.
- get_named_labels(label_dict: dict | None = None) pd.DataFrame
Method to return the a data frame of the label assignments with custom names of time steps and entities.
- Parameters:
- label_dictdict, default=None
a dictionary whose keys are ‘T’, ‘N’, and ‘F’ (which are the number of time steps, entities, and features respectively). Value of each key is a list such that the value of key: - ‘T’ is a list of names/labels of each time step to be used as index of each dataframe. If None, range(0, T) is used. Where T is the number of time steps in the fitted data - ‘N’ is a list of names/labels of each entity to be used as index of the dataframe. If None, range(0, N) is used. Where N is the number of entities/observations in the fitted data - ‘F’ is a list of names/labels of each feature to be used as column of each dataframe. If None, range(0, F) is used. Where F is the number of features in the fitted data If label_dict is None, the result of self.label_dict_ is used.
- Returns:
- pd.DataFrame
A pandas DataFrame with shape (N, T). The value in the n-th row and t-th column is an integer indicating the custer assignment of the n-th entity/observation at time t.
- set_label_dict(value: dict) None
Method to manually set the label_dict_.
- Parameters:
- valuedict
the value to set as label_dict_. Should be a dict with all of ‘T’, ‘N’, and ‘F’ (case sensitive, which are number of time steps, entities, and features respectively) as key. The value of each key is a list of labels for the key in the data. If your data don’t have values for any of the keys, set its value to None.
- Returns:
- dict
a dictionary whose keys are ‘T’, ‘N’, and ‘F’; and values are lists of the labels of each key.