hypertools.cluster¶
- hypertools.cluster(x, cluster='KMeans', n_clusters=None, return_model=False, manip=None, normalize=None, reduce=None, ndims=None, align=None, format_data=True, random_state=None, model=None)[source]¶
Performs clustering analysis and returns a list of cluster labels
- Parameters:
- xA Numpy array, Pandas Dataframe or list/tuple of arrays/dfs
The data to be clustered. You can pass a single array/df or a list (a tuple of datasets is treated exactly like a list). If a list is passed, the arrays will be stacked and the clustering will be performed across all lists (i.e. not within each list). All datasets in a list must have the same number of columns (the stacked data shares one feature space); reduce or align them to a common dimensionality first if they differ. None raises a TypeError.
- clusterstr, class, instance, dict, fitted Clusterer, False, or None
Model to use to discover clusters. Supported algorithms are: KMeans, MiniBatchKMeans, AgglomerativeClustering, Birch, FeatureAgglomeration, SpectralClustering, HDBSCAN, MeanShift, DBSCAN, OPTICS and AffinityPropagation (default: KMeans), plus the mixture (soft-clustering) models GaussianMixture, BayesianGaussianMixture, LatentDirichletAllocation and NMF. Can be passed as a string, a bare (uninstantiated) scikit-learn-style class, an already-constructed instance, the canonical dict spec {‘model’: …, ‘args’: […], ‘kwargs’: {…}} (both ‘args’ and ‘kwargs’ are OPTIONAL; positional ‘args’ are bound to the model’s constructor parameters by position – e.g. {‘model’: ‘KMeans’, ‘args’: [5]} asks for 5 clusters – with ‘kwargs’ winning over ‘args’ on a conflict, and a spec-carried cluster count winning over n_clusters=), or the LEGACY dict spec {‘model’ : ‘KMeans’, ‘params’ : {‘max_iter’ : 100}} (accepted for backward compatibility, but emits a DeprecationWarning). A previously-fitted Clusterer (as returned by return_model=True) is applied via .transform/.predict instead of being refit; no-predict models (e.g. AgglomerativeClustering) can only recover their fit-time labels this way – reusing them on different data warns or raises rather than silently mislabeling. None or False skips clustering entirely and returns the input unchanged. See scikit-learn specific model docs for details on parameters supported for each model. Note: LatentDirichletAllocation and NMF require non-negative data, and FeatureAgglomeration clusters features (columns), not observations – it returns one label per column of the input (with a UserWarning), not one per row.
- n_clustersint or None
Number of clusters to discover (default: None, which means 3). Must be an integer >= 1; anything else raises a ValueError naming the kwarg (rather than leaking scikit-learn’s internal parameter-validation error). Not used for models that discover the number of clusters automatically (HDBSCAN, MeanShift, DBSCAN, OPTICS, AffinityPropagation). For mixture models this sets the number of components. If the cluster spec itself carries a cluster count (an already-constructed instance’s own setting, or n_clusters/n_components in a dict spec’s kwargs), the spec’s value wins and a UserWarning notes the conflict.
- return_modelbool
If True, also return the fitted model: the fitted Clusterer wrapper when only the cluster stage ran, or a fitted hypertools.Pipeline when manip=/normalize=/reduce=/align= made multiple stages run (default: False).
- manip, normalize, reduce, alignmodel spec, False, or None
Cross-module stage kwargs (GH #138): when any of these is given, the other stages also run (via hypertools.core.pipeline.build_pipeline), in the canonical order manip -> normalize -> reduce -> align -> cluster (GH #153), with this function’s own cluster=/n_clusters= slotted in at the cluster stage (default: None for all four, i.e. only cluster runs). False skips a stage, exactly like None.
- ndimsint or None
Passed through to the reduce stage (as ndims=) when reduce= is also given. Without reduce= it has no effect, and a UserWarning says so (the pre-1.0 cluster(ndims=…) shortcut that reduced before clustering was removed).
- format_databool
Whether or not to first call the format_data function (default: True).
- random_stateint, RandomState, or None
Seed for reproducibility. Injected into the clustering model’s constructor when it accepts a random_state (KMeans, SpectralClustering, GaussianMixture, …) and the spec did not set one itself; density clusterers without a random_state parameter, and already-constructed instances you pass in, are left alone (default: None).
- modelsame forms as cluster, or None
Alias for cluster=, so the own-stage model spec can be spelled model= here exactly as in hyp.manip/hyp.impute/hyp.predict/ hyp.align (release-1.0 audit: the sibling APIs used two different kwarg conventions). Pass only one of cluster=/model=; passing both (with different values) raises ValueError (default: None).
- Returns:
- cluster_labelslist or numpy.ndarray
For hard-clustering models, a list of plain Python int cluster labels (one per observation; FeatureAgglomeration instead returns one label per COLUMN of the input – it clusters features). For mixture models, an (n_samples, n_components) array of membership proportions whose rows sum to 1. If return_model=True, a (cluster_labels, model) tuple is returned instead.
Examples
>>> import numpy as np >>> import hypertools as hyp >>> rng = np.random.default_rng(0) >>> x = np.vstack([rng.standard_normal((20, 4)), ... rng.standard_normal((20, 4)) + 10.0]) >>> labels = hyp.cluster(x, n_clusters=2, random_state=0) >>> len(labels), len(set(labels)) (40, 2)