doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
class sklearn.cluster.AffinityPropagation(*, damping=0.5, max_iter=200, convergence_iter=15, copy=True, preference=None, affinity='euclidean', verbose=False, random_state='warn') [source]
Perform Affinity Propagation Clustering of data. Read more in the User Guide. Parameters
dampingfloat, default=0.5
Damping factor (between 0.5 and 1) is the extent to which the current value is maintained relative to incoming values (weighted 1 - damping). This in order to avoid numerical oscillations when updating these values (messages).
max_iterint, default=200
Maximum number of iterations.
convergence_iterint, default=15
Number of iterations with no change in the number of estimated clusters that stops the convergence.
copybool, default=True
Make a copy of input data.
preferencearray-like of shape (n_samples,) or float, default=None
Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, ie of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities.
affinity{‘euclidean’, ‘precomputed’}, default=’euclidean’
Which affinity to use. At the moment ‘precomputed’ and euclidean are supported. ‘euclidean’ uses the negative squared euclidean distance between points.
verbosebool, default=False
Whether to be verbose.
random_stateint, RandomState instance or None, default=0
Pseudo-random number generator to control the starting state. Use an int for reproducible results across function calls. See the Glossary. New in version 0.23: this parameter was previously hardcoded as 0. Attributes
cluster_centers_indices_ndarray of shape (n_clusters,)
Indices of cluster centers.
cluster_centers_ndarray of shape (n_clusters, n_features)
Cluster centers (if affinity != precomputed).
labels_ndarray of shape (n_samples,)
Labels of each point.
affinity_matrix_ndarray of shape (n_samples, n_samples)
Stores the affinity matrix used in fit.
n_iter_int
Number of iterations taken to converge. Notes For an example, see examples/cluster/plot_affinity_propagation.py. The algorithmic complexity of affinity propagation is quadratic in the number of points. When fit does not converge, cluster_centers_ becomes an empty array and all training samples will be labelled as -1. In addition, predict will then label every sample as -1. When all training samples have equal similarities and equal preferences, the assignment of cluster centers and labels depends on the preference. If the preference is smaller than the similarities, fit will result in a single cluster center and label 0 for every sample. Otherwise, every training sample becomes its own cluster center and is assigned a unique label. References Brendan J. Frey and Delbert Dueck, “Clustering by Passing Messages Between Data Points”, Science Feb. 2007 Examples >>> from sklearn.cluster import AffinityPropagation
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [4, 2], [4, 4], [4, 0]])
>>> clustering = AffinityPropagation(random_state=5).fit(X)
>>> clustering
AffinityPropagation(random_state=5)
>>> clustering.labels_
array([0, 0, 0, 1, 1, 1])
>>> clustering.predict([[0, 0], [4, 4]])
array([0, 1])
>>> clustering.cluster_centers_
array([[1, 2],
[4, 2]])
Methods
fit(X[, y]) Fit the clustering from features, or affinity matrix.
fit_predict(X[, y]) Fit the clustering from features or affinity matrix, and return cluster labels.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict the closest cluster each sample in X belongs to.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]
Fit the clustering from features, or affinity matrix. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
self
fit_predict(X, y=None) [source]
Fit the clustering from features or affinity matrix, and return cluster labels. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels.
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.
predict(X) [source]
Predict the closest cluster each sample in X belongs to. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
labelsndarray of shape (n_samples,)
Cluster labels.
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. | sklearn.modules.generated.sklearn.cluster.affinitypropagation#sklearn.cluster.AffinityPropagation |
sklearn.cluster.AffinityPropagation
class sklearn.cluster.AffinityPropagation(*, damping=0.5, max_iter=200, convergence_iter=15, copy=True, preference=None, affinity='euclidean', verbose=False, random_state='warn') [source]
Perform Affinity Propagation Clustering of data. Read more in the User Guide. Parameters
dampingfloat, default=0.5
Damping factor (between 0.5 and 1) is the extent to which the current value is maintained relative to incoming values (weighted 1 - damping). This in order to avoid numerical oscillations when updating these values (messages).
max_iterint, default=200
Maximum number of iterations.
convergence_iterint, default=15
Number of iterations with no change in the number of estimated clusters that stops the convergence.
copybool, default=True
Make a copy of input data.
preferencearray-like of shape (n_samples,) or float, default=None
Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, ie of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities.
affinity{‘euclidean’, ‘precomputed’}, default=’euclidean’
Which affinity to use. At the moment ‘precomputed’ and euclidean are supported. ‘euclidean’ uses the negative squared euclidean distance between points.
verbosebool, default=False
Whether to be verbose.
random_stateint, RandomState instance or None, default=0
Pseudo-random number generator to control the starting state. Use an int for reproducible results across function calls. See the Glossary. New in version 0.23: this parameter was previously hardcoded as 0. Attributes
cluster_centers_indices_ndarray of shape (n_clusters,)
Indices of cluster centers.
cluster_centers_ndarray of shape (n_clusters, n_features)
Cluster centers (if affinity != precomputed).
labels_ndarray of shape (n_samples,)
Labels of each point.
affinity_matrix_ndarray of shape (n_samples, n_samples)
Stores the affinity matrix used in fit.
n_iter_int
Number of iterations taken to converge. Notes For an example, see examples/cluster/plot_affinity_propagation.py. The algorithmic complexity of affinity propagation is quadratic in the number of points. When fit does not converge, cluster_centers_ becomes an empty array and all training samples will be labelled as -1. In addition, predict will then label every sample as -1. When all training samples have equal similarities and equal preferences, the assignment of cluster centers and labels depends on the preference. If the preference is smaller than the similarities, fit will result in a single cluster center and label 0 for every sample. Otherwise, every training sample becomes its own cluster center and is assigned a unique label. References Brendan J. Frey and Delbert Dueck, “Clustering by Passing Messages Between Data Points”, Science Feb. 2007 Examples >>> from sklearn.cluster import AffinityPropagation
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [4, 2], [4, 4], [4, 0]])
>>> clustering = AffinityPropagation(random_state=5).fit(X)
>>> clustering
AffinityPropagation(random_state=5)
>>> clustering.labels_
array([0, 0, 0, 1, 1, 1])
>>> clustering.predict([[0, 0], [4, 4]])
array([0, 1])
>>> clustering.cluster_centers_
array([[1, 2],
[4, 2]])
Methods
fit(X[, y]) Fit the clustering from features, or affinity matrix.
fit_predict(X[, y]) Fit the clustering from features or affinity matrix, and return cluster labels.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict the closest cluster each sample in X belongs to.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]
Fit the clustering from features, or affinity matrix. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
self
fit_predict(X, y=None) [source]
Fit the clustering from features or affinity matrix, and return cluster labels. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels.
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.
predict(X) [source]
Predict the closest cluster each sample in X belongs to. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
labelsndarray of shape (n_samples,)
Cluster labels.
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.
Examples using sklearn.cluster.AffinityPropagation
Demo of affinity propagation clustering algorithm
Comparing different clustering algorithms on toy datasets | sklearn.modules.generated.sklearn.cluster.affinitypropagation |
fit(X, y=None) [source]
Fit the clustering from features, or affinity matrix. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
self | sklearn.modules.generated.sklearn.cluster.affinitypropagation#sklearn.cluster.AffinityPropagation.fit |
fit_predict(X, y=None) [source]
Fit the clustering from features or affinity matrix, and return cluster labels. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse feature matrix is provided, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels. | sklearn.modules.generated.sklearn.cluster.affinitypropagation#sklearn.cluster.AffinityPropagation.fit_predict |
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. | sklearn.modules.generated.sklearn.cluster.affinitypropagation#sklearn.cluster.AffinityPropagation.get_params |
predict(X) [source]
Predict the closest cluster each sample in X belongs to. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns
labelsndarray of shape (n_samples,)
Cluster labels. | sklearn.modules.generated.sklearn.cluster.affinitypropagation#sklearn.cluster.AffinityPropagation.predict |
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. | sklearn.modules.generated.sklearn.cluster.affinitypropagation#sklearn.cluster.AffinityPropagation.set_params |
sklearn.cluster.affinity_propagation(S, *, preference=None, convergence_iter=15, max_iter=200, damping=0.5, copy=True, verbose=False, return_n_iter=False, random_state='warn') [source]
Perform Affinity Propagation Clustering of data. Read more in the User Guide. Parameters
Sarray-like of shape (n_samples, n_samples)
Matrix of similarities between points.
preferencearray-like of shape (n_samples,) or float, default=None
Preferences for each point - points with larger values of preferences are more likely to be chosen as exemplars. The number of exemplars, i.e. of clusters, is influenced by the input preferences value. If the preferences are not passed as arguments, they will be set to the median of the input similarities (resulting in a moderate number of clusters). For a smaller amount of clusters, this can be set to the minimum value of the similarities.
convergence_iterint, default=15
Number of iterations with no change in the number of estimated clusters that stops the convergence.
max_iterint, default=200
Maximum number of iterations
dampingfloat, default=0.5
Damping factor between 0.5 and 1.
copybool, default=True
If copy is False, the affinity matrix is modified inplace by the algorithm, for memory efficiency.
verbosebool, default=False
The verbosity level.
return_n_iterbool, default=False
Whether or not to return the number of iterations.
random_stateint, RandomState instance or None, default=0
Pseudo-random number generator to control the starting state. Use an int for reproducible results across function calls. See the Glossary. New in version 0.23: this parameter was previously hardcoded as 0. Returns
cluster_centers_indicesndarray of shape (n_clusters,)
Index of clusters centers.
labelsndarray of shape (n_samples,)
Cluster labels for each point.
n_iterint
Number of iterations run. Returned only if return_n_iter is set to True. Notes For an example, see examples/cluster/plot_affinity_propagation.py. When the algorithm does not converge, it returns an empty array as cluster_center_indices and -1 as label for each training sample. When all training samples have equal similarities and equal preferences, the assignment of cluster centers and labels depends on the preference. If the preference is smaller than the similarities, a single cluster center and label 0 for every sample will be returned. Otherwise, every training sample becomes its own cluster center and is assigned a unique label. References Brendan J. Frey and Delbert Dueck, “Clustering by Passing Messages Between Data Points”, Science Feb. 2007 | sklearn.modules.generated.sklearn.cluster.affinity_propagation#sklearn.cluster.affinity_propagation |
class sklearn.cluster.AgglomerativeClustering(n_clusters=2, *, affinity='euclidean', memory=None, connectivity=None, compute_full_tree='auto', linkage='ward', distance_threshold=None, compute_distances=False) [source]
Agglomerative Clustering Recursively merges the pair of clusters that minimally increases a given linkage distance. Read more in the User Guide. Parameters
n_clustersint or None, default=2
The number of clusters to find. It must be None if distance_threshold is not None.
affinitystr or callable, default=’euclidean’
Metric used to compute the linkage. Can be “euclidean”, “l1”, “l2”, “manhattan”, “cosine”, or “precomputed”. If linkage is “ward”, only “euclidean” is accepted. If “precomputed”, a distance matrix (instead of a similarity matrix) is needed as input for the fit method.
memorystr or object with the joblib.Memory interface, default=None
Used to cache the output of the computation of the tree. By default, no caching is done. If a string is given, it is the path to the caching directory.
connectivityarray-like or callable, default=None
Connectivity matrix. Defines for each sample the neighboring samples following a given structure of the data. This can be a connectivity matrix itself or a callable that transforms the data into a connectivity matrix, such as derived from kneighbors_graph. Default is None, i.e, the hierarchical clustering algorithm is unstructured.
compute_full_tree‘auto’ or bool, default=’auto’
Stop early the construction of the tree at n_clusters. This is useful to decrease computation time if the number of clusters is not small compared to the number of samples. This option is useful only when specifying a connectivity matrix. Note also that when varying the number of clusters and using caching, it may be advantageous to compute the full tree. It must be True if distance_threshold is not None. By default compute_full_tree is “auto”, which is equivalent to True when distance_threshold is not None or that n_clusters is inferior to the maximum between 100 or 0.02 * n_samples. Otherwise, “auto” is equivalent to False.
linkage{‘ward’, ‘complete’, ‘average’, ‘single’}, default=’ward’
Which linkage criterion to use. The linkage criterion determines which distance to use between sets of observation. The algorithm will merge the pairs of cluster that minimize this criterion. ‘ward’ minimizes the variance of the clusters being merged. ‘average’ uses the average of the distances of each observation of the two sets. ‘complete’ or ‘maximum’ linkage uses the maximum distances between all observations of the two sets. ‘single’ uses the minimum of the distances between all observations of the two sets. New in version 0.20: Added the ‘single’ option
distance_thresholdfloat, default=None
The linkage distance threshold above which, clusters will not be merged. If not None, n_clusters must be None and compute_full_tree must be True. New in version 0.21.
compute_distancesbool, default=False
Computes distances between clusters even if distance_threshold is not used. This can be used to make dendrogram visualization, but introduces a computational and memory overhead. New in version 0.24. Attributes
n_clusters_int
The number of clusters found by the algorithm. If distance_threshold=None, it will be equal to the given n_clusters.
labels_ndarray of shape (n_samples)
cluster labels for each point
n_leaves_int
Number of leaves in the hierarchical tree.
n_connected_components_int
The estimated number of connected components in the graph. New in version 0.21: n_connected_components_ was added to replace n_components_.
children_array-like of shape (n_samples-1, 2)
The children of each non-leaf node. Values less than n_samples correspond to leaves of the tree which are the original samples. A node i greater than or equal to n_samples is a non-leaf node and has children children_[i - n_samples]. Alternatively at the i-th iteration, children[i][0] and children[i][1] are merged to form node n_samples + i
distances_array-like of shape (n_nodes-1,)
Distances between nodes in the corresponding place in children_. Only computed if distance_threshold is used or compute_distances is set to True. Examples >>> from sklearn.cluster import AgglomerativeClustering
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [4, 2], [4, 4], [4, 0]])
>>> clustering = AgglomerativeClustering().fit(X)
>>> clustering
AgglomerativeClustering()
>>> clustering.labels_
array([1, 1, 1, 0, 0, 0])
Methods
fit(X[, y]) Fit the hierarchical clustering from features, or distance matrix.
fit_predict(X[, y]) Fit the hierarchical clustering from features or distance matrix, and return cluster labels.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]
Fit the hierarchical clustering from features, or distance matrix. Parameters
Xarray-like, shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, or distances between instances if affinity='precomputed'.
yIgnored
Not used, present here for API consistency by convention. Returns
self
fit_predict(X, y=None) [source]
Fit the hierarchical clustering from features or distance matrix, and return cluster labels. Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, or distances between instances if affinity='precomputed'.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels.
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.
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. | sklearn.modules.generated.sklearn.cluster.agglomerativeclustering#sklearn.cluster.AgglomerativeClustering |
sklearn.cluster.AgglomerativeClustering
class sklearn.cluster.AgglomerativeClustering(n_clusters=2, *, affinity='euclidean', memory=None, connectivity=None, compute_full_tree='auto', linkage='ward', distance_threshold=None, compute_distances=False) [source]
Agglomerative Clustering Recursively merges the pair of clusters that minimally increases a given linkage distance. Read more in the User Guide. Parameters
n_clustersint or None, default=2
The number of clusters to find. It must be None if distance_threshold is not None.
affinitystr or callable, default=’euclidean’
Metric used to compute the linkage. Can be “euclidean”, “l1”, “l2”, “manhattan”, “cosine”, or “precomputed”. If linkage is “ward”, only “euclidean” is accepted. If “precomputed”, a distance matrix (instead of a similarity matrix) is needed as input for the fit method.
memorystr or object with the joblib.Memory interface, default=None
Used to cache the output of the computation of the tree. By default, no caching is done. If a string is given, it is the path to the caching directory.
connectivityarray-like or callable, default=None
Connectivity matrix. Defines for each sample the neighboring samples following a given structure of the data. This can be a connectivity matrix itself or a callable that transforms the data into a connectivity matrix, such as derived from kneighbors_graph. Default is None, i.e, the hierarchical clustering algorithm is unstructured.
compute_full_tree‘auto’ or bool, default=’auto’
Stop early the construction of the tree at n_clusters. This is useful to decrease computation time if the number of clusters is not small compared to the number of samples. This option is useful only when specifying a connectivity matrix. Note also that when varying the number of clusters and using caching, it may be advantageous to compute the full tree. It must be True if distance_threshold is not None. By default compute_full_tree is “auto”, which is equivalent to True when distance_threshold is not None or that n_clusters is inferior to the maximum between 100 or 0.02 * n_samples. Otherwise, “auto” is equivalent to False.
linkage{‘ward’, ‘complete’, ‘average’, ‘single’}, default=’ward’
Which linkage criterion to use. The linkage criterion determines which distance to use between sets of observation. The algorithm will merge the pairs of cluster that minimize this criterion. ‘ward’ minimizes the variance of the clusters being merged. ‘average’ uses the average of the distances of each observation of the two sets. ‘complete’ or ‘maximum’ linkage uses the maximum distances between all observations of the two sets. ‘single’ uses the minimum of the distances between all observations of the two sets. New in version 0.20: Added the ‘single’ option
distance_thresholdfloat, default=None
The linkage distance threshold above which, clusters will not be merged. If not None, n_clusters must be None and compute_full_tree must be True. New in version 0.21.
compute_distancesbool, default=False
Computes distances between clusters even if distance_threshold is not used. This can be used to make dendrogram visualization, but introduces a computational and memory overhead. New in version 0.24. Attributes
n_clusters_int
The number of clusters found by the algorithm. If distance_threshold=None, it will be equal to the given n_clusters.
labels_ndarray of shape (n_samples)
cluster labels for each point
n_leaves_int
Number of leaves in the hierarchical tree.
n_connected_components_int
The estimated number of connected components in the graph. New in version 0.21: n_connected_components_ was added to replace n_components_.
children_array-like of shape (n_samples-1, 2)
The children of each non-leaf node. Values less than n_samples correspond to leaves of the tree which are the original samples. A node i greater than or equal to n_samples is a non-leaf node and has children children_[i - n_samples]. Alternatively at the i-th iteration, children[i][0] and children[i][1] are merged to form node n_samples + i
distances_array-like of shape (n_nodes-1,)
Distances between nodes in the corresponding place in children_. Only computed if distance_threshold is used or compute_distances is set to True. Examples >>> from sklearn.cluster import AgglomerativeClustering
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [4, 2], [4, 4], [4, 0]])
>>> clustering = AgglomerativeClustering().fit(X)
>>> clustering
AgglomerativeClustering()
>>> clustering.labels_
array([1, 1, 1, 0, 0, 0])
Methods
fit(X[, y]) Fit the hierarchical clustering from features, or distance matrix.
fit_predict(X[, y]) Fit the hierarchical clustering from features or distance matrix, and return cluster labels.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]
Fit the hierarchical clustering from features, or distance matrix. Parameters
Xarray-like, shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, or distances between instances if affinity='precomputed'.
yIgnored
Not used, present here for API consistency by convention. Returns
self
fit_predict(X, y=None) [source]
Fit the hierarchical clustering from features or distance matrix, and return cluster labels. Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, or distances between instances if affinity='precomputed'.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels.
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.
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.
Examples using sklearn.cluster.AgglomerativeClustering
Plot Hierarchical Clustering Dendrogram
Agglomerative clustering with and without structure
Various Agglomerative Clustering on a 2D embedding of digits
A demo of structured Ward hierarchical clustering on an image of coins
Hierarchical clustering: structured vs unstructured ward
Agglomerative clustering with different metrics
Inductive Clustering
Comparing different hierarchical linkage methods on toy datasets
Comparing different clustering algorithms on toy datasets | sklearn.modules.generated.sklearn.cluster.agglomerativeclustering |
fit(X, y=None) [source]
Fit the hierarchical clustering from features, or distance matrix. Parameters
Xarray-like, shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, or distances between instances if affinity='precomputed'.
yIgnored
Not used, present here for API consistency by convention. Returns
self | sklearn.modules.generated.sklearn.cluster.agglomerativeclustering#sklearn.cluster.AgglomerativeClustering.fit |
fit_predict(X, y=None) [source]
Fit the hierarchical clustering from features or distance matrix, and return cluster labels. Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, or distances between instances if affinity='precomputed'.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels. | sklearn.modules.generated.sklearn.cluster.agglomerativeclustering#sklearn.cluster.AgglomerativeClustering.fit_predict |
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. | sklearn.modules.generated.sklearn.cluster.agglomerativeclustering#sklearn.cluster.AgglomerativeClustering.get_params |
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. | sklearn.modules.generated.sklearn.cluster.agglomerativeclustering#sklearn.cluster.AgglomerativeClustering.set_params |
class sklearn.cluster.Birch(*, threshold=0.5, branching_factor=50, n_clusters=3, compute_labels=True, copy=True) [source]
Implements the Birch clustering algorithm. It is a memory-efficient, online-learning algorithm provided as an alternative to MiniBatchKMeans. It constructs a tree data structure with the cluster centroids being read off the leaf. These can be either the final cluster centroids or can be provided as input to another clustering algorithm such as AgglomerativeClustering. Read more in the User Guide. New in version 0.16. Parameters
thresholdfloat, default=0.5
The radius of the subcluster obtained by merging a new sample and the closest subcluster should be lesser than the threshold. Otherwise a new subcluster is started. Setting this value to be very low promotes splitting and vice-versa.
branching_factorint, default=50
Maximum number of CF subclusters in each node. If a new samples enters such that the number of subclusters exceed the branching_factor then that node is split into two nodes with the subclusters redistributed in each. The parent subcluster of that node is removed and two new subclusters are added as parents of the 2 split nodes.
n_clustersint, instance of sklearn.cluster model, default=3
Number of clusters after the final clustering step, which treats the subclusters from the leaves as new samples.
None : the final clustering step is not performed and the subclusters are returned as they are.
sklearn.cluster Estimator : If a model is provided, the model is fit treating the subclusters as new samples and the initial data is mapped to the label of the closest subcluster.
int : the model fit is AgglomerativeClustering with n_clusters set to be equal to the int.
compute_labelsbool, default=True
Whether or not to compute labels for each fit.
copybool, default=True
Whether or not to make a copy of the given data. If set to False, the initial data will be overwritten. Attributes
root__CFNode
Root of the CFTree.
dummy_leaf__CFNode
Start pointer to all the leaves.
subcluster_centers_ndarray
Centroids of all subclusters read directly from the leaves.
subcluster_labels_ndarray
Labels assigned to the centroids of the subclusters after they are clustered globally.
labels_ndarray of shape (n_samples,)
Array of labels assigned to the input data. if partial_fit is used instead of fit, they are assigned to the last batch of data. See also
MiniBatchKMeans
Alternative implementation that does incremental updates of the centers’ positions using mini-batches. Notes The tree data structure consists of nodes with each node consisting of a number of subclusters. The maximum number of subclusters in a node is determined by the branching factor. Each subcluster maintains a linear sum, squared sum and the number of samples in that subcluster. In addition, each subcluster can also have a node as its child, if the subcluster is not a member of a leaf node. For a new point entering the root, it is merged with the subcluster closest to it and the linear sum, squared sum and the number of samples of that subcluster are updated. This is done recursively till the properties of the leaf node are updated. References Tian Zhang, Raghu Ramakrishnan, Maron Livny BIRCH: An efficient data clustering method for large databases. https://www.cs.sfu.ca/CourseCentral/459/han/papers/zhang96.pdf
Roberto Perdisci JBirch - Java implementation of BIRCH clustering algorithm https://code.google.com/archive/p/jbirch
Examples >>> from sklearn.cluster import Birch
>>> X = [[0, 1], [0.3, 1], [-0.3, 1], [0, -1], [0.3, -1], [-0.3, -1]]
>>> brc = Birch(n_clusters=None)
>>> brc.fit(X)
Birch(n_clusters=None)
>>> brc.predict(X)
array([0, 0, 0, 1, 1, 1])
Methods
fit(X[, y]) Build a CF Tree for the input data.
fit_predict(X[, y]) Perform clustering on X and returns cluster labels.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
partial_fit([X, y]) Online learning.
predict(X) Predict data using the centroids_ of subclusters.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform X into subcluster centroids dimension.
fit(X, y=None) [source]
Build a CF Tree for the input data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present here for API consistency by convention. Returns
self
Fitted estimator.
fit_predict(X, y=None) [source]
Perform clustering on X and returns cluster labels. Parameters
Xarray-like of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present for API consistency by convention. Returns
labelsndarray of shape (n_samples,), dtype=np.int64
Cluster labels.
fit_transform(X, y=None, **fit_params) [source]
Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters
Xarray-like of shape (n_samples, n_features)
Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
**fit_paramsdict
Additional fit parameters. Returns
X_newndarray array of shape (n_samples, n_features_new)
Transformed array.
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.
partial_fit(X=None, y=None) [source]
Online learning. Prevents rebuilding of CFTree from scratch. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), default=None
Input data. If X is not provided, only the global clustering step is done.
yIgnored
Not used, present here for API consistency by convention. Returns
self
Fitted estimator.
predict(X) [source]
Predict data using the centroids_ of subclusters. Avoid computation of the row norms of X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Input data. Returns
labelsndarray of shape(n_samples,)
Labelled data.
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.
transform(X) [source]
Transform X into subcluster centroids dimension. Each dimension represents the distance from the sample point to each cluster centroid. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Input data. Returns
X_trans{array-like, sparse matrix} of shape (n_samples, n_clusters)
Transformed data. | sklearn.modules.generated.sklearn.cluster.birch#sklearn.cluster.Birch |
sklearn.cluster.Birch
class sklearn.cluster.Birch(*, threshold=0.5, branching_factor=50, n_clusters=3, compute_labels=True, copy=True) [source]
Implements the Birch clustering algorithm. It is a memory-efficient, online-learning algorithm provided as an alternative to MiniBatchKMeans. It constructs a tree data structure with the cluster centroids being read off the leaf. These can be either the final cluster centroids or can be provided as input to another clustering algorithm such as AgglomerativeClustering. Read more in the User Guide. New in version 0.16. Parameters
thresholdfloat, default=0.5
The radius of the subcluster obtained by merging a new sample and the closest subcluster should be lesser than the threshold. Otherwise a new subcluster is started. Setting this value to be very low promotes splitting and vice-versa.
branching_factorint, default=50
Maximum number of CF subclusters in each node. If a new samples enters such that the number of subclusters exceed the branching_factor then that node is split into two nodes with the subclusters redistributed in each. The parent subcluster of that node is removed and two new subclusters are added as parents of the 2 split nodes.
n_clustersint, instance of sklearn.cluster model, default=3
Number of clusters after the final clustering step, which treats the subclusters from the leaves as new samples.
None : the final clustering step is not performed and the subclusters are returned as they are.
sklearn.cluster Estimator : If a model is provided, the model is fit treating the subclusters as new samples and the initial data is mapped to the label of the closest subcluster.
int : the model fit is AgglomerativeClustering with n_clusters set to be equal to the int.
compute_labelsbool, default=True
Whether or not to compute labels for each fit.
copybool, default=True
Whether or not to make a copy of the given data. If set to False, the initial data will be overwritten. Attributes
root__CFNode
Root of the CFTree.
dummy_leaf__CFNode
Start pointer to all the leaves.
subcluster_centers_ndarray
Centroids of all subclusters read directly from the leaves.
subcluster_labels_ndarray
Labels assigned to the centroids of the subclusters after they are clustered globally.
labels_ndarray of shape (n_samples,)
Array of labels assigned to the input data. if partial_fit is used instead of fit, they are assigned to the last batch of data. See also
MiniBatchKMeans
Alternative implementation that does incremental updates of the centers’ positions using mini-batches. Notes The tree data structure consists of nodes with each node consisting of a number of subclusters. The maximum number of subclusters in a node is determined by the branching factor. Each subcluster maintains a linear sum, squared sum and the number of samples in that subcluster. In addition, each subcluster can also have a node as its child, if the subcluster is not a member of a leaf node. For a new point entering the root, it is merged with the subcluster closest to it and the linear sum, squared sum and the number of samples of that subcluster are updated. This is done recursively till the properties of the leaf node are updated. References Tian Zhang, Raghu Ramakrishnan, Maron Livny BIRCH: An efficient data clustering method for large databases. https://www.cs.sfu.ca/CourseCentral/459/han/papers/zhang96.pdf
Roberto Perdisci JBirch - Java implementation of BIRCH clustering algorithm https://code.google.com/archive/p/jbirch
Examples >>> from sklearn.cluster import Birch
>>> X = [[0, 1], [0.3, 1], [-0.3, 1], [0, -1], [0.3, -1], [-0.3, -1]]
>>> brc = Birch(n_clusters=None)
>>> brc.fit(X)
Birch(n_clusters=None)
>>> brc.predict(X)
array([0, 0, 0, 1, 1, 1])
Methods
fit(X[, y]) Build a CF Tree for the input data.
fit_predict(X[, y]) Perform clustering on X and returns cluster labels.
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
partial_fit([X, y]) Online learning.
predict(X) Predict data using the centroids_ of subclusters.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform X into subcluster centroids dimension.
fit(X, y=None) [source]
Build a CF Tree for the input data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present here for API consistency by convention. Returns
self
Fitted estimator.
fit_predict(X, y=None) [source]
Perform clustering on X and returns cluster labels. Parameters
Xarray-like of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present for API consistency by convention. Returns
labelsndarray of shape (n_samples,), dtype=np.int64
Cluster labels.
fit_transform(X, y=None, **fit_params) [source]
Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters
Xarray-like of shape (n_samples, n_features)
Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
**fit_paramsdict
Additional fit parameters. Returns
X_newndarray array of shape (n_samples, n_features_new)
Transformed array.
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.
partial_fit(X=None, y=None) [source]
Online learning. Prevents rebuilding of CFTree from scratch. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), default=None
Input data. If X is not provided, only the global clustering step is done.
yIgnored
Not used, present here for API consistency by convention. Returns
self
Fitted estimator.
predict(X) [source]
Predict data using the centroids_ of subclusters. Avoid computation of the row norms of X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Input data. Returns
labelsndarray of shape(n_samples,)
Labelled data.
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.
transform(X) [source]
Transform X into subcluster centroids dimension. Each dimension represents the distance from the sample point to each cluster centroid. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Input data. Returns
X_trans{array-like, sparse matrix} of shape (n_samples, n_clusters)
Transformed data.
Examples using sklearn.cluster.Birch
Compare BIRCH and MiniBatchKMeans
Comparing different clustering algorithms on toy datasets | sklearn.modules.generated.sklearn.cluster.birch |
fit(X, y=None) [source]
Build a CF Tree for the input data. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present here for API consistency by convention. Returns
self
Fitted estimator. | sklearn.modules.generated.sklearn.cluster.birch#sklearn.cluster.Birch.fit |
fit_predict(X, y=None) [source]
Perform clustering on X and returns cluster labels. Parameters
Xarray-like of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present for API consistency by convention. Returns
labelsndarray of shape (n_samples,), dtype=np.int64
Cluster labels. | sklearn.modules.generated.sklearn.cluster.birch#sklearn.cluster.Birch.fit_predict |
fit_transform(X, y=None, **fit_params) [source]
Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters
Xarray-like of shape (n_samples, n_features)
Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
**fit_paramsdict
Additional fit parameters. Returns
X_newndarray array of shape (n_samples, n_features_new)
Transformed array. | sklearn.modules.generated.sklearn.cluster.birch#sklearn.cluster.Birch.fit_transform |
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. | sklearn.modules.generated.sklearn.cluster.birch#sklearn.cluster.Birch.get_params |
partial_fit(X=None, y=None) [source]
Online learning. Prevents rebuilding of CFTree from scratch. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), default=None
Input data. If X is not provided, only the global clustering step is done.
yIgnored
Not used, present here for API consistency by convention. Returns
self
Fitted estimator. | sklearn.modules.generated.sklearn.cluster.birch#sklearn.cluster.Birch.partial_fit |
predict(X) [source]
Predict data using the centroids_ of subclusters. Avoid computation of the row norms of X. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Input data. Returns
labelsndarray of shape(n_samples,)
Labelled data. | sklearn.modules.generated.sklearn.cluster.birch#sklearn.cluster.Birch.predict |
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. | sklearn.modules.generated.sklearn.cluster.birch#sklearn.cluster.Birch.set_params |
transform(X) [source]
Transform X into subcluster centroids dimension. Each dimension represents the distance from the sample point to each cluster centroid. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Input data. Returns
X_trans{array-like, sparse matrix} of shape (n_samples, n_clusters)
Transformed data. | sklearn.modules.generated.sklearn.cluster.birch#sklearn.cluster.Birch.transform |
sklearn.cluster.cluster_optics_dbscan(*, reachability, core_distances, ordering, eps) [source]
Performs DBSCAN extraction for an arbitrary epsilon. Extracting the clusters runs in linear time. Note that this results in labels_ which are close to a DBSCAN with similar settings and eps, only if eps is close to max_eps. Parameters
reachabilityarray of shape (n_samples,)
Reachability distances calculated by OPTICS (reachability_)
core_distancesarray of shape (n_samples,)
Distances at which points become core (core_distances_)
orderingarray of shape (n_samples,)
OPTICS ordered point indices (ordering_)
epsfloat
DBSCAN eps parameter. Must be set to < max_eps. Results will be close to DBSCAN algorithm if eps and max_eps are close to one another. Returns
labels_array of shape (n_samples,)
The estimated labels. | sklearn.modules.generated.sklearn.cluster.cluster_optics_dbscan#sklearn.cluster.cluster_optics_dbscan |
sklearn.cluster.cluster_optics_xi(*, reachability, predecessor, ordering, min_samples, min_cluster_size=None, xi=0.05, predecessor_correction=True) [source]
Automatically extract clusters according to the Xi-steep method. Parameters
reachabilityndarray of shape (n_samples,)
Reachability distances calculated by OPTICS (reachability_)
predecessorndarray of shape (n_samples,)
Predecessors calculated by OPTICS.
orderingndarray of shape (n_samples,)
OPTICS ordered point indices (ordering_)
min_samplesint > 1 or float between 0 and 1
The same as the min_samples given to OPTICS. Up and down steep regions can’t have more then min_samples consecutive non-steep points. Expressed as an absolute number or a fraction of the number of samples (rounded to be at least 2).
min_cluster_sizeint > 1 or float between 0 and 1, default=None
Minimum number of samples in an OPTICS cluster, expressed as an absolute number or a fraction of the number of samples (rounded to be at least 2). If None, the value of min_samples is used instead.
xifloat between 0 and 1, default=0.05
Determines the minimum steepness on the reachability plot that constitutes a cluster boundary. For example, an upwards point in the reachability plot is defined by the ratio from one point to its successor being at most 1-xi.
predecessor_correctionbool, default=True
Correct clusters based on the calculated predecessors. Returns
labelsndarray of shape (n_samples,)
The labels assigned to samples. Points which are not included in any cluster are labeled as -1.
clustersndarray of shape (n_clusters, 2)
The list of clusters in the form of [start, end] in each row, with all indices inclusive. The clusters are ordered according to (end,
-start) (ascending) so that larger clusters encompassing smaller clusters come after such nested smaller clusters. Since labels does not reflect the hierarchy, usually len(clusters) >
np.unique(labels). | sklearn.modules.generated.sklearn.cluster.cluster_optics_xi#sklearn.cluster.cluster_optics_xi |
sklearn.cluster.compute_optics_graph(X, *, min_samples, max_eps, metric, p, metric_params, algorithm, leaf_size, n_jobs) [source]
Computes the OPTICS reachability graph. Read more in the User Guide. Parameters
Xndarray of shape (n_samples, n_features), or (n_samples, n_samples) if metric=’precomputed’.
A feature array, or array of distances between samples if metric=’precomputed’
min_samplesint > 1 or float between 0 and 1
The number of samples in a neighborhood for a point to be considered as a core point. Expressed as an absolute number or a fraction of the number of samples (rounded to be at least 2).
max_epsfloat, default=np.inf
The maximum distance between two samples for one to be considered as in the neighborhood of the other. Default value of np.inf will identify clusters across all scales; reducing max_eps will result in shorter run times.
metricstr or callable, default=’minkowski’
Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy’s metrics, but is less efficient than passing the metric name as a string. If metric is “precomputed”, X is assumed to be a distance matrix and must be square. Valid values for metric are: from scikit-learn: [‘cityblock’, ‘cosine’, ‘euclidean’, ‘l1’, ‘l2’, ‘manhattan’] from scipy.spatial.distance: [‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘correlation’, ‘dice’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘yule’] See the documentation for scipy.spatial.distance for details on these metrics.
pint, default=2
Parameter for the Minkowski metric from pairwise_distances. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
metric_paramsdict, default=None
Additional keyword arguments for the metric function.
algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’
Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree
‘kd_tree’ will use KDTree
‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. (default) Note: fitting on sparse input will override the setting of this parameter, using brute force.
leaf_sizeint, default=30
Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.
n_jobsint, default=None
The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Returns
ordering_array of shape (n_samples,)
The cluster ordered list of sample indices.
core_distances_array of shape (n_samples,)
Distance at which each sample becomes a core point, indexed by object order. Points which will never be core have a distance of inf. Use clust.core_distances_[clust.ordering_] to access in cluster order.
reachability_array of shape (n_samples,)
Reachability distances per sample, indexed by object order. Use clust.reachability_[clust.ordering_] to access in cluster order.
predecessor_array of shape (n_samples,)
Point that a sample was reached from, indexed by object order. Seed points have a predecessor of -1. References
1
Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, and Jörg Sander. “OPTICS: ordering points to identify the clustering structure.” ACM SIGMOD Record 28, no. 2 (1999): 49-60. | sklearn.modules.generated.sklearn.cluster.compute_optics_graph#sklearn.cluster.compute_optics_graph |
class sklearn.cluster.DBSCAN(eps=0.5, *, min_samples=5, metric='euclidean', metric_params=None, algorithm='auto', leaf_size=30, p=None, n_jobs=None) [source]
Perform DBSCAN clustering from vector array or distance matrix. DBSCAN - Density-Based Spatial Clustering of Applications with Noise. Finds core samples of high density and expands clusters from them. Good for data which contains clusters of similar density. Read more in the User Guide. Parameters
epsfloat, default=0.5
The maximum distance between two samples for one to be considered as in the neighborhood of the other. This is not a maximum bound on the distances of points within a cluster. This is the most important DBSCAN parameter to choose appropriately for your data set and distance function.
min_samplesint, default=5
The number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself.
metricstring, or callable, default=’euclidean’
The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by sklearn.metrics.pairwise_distances for its metric parameter. If metric is “precomputed”, X is assumed to be a distance matrix and must be square. X may be a Glossary, in which case only “nonzero” elements may be considered neighbors for DBSCAN. New in version 0.17: metric precomputed to accept precomputed sparse matrix.
metric_paramsdict, default=None
Additional keyword arguments for the metric function. New in version 0.19.
algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’
The algorithm to be used by the NearestNeighbors module to compute pointwise distances and find nearest neighbors. See NearestNeighbors module documentation for details.
leaf_sizeint, default=30
Leaf size passed to BallTree or cKDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.
pfloat, default=None
The power of the Minkowski metric to be used to calculate distance between points. If None, then p=2 (equivalent to the Euclidean distance).
n_jobsint, default=None
The number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes
core_sample_indices_ndarray of shape (n_core_samples,)
Indices of core samples.
components_ndarray of shape (n_core_samples, n_features)
Copy of each core sample found by training.
labels_ndarray of shape (n_samples)
Cluster labels for each point in the dataset given to fit(). Noisy samples are given the label -1. See also
OPTICS
A similar clustering at multiple values of eps. Our implementation is optimized for memory usage. Notes For an example, see examples/cluster/plot_dbscan.py. This implementation bulk-computes all neighborhood queries, which increases the memory complexity to O(n.d) where d is the average number of neighbors, while original DBSCAN had memory complexity O(n). It may attract a higher memory complexity when querying these nearest neighborhoods, depending on the algorithm. One way to avoid the query complexity is to pre-compute sparse neighborhoods in chunks using NearestNeighbors.radius_neighbors_graph with mode='distance', then using metric='precomputed' here. Another way to reduce memory and computation time is to remove (near-)duplicate points and use sample_weight instead. cluster.OPTICS provides a similar clustering with lower memory usage. References Ester, M., H. P. Kriegel, J. Sander, and X. Xu, “A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise”. In: Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017). DBSCAN revisited, revisited: why and how you should (still) use DBSCAN. ACM Transactions on Database Systems (TODS), 42(3), 19. Examples >>> from sklearn.cluster import DBSCAN
>>> import numpy as np
>>> X = np.array([[1, 2], [2, 2], [2, 3],
... [8, 7], [8, 8], [25, 80]])
>>> clustering = DBSCAN(eps=3, min_samples=2).fit(X)
>>> clustering.labels_
array([ 0, 0, 0, 1, 1, -1])
>>> clustering
DBSCAN(eps=3, min_samples=2)
Methods
fit(X[, y, sample_weight]) Perform DBSCAN clustering from features, or distance matrix.
fit_predict(X[, y, sample_weight]) Perform DBSCAN clustering from features or distance matrix, and return cluster labels.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None, sample_weight=None) [source]
Perform DBSCAN clustering from features, or distance matrix. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or (n_samples, n_samples)
Training instances to cluster, or distances between instances if metric='precomputed'. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.
sample_weightarray-like of shape (n_samples,), default=None
Weight of each sample, such that a sample with a weight of at least min_samples is by itself a core sample; a sample with a negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1.
yIgnored
Not used, present here for API consistency by convention. Returns
self
fit_predict(X, y=None, sample_weight=None) [source]
Perform DBSCAN clustering from features or distance matrix, and return cluster labels. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or (n_samples, n_samples)
Training instances to cluster, or distances between instances if metric='precomputed'. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.
sample_weightarray-like of shape (n_samples,), default=None
Weight of each sample, such that a sample with a weight of at least min_samples is by itself a core sample; a sample with a negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels. Noisy samples are given the label -1.
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.
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. | sklearn.modules.generated.sklearn.cluster.dbscan#sklearn.cluster.DBSCAN |
sklearn.cluster.DBSCAN
class sklearn.cluster.DBSCAN(eps=0.5, *, min_samples=5, metric='euclidean', metric_params=None, algorithm='auto', leaf_size=30, p=None, n_jobs=None) [source]
Perform DBSCAN clustering from vector array or distance matrix. DBSCAN - Density-Based Spatial Clustering of Applications with Noise. Finds core samples of high density and expands clusters from them. Good for data which contains clusters of similar density. Read more in the User Guide. Parameters
epsfloat, default=0.5
The maximum distance between two samples for one to be considered as in the neighborhood of the other. This is not a maximum bound on the distances of points within a cluster. This is the most important DBSCAN parameter to choose appropriately for your data set and distance function.
min_samplesint, default=5
The number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself.
metricstring, or callable, default=’euclidean’
The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by sklearn.metrics.pairwise_distances for its metric parameter. If metric is “precomputed”, X is assumed to be a distance matrix and must be square. X may be a Glossary, in which case only “nonzero” elements may be considered neighbors for DBSCAN. New in version 0.17: metric precomputed to accept precomputed sparse matrix.
metric_paramsdict, default=None
Additional keyword arguments for the metric function. New in version 0.19.
algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’
The algorithm to be used by the NearestNeighbors module to compute pointwise distances and find nearest neighbors. See NearestNeighbors module documentation for details.
leaf_sizeint, default=30
Leaf size passed to BallTree or cKDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.
pfloat, default=None
The power of the Minkowski metric to be used to calculate distance between points. If None, then p=2 (equivalent to the Euclidean distance).
n_jobsint, default=None
The number of parallel jobs to run. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes
core_sample_indices_ndarray of shape (n_core_samples,)
Indices of core samples.
components_ndarray of shape (n_core_samples, n_features)
Copy of each core sample found by training.
labels_ndarray of shape (n_samples)
Cluster labels for each point in the dataset given to fit(). Noisy samples are given the label -1. See also
OPTICS
A similar clustering at multiple values of eps. Our implementation is optimized for memory usage. Notes For an example, see examples/cluster/plot_dbscan.py. This implementation bulk-computes all neighborhood queries, which increases the memory complexity to O(n.d) where d is the average number of neighbors, while original DBSCAN had memory complexity O(n). It may attract a higher memory complexity when querying these nearest neighborhoods, depending on the algorithm. One way to avoid the query complexity is to pre-compute sparse neighborhoods in chunks using NearestNeighbors.radius_neighbors_graph with mode='distance', then using metric='precomputed' here. Another way to reduce memory and computation time is to remove (near-)duplicate points and use sample_weight instead. cluster.OPTICS provides a similar clustering with lower memory usage. References Ester, M., H. P. Kriegel, J. Sander, and X. Xu, “A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise”. In: Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017). DBSCAN revisited, revisited: why and how you should (still) use DBSCAN. ACM Transactions on Database Systems (TODS), 42(3), 19. Examples >>> from sklearn.cluster import DBSCAN
>>> import numpy as np
>>> X = np.array([[1, 2], [2, 2], [2, 3],
... [8, 7], [8, 8], [25, 80]])
>>> clustering = DBSCAN(eps=3, min_samples=2).fit(X)
>>> clustering.labels_
array([ 0, 0, 0, 1, 1, -1])
>>> clustering
DBSCAN(eps=3, min_samples=2)
Methods
fit(X[, y, sample_weight]) Perform DBSCAN clustering from features, or distance matrix.
fit_predict(X[, y, sample_weight]) Perform DBSCAN clustering from features or distance matrix, and return cluster labels.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None, sample_weight=None) [source]
Perform DBSCAN clustering from features, or distance matrix. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or (n_samples, n_samples)
Training instances to cluster, or distances between instances if metric='precomputed'. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.
sample_weightarray-like of shape (n_samples,), default=None
Weight of each sample, such that a sample with a weight of at least min_samples is by itself a core sample; a sample with a negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1.
yIgnored
Not used, present here for API consistency by convention. Returns
self
fit_predict(X, y=None, sample_weight=None) [source]
Perform DBSCAN clustering from features or distance matrix, and return cluster labels. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or (n_samples, n_samples)
Training instances to cluster, or distances between instances if metric='precomputed'. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.
sample_weightarray-like of shape (n_samples,), default=None
Weight of each sample, such that a sample with a weight of at least min_samples is by itself a core sample; a sample with a negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels. Noisy samples are given the label -1.
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.
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.
Examples using sklearn.cluster.DBSCAN
Demo of DBSCAN clustering algorithm
Comparing different clustering algorithms on toy datasets | sklearn.modules.generated.sklearn.cluster.dbscan |
sklearn.cluster.dbscan(X, eps=0.5, *, min_samples=5, metric='minkowski', metric_params=None, algorithm='auto', leaf_size=30, p=2, sample_weight=None, n_jobs=None) [source]
Perform DBSCAN clustering from vector array or distance matrix. Read more in the User Guide. Parameters
X{array-like, sparse (CSR) matrix} of shape (n_samples, n_features) or (n_samples, n_samples)
A feature array, or array of distances between samples if metric='precomputed'.
epsfloat, default=0.5
The maximum distance between two samples for one to be considered as in the neighborhood of the other. This is not a maximum bound on the distances of points within a cluster. This is the most important DBSCAN parameter to choose appropriately for your data set and distance function.
min_samplesint, default=5
The number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself.
metricstr or callable, default=’minkowski’
The metric to use when calculating distance between instances in a feature array. If metric is a string or callable, it must be one of the options allowed by sklearn.metrics.pairwise_distances for its metric parameter. If metric is “precomputed”, X is assumed to be a distance matrix and must be square during fit. X may be a sparse graph, in which case only “nonzero” elements may be considered neighbors.
metric_paramsdict, default=None
Additional keyword arguments for the metric function. New in version 0.19.
algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’
The algorithm to be used by the NearestNeighbors module to compute pointwise distances and find nearest neighbors. See NearestNeighbors module documentation for details.
leaf_sizeint, default=30
Leaf size passed to BallTree or cKDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.
pfloat, default=2
The power of the Minkowski metric to be used to calculate distance between points.
sample_weightarray-like of shape (n_samples,), default=None
Weight of each sample, such that a sample with a weight of at least min_samples is by itself a core sample; a sample with negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1.
n_jobsint, default=None
The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. If precomputed distance are used, parallel execution is not available and thus n_jobs will have no effect. Returns
core_samplesndarray of shape (n_core_samples,)
Indices of core samples.
labelsndarray of shape (n_samples,)
Cluster labels for each point. Noisy samples are given the label -1. See also
DBSCAN
An estimator interface for this clustering algorithm.
OPTICS
A similar estimator interface clustering at multiple values of eps. Our implementation is optimized for memory usage. Notes For an example, see examples/cluster/plot_dbscan.py. This implementation bulk-computes all neighborhood queries, which increases the memory complexity to O(n.d) where d is the average number of neighbors, while original DBSCAN had memory complexity O(n). It may attract a higher memory complexity when querying these nearest neighborhoods, depending on the algorithm. One way to avoid the query complexity is to pre-compute sparse neighborhoods in chunks using NearestNeighbors.radius_neighbors_graph with mode='distance', then using metric='precomputed' here. Another way to reduce memory and computation time is to remove (near-)duplicate points and use sample_weight instead. cluster.optics provides a similar clustering with lower memory usage. References Ester, M., H. P. Kriegel, J. Sander, and X. Xu, “A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise”. In: Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017). DBSCAN revisited, revisited: why and how you should (still) use DBSCAN. ACM Transactions on Database Systems (TODS), 42(3), 19. | sklearn.modules.generated.dbscan-function#sklearn.cluster.dbscan |
fit(X, y=None, sample_weight=None) [source]
Perform DBSCAN clustering from features, or distance matrix. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or (n_samples, n_samples)
Training instances to cluster, or distances between instances if metric='precomputed'. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.
sample_weightarray-like of shape (n_samples,), default=None
Weight of each sample, such that a sample with a weight of at least min_samples is by itself a core sample; a sample with a negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1.
yIgnored
Not used, present here for API consistency by convention. Returns
self | sklearn.modules.generated.sklearn.cluster.dbscan#sklearn.cluster.DBSCAN.fit |
fit_predict(X, y=None, sample_weight=None) [source]
Perform DBSCAN clustering from features or distance matrix, and return cluster labels. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or (n_samples, n_samples)
Training instances to cluster, or distances between instances if metric='precomputed'. If a sparse matrix is provided, it will be converted into a sparse csr_matrix.
sample_weightarray-like of shape (n_samples,), default=None
Weight of each sample, such that a sample with a weight of at least min_samples is by itself a core sample; a sample with a negative weight may inhibit its eps-neighbor from being core. Note that weights are absolute, and default to 1.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels. Noisy samples are given the label -1. | sklearn.modules.generated.sklearn.cluster.dbscan#sklearn.cluster.DBSCAN.fit_predict |
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. | sklearn.modules.generated.sklearn.cluster.dbscan#sklearn.cluster.DBSCAN.get_params |
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. | sklearn.modules.generated.sklearn.cluster.dbscan#sklearn.cluster.DBSCAN.set_params |
sklearn.cluster.estimate_bandwidth(X, *, quantile=0.3, n_samples=None, random_state=0, n_jobs=None) [source]
Estimate the bandwidth to use with the mean-shift algorithm. That this function takes time at least quadratic in n_samples. For large datasets, it’s wise to set that parameter to a small value. Parameters
Xarray-like of shape (n_samples, n_features)
Input points.
quantilefloat, default=0.3
should be between [0, 1] 0.5 means that the median of all pairwise distances is used.
n_samplesint, default=None
The number of samples to use. If not given, all samples are used.
random_stateint, RandomState instance, default=None
The generator used to randomly select the samples from input points for bandwidth estimation. Use an int to make the randomness deterministic. See Glossary.
n_jobsint, default=None
The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Returns
bandwidthfloat
The bandwidth parameter. | sklearn.modules.generated.sklearn.cluster.estimate_bandwidth#sklearn.cluster.estimate_bandwidth |
class sklearn.cluster.FeatureAgglomeration(n_clusters=2, *, affinity='euclidean', memory=None, connectivity=None, compute_full_tree='auto', linkage='ward', pooling_func=<function mean>, distance_threshold=None, compute_distances=False) [source]
Agglomerate features. Similar to AgglomerativeClustering, but recursively merges features instead of samples. Read more in the User Guide. Parameters
n_clustersint, default=2
The number of clusters to find. It must be None if distance_threshold is not None.
affinitystr or callable, default=’euclidean’
Metric used to compute the linkage. Can be “euclidean”, “l1”, “l2”, “manhattan”, “cosine”, or ‘precomputed’. If linkage is “ward”, only “euclidean” is accepted.
memorystr or object with the joblib.Memory interface, default=None
Used to cache the output of the computation of the tree. By default, no caching is done. If a string is given, it is the path to the caching directory.
connectivityarray-like or callable, default=None
Connectivity matrix. Defines for each feature the neighboring features following a given structure of the data. This can be a connectivity matrix itself or a callable that transforms the data into a connectivity matrix, such as derived from kneighbors_graph. Default is None, i.e, the hierarchical clustering algorithm is unstructured.
compute_full_tree‘auto’ or bool, default=’auto’
Stop early the construction of the tree at n_clusters. This is useful to decrease computation time if the number of clusters is not small compared to the number of features. This option is useful only when specifying a connectivity matrix. Note also that when varying the number of clusters and using caching, it may be advantageous to compute the full tree. It must be True if distance_threshold is not None. By default compute_full_tree is “auto”, which is equivalent to True when distance_threshold is not None or that n_clusters is inferior to the maximum between 100 or 0.02 * n_samples. Otherwise, “auto” is equivalent to False.
linkage{‘ward’, ‘complete’, ‘average’, ‘single’}, default=’ward’
Which linkage criterion to use. The linkage criterion determines which distance to use between sets of features. The algorithm will merge the pairs of cluster that minimize this criterion. ward minimizes the variance of the clusters being merged. average uses the average of the distances of each feature of the two sets. complete or maximum linkage uses the maximum distances between all features of the two sets. single uses the minimum of the distances between all observations of the two sets.
pooling_funccallable, default=np.mean
This combines the values of agglomerated features into a single value, and should accept an array of shape [M, N] and the keyword argument axis=1, and reduce it to an array of size [M].
distance_thresholdfloat, default=None
The linkage distance threshold above which, clusters will not be merged. If not None, n_clusters must be None and compute_full_tree must be True. New in version 0.21.
compute_distancesbool, default=False
Computes distances between clusters even if distance_threshold is not used. This can be used to make dendrogram visualization, but introduces a computational and memory overhead. New in version 0.24. Attributes
n_clusters_int
The number of clusters found by the algorithm. If distance_threshold=None, it will be equal to the given n_clusters.
labels_array-like of (n_features,)
cluster labels for each feature.
n_leaves_int
Number of leaves in the hierarchical tree.
n_connected_components_int
The estimated number of connected components in the graph. New in version 0.21: n_connected_components_ was added to replace n_components_.
children_array-like of shape (n_nodes-1, 2)
The children of each non-leaf node. Values less than n_features correspond to leaves of the tree which are the original samples. A node i greater than or equal to n_features is a non-leaf node and has children children_[i - n_features]. Alternatively at the i-th iteration, children[i][0] and children[i][1] are merged to form node n_features + i
distances_array-like of shape (n_nodes-1,)
Distances between nodes in the corresponding place in children_. Only computed if distance_threshold is used or compute_distances is set to True. Examples >>> import numpy as np
>>> from sklearn import datasets, cluster
>>> digits = datasets.load_digits()
>>> images = digits.images
>>> X = np.reshape(images, (len(images), -1))
>>> agglo = cluster.FeatureAgglomeration(n_clusters=32)
>>> agglo.fit(X)
FeatureAgglomeration(n_clusters=32)
>>> X_reduced = agglo.transform(X)
>>> X_reduced.shape
(1797, 32)
Methods
fit(X[, y]) Fit the hierarchical clustering on the data
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
inverse_transform(Xred) Inverse the transformation.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform a new matrix using the built clustering
fit(X, y=None, **params) [source]
Fit the hierarchical clustering on the data Parameters
Xarray-like of shape (n_samples, n_features)
The data
yIgnored
Returns
self
property fit_predict
Fit the hierarchical clustering from features or distance matrix, and return cluster labels. Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, or distances between instances if affinity='precomputed'.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels.
fit_transform(X, y=None, **fit_params) [source]
Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters
Xarray-like of shape (n_samples, n_features)
Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
**fit_paramsdict
Additional fit parameters. Returns
X_newndarray array of shape (n_samples, n_features_new)
Transformed array.
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.
inverse_transform(Xred) [source]
Inverse the transformation. Return a vector of size nb_features with the values of Xred assigned to each group of features Parameters
Xredarray-like of shape (n_samples, n_clusters) or (n_clusters,)
The values to be assigned to each cluster of samples Returns
Xndarray of shape (n_samples, n_features) or (n_features,)
A vector of size n_samples with the values of Xred assigned to each of the cluster of samples.
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.
transform(X) [source]
Transform a new matrix using the built clustering Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples,)
A M by N array of M observations in N dimensions or a length M array of M one-dimensional observations. Returns
Yndarray of shape (n_samples, n_clusters) or (n_clusters,)
The pooled values for each feature cluster. | sklearn.modules.generated.sklearn.cluster.featureagglomeration#sklearn.cluster.FeatureAgglomeration |
sklearn.cluster.FeatureAgglomeration
class sklearn.cluster.FeatureAgglomeration(n_clusters=2, *, affinity='euclidean', memory=None, connectivity=None, compute_full_tree='auto', linkage='ward', pooling_func=<function mean>, distance_threshold=None, compute_distances=False) [source]
Agglomerate features. Similar to AgglomerativeClustering, but recursively merges features instead of samples. Read more in the User Guide. Parameters
n_clustersint, default=2
The number of clusters to find. It must be None if distance_threshold is not None.
affinitystr or callable, default=’euclidean’
Metric used to compute the linkage. Can be “euclidean”, “l1”, “l2”, “manhattan”, “cosine”, or ‘precomputed’. If linkage is “ward”, only “euclidean” is accepted.
memorystr or object with the joblib.Memory interface, default=None
Used to cache the output of the computation of the tree. By default, no caching is done. If a string is given, it is the path to the caching directory.
connectivityarray-like or callable, default=None
Connectivity matrix. Defines for each feature the neighboring features following a given structure of the data. This can be a connectivity matrix itself or a callable that transforms the data into a connectivity matrix, such as derived from kneighbors_graph. Default is None, i.e, the hierarchical clustering algorithm is unstructured.
compute_full_tree‘auto’ or bool, default=’auto’
Stop early the construction of the tree at n_clusters. This is useful to decrease computation time if the number of clusters is not small compared to the number of features. This option is useful only when specifying a connectivity matrix. Note also that when varying the number of clusters and using caching, it may be advantageous to compute the full tree. It must be True if distance_threshold is not None. By default compute_full_tree is “auto”, which is equivalent to True when distance_threshold is not None or that n_clusters is inferior to the maximum between 100 or 0.02 * n_samples. Otherwise, “auto” is equivalent to False.
linkage{‘ward’, ‘complete’, ‘average’, ‘single’}, default=’ward’
Which linkage criterion to use. The linkage criterion determines which distance to use between sets of features. The algorithm will merge the pairs of cluster that minimize this criterion. ward minimizes the variance of the clusters being merged. average uses the average of the distances of each feature of the two sets. complete or maximum linkage uses the maximum distances between all features of the two sets. single uses the minimum of the distances between all observations of the two sets.
pooling_funccallable, default=np.mean
This combines the values of agglomerated features into a single value, and should accept an array of shape [M, N] and the keyword argument axis=1, and reduce it to an array of size [M].
distance_thresholdfloat, default=None
The linkage distance threshold above which, clusters will not be merged. If not None, n_clusters must be None and compute_full_tree must be True. New in version 0.21.
compute_distancesbool, default=False
Computes distances between clusters even if distance_threshold is not used. This can be used to make dendrogram visualization, but introduces a computational and memory overhead. New in version 0.24. Attributes
n_clusters_int
The number of clusters found by the algorithm. If distance_threshold=None, it will be equal to the given n_clusters.
labels_array-like of (n_features,)
cluster labels for each feature.
n_leaves_int
Number of leaves in the hierarchical tree.
n_connected_components_int
The estimated number of connected components in the graph. New in version 0.21: n_connected_components_ was added to replace n_components_.
children_array-like of shape (n_nodes-1, 2)
The children of each non-leaf node. Values less than n_features correspond to leaves of the tree which are the original samples. A node i greater than or equal to n_features is a non-leaf node and has children children_[i - n_features]. Alternatively at the i-th iteration, children[i][0] and children[i][1] are merged to form node n_features + i
distances_array-like of shape (n_nodes-1,)
Distances between nodes in the corresponding place in children_. Only computed if distance_threshold is used or compute_distances is set to True. Examples >>> import numpy as np
>>> from sklearn import datasets, cluster
>>> digits = datasets.load_digits()
>>> images = digits.images
>>> X = np.reshape(images, (len(images), -1))
>>> agglo = cluster.FeatureAgglomeration(n_clusters=32)
>>> agglo.fit(X)
FeatureAgglomeration(n_clusters=32)
>>> X_reduced = agglo.transform(X)
>>> X_reduced.shape
(1797, 32)
Methods
fit(X[, y]) Fit the hierarchical clustering on the data
fit_transform(X[, y]) Fit to data, then transform it.
get_params([deep]) Get parameters for this estimator.
inverse_transform(Xred) Inverse the transformation.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform a new matrix using the built clustering
fit(X, y=None, **params) [source]
Fit the hierarchical clustering on the data Parameters
Xarray-like of shape (n_samples, n_features)
The data
yIgnored
Returns
self
property fit_predict
Fit the hierarchical clustering from features or distance matrix, and return cluster labels. Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, or distances between instances if affinity='precomputed'.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels.
fit_transform(X, y=None, **fit_params) [source]
Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters
Xarray-like of shape (n_samples, n_features)
Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
**fit_paramsdict
Additional fit parameters. Returns
X_newndarray array of shape (n_samples, n_features_new)
Transformed array.
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.
inverse_transform(Xred) [source]
Inverse the transformation. Return a vector of size nb_features with the values of Xred assigned to each group of features Parameters
Xredarray-like of shape (n_samples, n_clusters) or (n_clusters,)
The values to be assigned to each cluster of samples Returns
Xndarray of shape (n_samples, n_features) or (n_features,)
A vector of size n_samples with the values of Xred assigned to each of the cluster of samples.
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.
transform(X) [source]
Transform a new matrix using the built clustering Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples,)
A M by N array of M observations in N dimensions or a length M array of M one-dimensional observations. Returns
Yndarray of shape (n_samples, n_clusters) or (n_clusters,)
The pooled values for each feature cluster.
Examples using sklearn.cluster.FeatureAgglomeration
Feature agglomeration
Feature agglomeration vs. univariate selection | sklearn.modules.generated.sklearn.cluster.featureagglomeration |
fit(X, y=None, **params) [source]
Fit the hierarchical clustering on the data Parameters
Xarray-like of shape (n_samples, n_features)
The data
yIgnored
Returns
self | sklearn.modules.generated.sklearn.cluster.featureagglomeration#sklearn.cluster.FeatureAgglomeration.fit |
property fit_predict
Fit the hierarchical clustering from features or distance matrix, and return cluster labels. Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, or distances between instances if affinity='precomputed'.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels. | sklearn.modules.generated.sklearn.cluster.featureagglomeration#sklearn.cluster.FeatureAgglomeration.fit_predict |
fit_transform(X, y=None, **fit_params) [source]
Fit to data, then transform it. Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X. Parameters
Xarray-like of shape (n_samples, n_features)
Input samples.
yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
**fit_paramsdict
Additional fit parameters. Returns
X_newndarray array of shape (n_samples, n_features_new)
Transformed array. | sklearn.modules.generated.sklearn.cluster.featureagglomeration#sklearn.cluster.FeatureAgglomeration.fit_transform |
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. | sklearn.modules.generated.sklearn.cluster.featureagglomeration#sklearn.cluster.FeatureAgglomeration.get_params |
inverse_transform(Xred) [source]
Inverse the transformation. Return a vector of size nb_features with the values of Xred assigned to each group of features Parameters
Xredarray-like of shape (n_samples, n_clusters) or (n_clusters,)
The values to be assigned to each cluster of samples Returns
Xndarray of shape (n_samples, n_features) or (n_features,)
A vector of size n_samples with the values of Xred assigned to each of the cluster of samples. | sklearn.modules.generated.sklearn.cluster.featureagglomeration#sklearn.cluster.FeatureAgglomeration.inverse_transform |
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. | sklearn.modules.generated.sklearn.cluster.featureagglomeration#sklearn.cluster.FeatureAgglomeration.set_params |
transform(X) [source]
Transform a new matrix using the built clustering Parameters
Xarray-like of shape (n_samples, n_features) or (n_samples,)
A M by N array of M observations in N dimensions or a length M array of M one-dimensional observations. Returns
Yndarray of shape (n_samples, n_clusters) or (n_clusters,)
The pooled values for each feature cluster. | sklearn.modules.generated.sklearn.cluster.featureagglomeration#sklearn.cluster.FeatureAgglomeration.transform |
class sklearn.cluster.KMeans(n_clusters=8, *, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='deprecated', verbose=0, random_state=None, copy_x=True, n_jobs='deprecated', algorithm='auto') [source]
K-Means clustering. Read more in the User Guide. Parameters
n_clustersint, default=8
The number of clusters to form as well as the number of centroids to generate.
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 centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details. ‘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.
n_initint, default=10
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.
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.
precompute_distances{‘auto’, True, False}, default=’auto’
Precompute distances (faster but takes more memory). ‘auto’ : do not precompute distances if n_samples * n_clusters > 12 million. This corresponds to about 100MB overhead per job using double precision. True : always precompute distances. False : never precompute distances. Deprecated since version 0.23: ‘precompute_distances’ was deprecated in version 0.22 and will be removed in 1.0 (renaming of 0.25). It has no effect.
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.
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.
n_jobsint, default=None
The number of OpenMP threads to use for the computation. Parallelism is sample-wise on the main cython loop which assigns each sample to its closest center. None or -1 means using all processors. Deprecated since version 0.23: n_jobs was deprecated in version 0.23 and will be removed in 1.0 (renaming of 0.25).
algorithm{“auto”, “full”, “elkan”}, default=”auto”
K-means algorithm to use. The classical EM-style algorithm is “full”. The “elkan” variation is more efficient on data 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). For now “auto” (kept for backward compatibiliy) chooses “elkan” but it might change in the future for a better heuristic. Changed in version 0.18: Added Elkan algorithm Attributes
cluster_centers_ndarray of shape (n_clusters, n_features)
Coordinates of cluster centers. If the algorithm stops before fully converging (see tol and max_iter), these will not be consistent with labels_.
labels_ndarray of shape (n_samples,)
Labels of each point
inertia_float
Sum of squared distances of samples to their closest cluster center.
n_iter_int
Number of iterations run. See also
MiniBatchKMeans
Alternative online implementation that does incremental updates of the centers positions using mini-batches. For large scale learning (say n_samples > 10k) MiniBatchKMeans is probably much faster than the default batch implementation. Notes The k-means problem is solved using either Lloyd’s or Elkan’s algorithm. The average complexity is given by O(k n T), were n is the number of samples and T is the number of iteration. The worst case complexity is given by O(n^(k+2/p)) with n = n_samples, p = n_features. (D. Arthur and S. Vassilvitskii, ‘How slow is the k-means method?’ SoCG2006) In practice, the k-means algorithm is very fast (one of the fastest clustering algorithms available), but it falls in local minima. That’s why it can be useful to restart it several times. If the algorithm stops before fully converging (because of tol or max_iter), labels_ and cluster_centers_ will not be consistent, i.e. the cluster_centers_ will not be the means of the points in each cluster. Also, the estimator will reassign labels_ after the last iteration to make labels_ consistent with predict on the training set. Examples >>> from sklearn.cluster import KMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [10, 2], [10, 4], [10, 0]])
>>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
>>> kmeans.labels_
array([1, 1, 1, 0, 0, 0], dtype=int32)
>>> kmeans.predict([[0, 0], [12, 3]])
array([1, 0], dtype=int32)
>>> kmeans.cluster_centers_
array([[10., 2.],
[ 1., 2.]])
Methods
fit(X[, y, sample_weight]) Compute k-means clustering.
fit_predict(X[, y, sample_weight]) Compute cluster centers and predict cluster index for each sample.
fit_transform(X[, y, sample_weight]) Compute clustering and transform X to cluster-distance space.
get_params([deep]) Get parameters for this estimator.
predict(X[, sample_weight]) Predict the closest cluster each sample in X belongs to.
score(X[, y, sample_weight]) Opposite of the value of X on the K-means objective.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform X to a cluster-distance space.
fit(X, y=None, sample_weight=None) [source]
Compute k-means clustering. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous. If a sparse matrix is passed, a copy will be made if it’s not in CSR format.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. New in version 0.20. Returns
self
Fitted estimator.
fit_predict(X, y=None, sample_weight=None) [source]
Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
fit_transform(X, y=None, sample_weight=None) [source]
Compute clustering and transform X to cluster-distance space. Equivalent to fit(X).transform(X), but more efficiently implemented. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space.
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.
predict(X, sample_weight=None) [source]
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, cluster_centers_ is called the code book and each value returned by predict is the index of the closest code in the code book. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
score(X, y=None, sample_weight=None) [source]
Opposite of the value of X on the K-means objective. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
scorefloat
Opposite of the value of X on the K-means objective.
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.
transform(X) [source]
Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by transform will typically be dense. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space. | sklearn.modules.generated.sklearn.cluster.kmeans#sklearn.cluster.KMeans |
sklearn.cluster.KMeans
class sklearn.cluster.KMeans(n_clusters=8, *, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='deprecated', verbose=0, random_state=None, copy_x=True, n_jobs='deprecated', algorithm='auto') [source]
K-Means clustering. Read more in the User Guide. Parameters
n_clustersint, default=8
The number of clusters to form as well as the number of centroids to generate.
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 centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details. ‘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.
n_initint, default=10
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.
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.
precompute_distances{‘auto’, True, False}, default=’auto’
Precompute distances (faster but takes more memory). ‘auto’ : do not precompute distances if n_samples * n_clusters > 12 million. This corresponds to about 100MB overhead per job using double precision. True : always precompute distances. False : never precompute distances. Deprecated since version 0.23: ‘precompute_distances’ was deprecated in version 0.22 and will be removed in 1.0 (renaming of 0.25). It has no effect.
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.
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.
n_jobsint, default=None
The number of OpenMP threads to use for the computation. Parallelism is sample-wise on the main cython loop which assigns each sample to its closest center. None or -1 means using all processors. Deprecated since version 0.23: n_jobs was deprecated in version 0.23 and will be removed in 1.0 (renaming of 0.25).
algorithm{“auto”, “full”, “elkan”}, default=”auto”
K-means algorithm to use. The classical EM-style algorithm is “full”. The “elkan” variation is more efficient on data 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). For now “auto” (kept for backward compatibiliy) chooses “elkan” but it might change in the future for a better heuristic. Changed in version 0.18: Added Elkan algorithm Attributes
cluster_centers_ndarray of shape (n_clusters, n_features)
Coordinates of cluster centers. If the algorithm stops before fully converging (see tol and max_iter), these will not be consistent with labels_.
labels_ndarray of shape (n_samples,)
Labels of each point
inertia_float
Sum of squared distances of samples to their closest cluster center.
n_iter_int
Number of iterations run. See also
MiniBatchKMeans
Alternative online implementation that does incremental updates of the centers positions using mini-batches. For large scale learning (say n_samples > 10k) MiniBatchKMeans is probably much faster than the default batch implementation. Notes The k-means problem is solved using either Lloyd’s or Elkan’s algorithm. The average complexity is given by O(k n T), were n is the number of samples and T is the number of iteration. The worst case complexity is given by O(n^(k+2/p)) with n = n_samples, p = n_features. (D. Arthur and S. Vassilvitskii, ‘How slow is the k-means method?’ SoCG2006) In practice, the k-means algorithm is very fast (one of the fastest clustering algorithms available), but it falls in local minima. That’s why it can be useful to restart it several times. If the algorithm stops before fully converging (because of tol or max_iter), labels_ and cluster_centers_ will not be consistent, i.e. the cluster_centers_ will not be the means of the points in each cluster. Also, the estimator will reassign labels_ after the last iteration to make labels_ consistent with predict on the training set. Examples >>> from sklearn.cluster import KMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [10, 2], [10, 4], [10, 0]])
>>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
>>> kmeans.labels_
array([1, 1, 1, 0, 0, 0], dtype=int32)
>>> kmeans.predict([[0, 0], [12, 3]])
array([1, 0], dtype=int32)
>>> kmeans.cluster_centers_
array([[10., 2.],
[ 1., 2.]])
Methods
fit(X[, y, sample_weight]) Compute k-means clustering.
fit_predict(X[, y, sample_weight]) Compute cluster centers and predict cluster index for each sample.
fit_transform(X[, y, sample_weight]) Compute clustering and transform X to cluster-distance space.
get_params([deep]) Get parameters for this estimator.
predict(X[, sample_weight]) Predict the closest cluster each sample in X belongs to.
score(X[, y, sample_weight]) Opposite of the value of X on the K-means objective.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform X to a cluster-distance space.
fit(X, y=None, sample_weight=None) [source]
Compute k-means clustering. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous. If a sparse matrix is passed, a copy will be made if it’s not in CSR format.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. New in version 0.20. Returns
self
Fitted estimator.
fit_predict(X, y=None, sample_weight=None) [source]
Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
fit_transform(X, y=None, sample_weight=None) [source]
Compute clustering and transform X to cluster-distance space. Equivalent to fit(X).transform(X), but more efficiently implemented. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space.
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.
predict(X, sample_weight=None) [source]
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, cluster_centers_ is called the code book and each value returned by predict is the index of the closest code in the code book. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
score(X, y=None, sample_weight=None) [source]
Opposite of the value of X on the K-means objective. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
scorefloat
Opposite of the value of X on the K-means objective.
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.
transform(X) [source]
Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by transform will typically be dense. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space.
Examples using sklearn.cluster.KMeans
Release Highlights for scikit-learn 0.23
Demonstration of k-means assumptions
Vector Quantization Example
K-means Clustering
Color Quantization using K-Means
Empirical evaluation of the impact of k-means initialization
Comparison of the K-Means and MiniBatchKMeans clustering algorithms
A demo of K-Means clustering on the handwritten digits data
Selecting the number of clusters with silhouette analysis on KMeans clustering
Clustering text documents using k-means | sklearn.modules.generated.sklearn.cluster.kmeans |
fit(X, y=None, sample_weight=None) [source]
Compute k-means clustering. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous. If a sparse matrix is passed, a copy will be made if it’s not in CSR format.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. New in version 0.20. Returns
self
Fitted estimator. | sklearn.modules.generated.sklearn.cluster.kmeans#sklearn.cluster.KMeans.fit |
fit_predict(X, y=None, sample_weight=None) [source]
Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to. | sklearn.modules.generated.sklearn.cluster.kmeans#sklearn.cluster.KMeans.fit_predict |
fit_transform(X, y=None, sample_weight=None) [source]
Compute clustering and transform X to cluster-distance space. Equivalent to fit(X).transform(X), but more efficiently implemented. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space. | sklearn.modules.generated.sklearn.cluster.kmeans#sklearn.cluster.KMeans.fit_transform |
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. | sklearn.modules.generated.sklearn.cluster.kmeans#sklearn.cluster.KMeans.get_params |
predict(X, sample_weight=None) [source]
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, cluster_centers_ is called the code book and each value returned by predict is the index of the closest code in the code book. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to. | sklearn.modules.generated.sklearn.cluster.kmeans#sklearn.cluster.KMeans.predict |
score(X, y=None, sample_weight=None) [source]
Opposite of the value of X on the K-means objective. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
scorefloat
Opposite of the value of X on the K-means objective. | sklearn.modules.generated.sklearn.cluster.kmeans#sklearn.cluster.KMeans.score |
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. | sklearn.modules.generated.sklearn.cluster.kmeans#sklearn.cluster.KMeans.set_params |
transform(X) [source]
Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by transform will typically be dense. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space. | sklearn.modules.generated.sklearn.cluster.kmeans#sklearn.cluster.KMeans.transform |
sklearn.cluster.kmeans_plusplus(X, n_clusters, *, x_squared_norms=None, random_state=None, n_local_trials=None) [source]
Init n_clusters seeds according to k-means++ New in version 0.24. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The data to pick seeds from.
n_clustersint
The number of centroids to initialize
x_squared_normsarray-like of shape (n_samples,), default=None
Squared Euclidean norm of each data point.
random_stateint or RandomState instance, default=None
Determines random number generation for centroid initialization. Pass an int for reproducible output across multiple function calls. See Glossary.
n_local_trialsint, default=None
The number of seeding trials for each center (except the first), of which the one reducing inertia the most is greedily chosen. Set to None to make the number of trials depend logarithmically on the number of seeds (2+log(k)). Returns
centersndarray of shape (n_clusters, n_features)
The inital centers for k-means.
indicesndarray of shape (n_clusters,)
The index location of the chosen centers in the data array X. For a given index and center, X[index] = center. Notes Selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. see: Arthur, D. and Vassilvitskii, S. “k-means++: the advantages of careful seeding”. ACM-SIAM symposium on Discrete algorithms. 2007 Examples >>> from sklearn.cluster import kmeans_plusplus
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [10, 2], [10, 4], [10, 0]])
>>> centers, indices = kmeans_plusplus(X, n_clusters=2, random_state=0)
>>> centers
array([[10, 4],
[ 1, 0]])
>>> indices
array([4, 2]) | sklearn.modules.generated.sklearn.cluster.kmeans_plusplus#sklearn.cluster.kmeans_plusplus |
sklearn.cluster.k_means(X, n_clusters, *, sample_weight=None, init='k-means++', precompute_distances='deprecated', n_init=10, max_iter=300, verbose=False, tol=0.0001, random_state=None, copy_x=True, n_jobs='deprecated', algorithm='auto', return_n_iter=False) [source]
K-means clustering algorithm. Read more in the User Guide. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
The observations to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous.
n_clustersint
The number of clusters to form as well as the number of centroids to generate.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight.
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 centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details. ‘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.
precompute_distances{‘auto’, True, False}
Precompute distances (faster but takes more memory). ‘auto’ : do not precompute distances if n_samples * n_clusters > 12 million. This corresponds to about 100MB overhead per job using double precision. True : always precompute distances False : never precompute distances Deprecated since version 0.23: ‘precompute_distances’ was deprecated in version 0.23 and will be removed in 1.0 (renaming of 0.25). It has no effect.
n_initint, default=10
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.
max_iterint, default=300
Maximum number of iterations of the k-means algorithm to run.
verbosebool, default=False
Verbosity mode.
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.
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.
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.
n_jobsint, default=None
The number of OpenMP threads to use for the computation. Parallelism is sample-wise on the main cython loop which assigns each sample to its closest center. None or -1 means using all processors. Deprecated since version 0.23: n_jobs was deprecated in version 0.23 and will be removed in 1.0 (renaming of 0.25).
algorithm{“auto”, “full”, “elkan”}, default=”auto”
K-means algorithm to use. The classical EM-style algorithm is “full”. The “elkan” variation is more efficient on data 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). For now “auto” (kept for backward compatibiliy) chooses “elkan” but it might change in the future for a better heuristic.
return_n_iterbool, default=False
Whether or not to return the number of iterations. Returns
centroidndarray of shape (n_clusters, n_features)
Centroids found at the last iteration of k-means.
labelndarray of shape (n_samples,)
label[i] is the code or index of the centroid the i’th observation is closest to.
inertiafloat
The final value of the inertia criterion (sum of squared distances to the closest centroid for all observations in the training set).
best_n_iterint
Number of iterations corresponding to the best results. Returned only if return_n_iter is set to True. | sklearn.modules.generated.sklearn.cluster.k_means#sklearn.cluster.k_means |
class sklearn.cluster.MeanShift(*, bandwidth=None, seeds=None, bin_seeding=False, min_bin_freq=1, cluster_all=True, n_jobs=None, max_iter=300) [source]
Mean shift clustering using a flat kernel. Mean shift clustering aims to discover “blobs” in a smooth density of samples. It is a centroid-based algorithm, which works by updating candidates for centroids to be the mean of the points within a given region. These candidates are then filtered in a post-processing stage to eliminate near-duplicates to form the final set of centroids. Seeding is performed using a binning technique for scalability. Read more in the User Guide. Parameters
bandwidthfloat, default=None
Bandwidth used in the RBF kernel. If not given, the bandwidth is estimated using sklearn.cluster.estimate_bandwidth; see the documentation for that function for hints on scalability (see also the Notes, below).
seedsarray-like of shape (n_samples, n_features), default=None
Seeds used to initialize kernels. If not set, the seeds are calculated by clustering.get_bin_seeds with bandwidth as the grid size and default values for other parameters.
bin_seedingbool, default=False
If true, initial kernel locations are not locations of all points, but rather the location of the discretized version of points, where points are binned onto a grid whose coarseness corresponds to the bandwidth. Setting this option to True will speed up the algorithm because fewer seeds will be initialized. The default value is False. Ignored if seeds argument is not None.
min_bin_freqint, default=1
To speed up the algorithm, accept only those bins with at least min_bin_freq points as seeds.
cluster_allbool, default=True
If true, then all points are clustered, even those orphans that are not within any kernel. Orphans are assigned to the nearest kernel. If false, then orphans are given cluster label -1.
n_jobsint, default=None
The number of jobs to use for the computation. This works by computing each of the n_init runs in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
max_iterint, default=300
Maximum number of iterations, per seed point before the clustering operation terminates (for that seed point), if has not converged yet. New in version 0.22. Attributes
cluster_centers_ndarray of shape (n_clusters, n_features)
Coordinates of cluster centers.
labels_ndarray of shape (n_samples,)
Labels of each point.
n_iter_int
Maximum number of iterations performed on each seed. New in version 0.22. Notes Scalability: Because this implementation uses a flat kernel and a Ball Tree to look up members of each kernel, the complexity will tend towards O(T*n*log(n)) in lower dimensions, with n the number of samples and T the number of points. In higher dimensions the complexity will tend towards O(T*n^2). Scalability can be boosted by using fewer seeds, for example by using a higher value of min_bin_freq in the get_bin_seeds function. Note that the estimate_bandwidth function is much less scalable than the mean shift algorithm and will be the bottleneck if it is used. References Dorin Comaniciu and Peter Meer, “Mean Shift: A robust approach toward feature space analysis”. IEEE Transactions on Pattern Analysis and Machine Intelligence. 2002. pp. 603-619. Examples >>> from sklearn.cluster import MeanShift
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
... [4, 7], [3, 5], [3, 6]])
>>> clustering = MeanShift(bandwidth=2).fit(X)
>>> clustering.labels_
array([1, 1, 1, 0, 0, 0])
>>> clustering.predict([[0, 0], [5, 5]])
array([1, 0])
>>> clustering
MeanShift(bandwidth=2)
Methods
fit(X[, y]) Perform clustering.
fit_predict(X[, y]) Perform clustering on X and returns cluster labels.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict the closest cluster each sample in X belongs to.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]
Perform clustering. Parameters
Xarray-like of shape (n_samples, n_features)
Samples to cluster.
yIgnored
fit_predict(X, y=None) [source]
Perform clustering on X and returns cluster labels. Parameters
Xarray-like of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present for API consistency by convention. Returns
labelsndarray of shape (n_samples,), dtype=np.int64
Cluster labels.
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.
predict(X) [source]
Predict the closest cluster each sample in X belongs to. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
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. | sklearn.modules.generated.sklearn.cluster.meanshift#sklearn.cluster.MeanShift |
sklearn.cluster.MeanShift
class sklearn.cluster.MeanShift(*, bandwidth=None, seeds=None, bin_seeding=False, min_bin_freq=1, cluster_all=True, n_jobs=None, max_iter=300) [source]
Mean shift clustering using a flat kernel. Mean shift clustering aims to discover “blobs” in a smooth density of samples. It is a centroid-based algorithm, which works by updating candidates for centroids to be the mean of the points within a given region. These candidates are then filtered in a post-processing stage to eliminate near-duplicates to form the final set of centroids. Seeding is performed using a binning technique for scalability. Read more in the User Guide. Parameters
bandwidthfloat, default=None
Bandwidth used in the RBF kernel. If not given, the bandwidth is estimated using sklearn.cluster.estimate_bandwidth; see the documentation for that function for hints on scalability (see also the Notes, below).
seedsarray-like of shape (n_samples, n_features), default=None
Seeds used to initialize kernels. If not set, the seeds are calculated by clustering.get_bin_seeds with bandwidth as the grid size and default values for other parameters.
bin_seedingbool, default=False
If true, initial kernel locations are not locations of all points, but rather the location of the discretized version of points, where points are binned onto a grid whose coarseness corresponds to the bandwidth. Setting this option to True will speed up the algorithm because fewer seeds will be initialized. The default value is False. Ignored if seeds argument is not None.
min_bin_freqint, default=1
To speed up the algorithm, accept only those bins with at least min_bin_freq points as seeds.
cluster_allbool, default=True
If true, then all points are clustered, even those orphans that are not within any kernel. Orphans are assigned to the nearest kernel. If false, then orphans are given cluster label -1.
n_jobsint, default=None
The number of jobs to use for the computation. This works by computing each of the n_init runs in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
max_iterint, default=300
Maximum number of iterations, per seed point before the clustering operation terminates (for that seed point), if has not converged yet. New in version 0.22. Attributes
cluster_centers_ndarray of shape (n_clusters, n_features)
Coordinates of cluster centers.
labels_ndarray of shape (n_samples,)
Labels of each point.
n_iter_int
Maximum number of iterations performed on each seed. New in version 0.22. Notes Scalability: Because this implementation uses a flat kernel and a Ball Tree to look up members of each kernel, the complexity will tend towards O(T*n*log(n)) in lower dimensions, with n the number of samples and T the number of points. In higher dimensions the complexity will tend towards O(T*n^2). Scalability can be boosted by using fewer seeds, for example by using a higher value of min_bin_freq in the get_bin_seeds function. Note that the estimate_bandwidth function is much less scalable than the mean shift algorithm and will be the bottleneck if it is used. References Dorin Comaniciu and Peter Meer, “Mean Shift: A robust approach toward feature space analysis”. IEEE Transactions on Pattern Analysis and Machine Intelligence. 2002. pp. 603-619. Examples >>> from sklearn.cluster import MeanShift
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
... [4, 7], [3, 5], [3, 6]])
>>> clustering = MeanShift(bandwidth=2).fit(X)
>>> clustering.labels_
array([1, 1, 1, 0, 0, 0])
>>> clustering.predict([[0, 0], [5, 5]])
array([1, 0])
>>> clustering
MeanShift(bandwidth=2)
Methods
fit(X[, y]) Perform clustering.
fit_predict(X[, y]) Perform clustering on X and returns cluster labels.
get_params([deep]) Get parameters for this estimator.
predict(X) Predict the closest cluster each sample in X belongs to.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]
Perform clustering. Parameters
Xarray-like of shape (n_samples, n_features)
Samples to cluster.
yIgnored
fit_predict(X, y=None) [source]
Perform clustering on X and returns cluster labels. Parameters
Xarray-like of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present for API consistency by convention. Returns
labelsndarray of shape (n_samples,), dtype=np.int64
Cluster labels.
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.
predict(X) [source]
Predict the closest cluster each sample in X belongs to. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
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.
Examples using sklearn.cluster.MeanShift
A demo of the mean-shift clustering algorithm
Comparing different clustering algorithms on toy datasets | sklearn.modules.generated.sklearn.cluster.meanshift |
fit(X, y=None) [source]
Perform clustering. Parameters
Xarray-like of shape (n_samples, n_features)
Samples to cluster.
yIgnored | sklearn.modules.generated.sklearn.cluster.meanshift#sklearn.cluster.MeanShift.fit |
fit_predict(X, y=None) [source]
Perform clustering on X and returns cluster labels. Parameters
Xarray-like of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present for API consistency by convention. Returns
labelsndarray of shape (n_samples,), dtype=np.int64
Cluster labels. | sklearn.modules.generated.sklearn.cluster.meanshift#sklearn.cluster.MeanShift.fit_predict |
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. | sklearn.modules.generated.sklearn.cluster.meanshift#sklearn.cluster.MeanShift.get_params |
predict(X) [source]
Predict the closest cluster each sample in X belongs to. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to. | sklearn.modules.generated.sklearn.cluster.meanshift#sklearn.cluster.MeanShift.predict |
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. | sklearn.modules.generated.sklearn.cluster.meanshift#sklearn.cluster.MeanShift.set_params |
sklearn.cluster.mean_shift(X, *, bandwidth=None, seeds=None, bin_seeding=False, min_bin_freq=1, cluster_all=True, max_iter=300, n_jobs=None) [source]
Perform mean shift clustering of data using a flat kernel. Read more in the User Guide. Parameters
Xarray-like of shape (n_samples, n_features)
Input data.
bandwidthfloat, default=None
Kernel bandwidth. If bandwidth is not given, it is determined using a heuristic based on the median of all pairwise distances. This will take quadratic time in the number of samples. The sklearn.cluster.estimate_bandwidth function can be used to do this more efficiently.
seedsarray-like of shape (n_seeds, n_features) or None
Point used as initial kernel locations. If None and bin_seeding=False, each data point is used as a seed. If None and bin_seeding=True, see bin_seeding.
bin_seedingbool, default=False
If true, initial kernel locations are not locations of all points, but rather the location of the discretized version of points, where points are binned onto a grid whose coarseness corresponds to the bandwidth. Setting this option to True will speed up the algorithm because fewer seeds will be initialized. Ignored if seeds argument is not None.
min_bin_freqint, default=1
To speed up the algorithm, accept only those bins with at least min_bin_freq points as seeds.
cluster_allbool, default=True
If true, then all points are clustered, even those orphans that are not within any kernel. Orphans are assigned to the nearest kernel. If false, then orphans are given cluster label -1.
max_iterint, default=300
Maximum number of iterations, per seed point before the clustering operation terminates (for that seed point), if has not converged yet.
n_jobsint, default=None
The number of jobs to use for the computation. This works by computing each of the n_init runs in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. New in version 0.17: Parallel Execution using n_jobs. Returns
cluster_centersndarray of shape (n_clusters, n_features)
Coordinates of cluster centers.
labelsndarray of shape (n_samples,)
Cluster labels for each point. Notes For an example, see examples/cluster/plot_mean_shift.py. | sklearn.modules.generated.sklearn.cluster.mean_shift#sklearn.cluster.mean_shift |
class sklearn.cluster.MiniBatchKMeans(n_clusters=8, *, init='k-means++', max_iter=100, batch_size=100, verbose=0, compute_labels=True, random_state=None, tol=0.0, max_no_improvement=10, init_size=None, n_init=3, reassignment_ratio=0.01) [source]
Mini-Batch K-Means clustering. Read more in the User Guide. Parameters
n_clustersint, default=8
The number of clusters to form as well as the number of centroids to generate.
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 centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details. ‘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.
max_iterint, default=100
Maximum number of iterations over the complete dataset before stopping independently of any early stopping criterion heuristics.
batch_sizeint, default=100
Size of the mini batches.
verboseint, default=0
Verbosity mode.
compute_labelsbool, default=True
Compute label assignment and inertia for the complete dataset once the minibatch optimization has converged in fit.
random_stateint, RandomState instance or None, default=None
Determines random number generation for centroid initialization and random reassignment. Use an int to make the randomness deterministic. See Glossary.
tolfloat, default=0.0
Control early stopping based on the relative center changes as measured by a smoothed, variance-normalized of the mean center squared position changes. This early stopping heuristics is closer to the one used for the batch variant of the algorithms but induces a slight computational and memory overhead over the inertia heuristic. To disable convergence detection based on normalized center change, set tol to 0.0 (default).
max_no_improvementint, default=10
Control early stopping based on the consecutive number of mini batches that does not yield an improvement on the smoothed inertia. To disable convergence detection based on inertia, set max_no_improvement to None.
init_sizeint, default=None
Number of samples to randomly sample for speeding up the initialization (sometimes at the expense of accuracy): the only algorithm is initialized by running a batch KMeans on a random subset of the data. This needs to be larger than n_clusters. If None, init_size= 3 * batch_size.
n_initint, default=3
Number of random initializations that are tried. In contrast to KMeans, the algorithm is only run once, using the best of the n_init initializations as measured by inertia.
reassignment_ratiofloat, default=0.01
Control the fraction of the maximum number of counts for a center to be reassigned. A higher value means that low count centers are more easily reassigned, which means that the model will take longer to converge, but should converge in a better clustering. Attributes
cluster_centers_ndarray of shape (n_clusters, n_features)
Coordinates of cluster centers.
labels_int
Labels of each point (if compute_labels is set to True).
inertia_float
The value of the inertia criterion associated with the chosen partition (if compute_labels is set to True). The inertia is defined as the sum of square distances of samples to their nearest neighbor.
n_iter_int
Number of batches processed.
counts_ndarray of shape (n_clusters,)
Weigth sum of each cluster. Deprecated since version 0.24: This attribute is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26).
init_size_int
The effective number of samples used for the initialization. Deprecated since version 0.24: This attribute is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). See also
KMeans
The classic implementation of the clustering method based on the Lloyd’s algorithm. It consumes the whole set of input data at each iteration. Notes See https://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf Examples >>> from sklearn.cluster import MiniBatchKMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [4, 2], [4, 0], [4, 4],
... [4, 5], [0, 1], [2, 2],
... [3, 2], [5, 5], [1, -1]])
>>> # manually fit on batches
>>> kmeans = MiniBatchKMeans(n_clusters=2,
... random_state=0,
... batch_size=6)
>>> kmeans = kmeans.partial_fit(X[0:6,:])
>>> kmeans = kmeans.partial_fit(X[6:12,:])
>>> kmeans.cluster_centers_
array([[2. , 1. ],
[3.5, 4.5]])
>>> kmeans.predict([[0, 0], [4, 4]])
array([0, 1], dtype=int32)
>>> # fit on the whole data
>>> kmeans = MiniBatchKMeans(n_clusters=2,
... random_state=0,
... batch_size=6,
... max_iter=10).fit(X)
>>> kmeans.cluster_centers_
array([[3.95918367, 2.40816327],
[1.12195122, 1.3902439 ]])
>>> kmeans.predict([[0, 0], [4, 4]])
array([1, 0], dtype=int32)
Methods
fit(X[, y, sample_weight]) Compute the centroids on X by chunking it into mini-batches.
fit_predict(X[, y, sample_weight]) Compute cluster centers and predict cluster index for each sample.
fit_transform(X[, y, sample_weight]) Compute clustering and transform X to cluster-distance space.
get_params([deep]) Get parameters for this estimator.
partial_fit(X[, y, sample_weight]) Update k means estimate on a single mini-batch X.
predict(X[, sample_weight]) Predict the closest cluster each sample in X belongs to.
score(X[, y, sample_weight]) Opposite of the value of X on the K-means objective.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform X to a cluster-distance space.
fit(X, y=None, sample_weight=None) [source]
Compute the centroids on X by chunking it into mini-batches. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight (default: None). New in version 0.20. Returns
self
fit_predict(X, y=None, sample_weight=None) [source]
Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
fit_transform(X, y=None, sample_weight=None) [source]
Compute clustering and transform X to cluster-distance space. Equivalent to fit(X).transform(X), but more efficiently implemented. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space.
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.
partial_fit(X, y=None, sample_weight=None) [source]
Update k means estimate on a single mini-batch X. Parameters
Xarray-like of shape (n_samples, n_features)
Coordinates of the data points to cluster. It must be noted that X will be copied if it is not C-contiguous.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight (default: None). Returns
self
predict(X, sample_weight=None) [source]
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, cluster_centers_ is called the code book and each value returned by predict is the index of the closest code in the code book. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight (default: None). Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
score(X, y=None, sample_weight=None) [source]
Opposite of the value of X on the K-means objective. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
scorefloat
Opposite of the value of X on the K-means objective.
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.
transform(X) [source]
Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by transform will typically be dense. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space. | sklearn.modules.generated.sklearn.cluster.minibatchkmeans#sklearn.cluster.MiniBatchKMeans |
sklearn.cluster.MiniBatchKMeans
class sklearn.cluster.MiniBatchKMeans(n_clusters=8, *, init='k-means++', max_iter=100, batch_size=100, verbose=0, compute_labels=True, random_state=None, tol=0.0, max_no_improvement=10, init_size=None, n_init=3, reassignment_ratio=0.01) [source]
Mini-Batch K-Means clustering. Read more in the User Guide. Parameters
n_clustersint, default=8
The number of clusters to form as well as the number of centroids to generate.
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 centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details. ‘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.
max_iterint, default=100
Maximum number of iterations over the complete dataset before stopping independently of any early stopping criterion heuristics.
batch_sizeint, default=100
Size of the mini batches.
verboseint, default=0
Verbosity mode.
compute_labelsbool, default=True
Compute label assignment and inertia for the complete dataset once the minibatch optimization has converged in fit.
random_stateint, RandomState instance or None, default=None
Determines random number generation for centroid initialization and random reassignment. Use an int to make the randomness deterministic. See Glossary.
tolfloat, default=0.0
Control early stopping based on the relative center changes as measured by a smoothed, variance-normalized of the mean center squared position changes. This early stopping heuristics is closer to the one used for the batch variant of the algorithms but induces a slight computational and memory overhead over the inertia heuristic. To disable convergence detection based on normalized center change, set tol to 0.0 (default).
max_no_improvementint, default=10
Control early stopping based on the consecutive number of mini batches that does not yield an improvement on the smoothed inertia. To disable convergence detection based on inertia, set max_no_improvement to None.
init_sizeint, default=None
Number of samples to randomly sample for speeding up the initialization (sometimes at the expense of accuracy): the only algorithm is initialized by running a batch KMeans on a random subset of the data. This needs to be larger than n_clusters. If None, init_size= 3 * batch_size.
n_initint, default=3
Number of random initializations that are tried. In contrast to KMeans, the algorithm is only run once, using the best of the n_init initializations as measured by inertia.
reassignment_ratiofloat, default=0.01
Control the fraction of the maximum number of counts for a center to be reassigned. A higher value means that low count centers are more easily reassigned, which means that the model will take longer to converge, but should converge in a better clustering. Attributes
cluster_centers_ndarray of shape (n_clusters, n_features)
Coordinates of cluster centers.
labels_int
Labels of each point (if compute_labels is set to True).
inertia_float
The value of the inertia criterion associated with the chosen partition (if compute_labels is set to True). The inertia is defined as the sum of square distances of samples to their nearest neighbor.
n_iter_int
Number of batches processed.
counts_ndarray of shape (n_clusters,)
Weigth sum of each cluster. Deprecated since version 0.24: This attribute is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26).
init_size_int
The effective number of samples used for the initialization. Deprecated since version 0.24: This attribute is deprecated in 0.24 and will be removed in 1.1 (renaming of 0.26). See also
KMeans
The classic implementation of the clustering method based on the Lloyd’s algorithm. It consumes the whole set of input data at each iteration. Notes See https://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf Examples >>> from sklearn.cluster import MiniBatchKMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
... [4, 2], [4, 0], [4, 4],
... [4, 5], [0, 1], [2, 2],
... [3, 2], [5, 5], [1, -1]])
>>> # manually fit on batches
>>> kmeans = MiniBatchKMeans(n_clusters=2,
... random_state=0,
... batch_size=6)
>>> kmeans = kmeans.partial_fit(X[0:6,:])
>>> kmeans = kmeans.partial_fit(X[6:12,:])
>>> kmeans.cluster_centers_
array([[2. , 1. ],
[3.5, 4.5]])
>>> kmeans.predict([[0, 0], [4, 4]])
array([0, 1], dtype=int32)
>>> # fit on the whole data
>>> kmeans = MiniBatchKMeans(n_clusters=2,
... random_state=0,
... batch_size=6,
... max_iter=10).fit(X)
>>> kmeans.cluster_centers_
array([[3.95918367, 2.40816327],
[1.12195122, 1.3902439 ]])
>>> kmeans.predict([[0, 0], [4, 4]])
array([1, 0], dtype=int32)
Methods
fit(X[, y, sample_weight]) Compute the centroids on X by chunking it into mini-batches.
fit_predict(X[, y, sample_weight]) Compute cluster centers and predict cluster index for each sample.
fit_transform(X[, y, sample_weight]) Compute clustering and transform X to cluster-distance space.
get_params([deep]) Get parameters for this estimator.
partial_fit(X[, y, sample_weight]) Update k means estimate on a single mini-batch X.
predict(X[, sample_weight]) Predict the closest cluster each sample in X belongs to.
score(X[, y, sample_weight]) Opposite of the value of X on the K-means objective.
set_params(**params) Set the parameters of this estimator.
transform(X) Transform X to a cluster-distance space.
fit(X, y=None, sample_weight=None) [source]
Compute the centroids on X by chunking it into mini-batches. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight (default: None). New in version 0.20. Returns
self
fit_predict(X, y=None, sample_weight=None) [source]
Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
fit_transform(X, y=None, sample_weight=None) [source]
Compute clustering and transform X to cluster-distance space. Equivalent to fit(X).transform(X), but more efficiently implemented. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space.
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.
partial_fit(X, y=None, sample_weight=None) [source]
Update k means estimate on a single mini-batch X. Parameters
Xarray-like of shape (n_samples, n_features)
Coordinates of the data points to cluster. It must be noted that X will be copied if it is not C-contiguous.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight (default: None). Returns
self
predict(X, sample_weight=None) [source]
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, cluster_centers_ is called the code book and each value returned by predict is the index of the closest code in the code book. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight (default: None). Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
score(X, y=None, sample_weight=None) [source]
Opposite of the value of X on the K-means objective. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
scorefloat
Opposite of the value of X on the K-means objective.
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.
transform(X) [source]
Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by transform will typically be dense. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space.
Examples using sklearn.cluster.MiniBatchKMeans
Biclustering documents with the Spectral Co-clustering algorithm
Online learning of a dictionary of parts of faces
Compare BIRCH and MiniBatchKMeans
Empirical evaluation of the impact of k-means initialization
Comparison of the K-Means and MiniBatchKMeans clustering algorithms
Comparing different clustering algorithms on toy datasets
Faces dataset decompositions
Clustering text documents using k-means | sklearn.modules.generated.sklearn.cluster.minibatchkmeans |
fit(X, y=None, sample_weight=None) [source]
Compute the centroids on X by chunking it into mini-batches. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight (default: None). New in version 0.20. Returns
self | sklearn.modules.generated.sklearn.cluster.minibatchkmeans#sklearn.cluster.MiniBatchKMeans.fit |
fit_predict(X, y=None, sample_weight=None) [source]
Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to. | sklearn.modules.generated.sklearn.cluster.minibatchkmeans#sklearn.cluster.MiniBatchKMeans.fit_predict |
fit_transform(X, y=None, sample_weight=None) [source]
Compute clustering and transform X to cluster-distance space. Equivalent to fit(X).transform(X), but more efficiently implemented. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space. | sklearn.modules.generated.sklearn.cluster.minibatchkmeans#sklearn.cluster.MiniBatchKMeans.fit_transform |
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. | sklearn.modules.generated.sklearn.cluster.minibatchkmeans#sklearn.cluster.MiniBatchKMeans.get_params |
partial_fit(X, y=None, sample_weight=None) [source]
Update k means estimate on a single mini-batch X. Parameters
Xarray-like of shape (n_samples, n_features)
Coordinates of the data points to cluster. It must be noted that X will be copied if it is not C-contiguous.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight (default: None). Returns
self | sklearn.modules.generated.sklearn.cluster.minibatchkmeans#sklearn.cluster.MiniBatchKMeans.partial_fit |
predict(X, sample_weight=None) [source]
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, cluster_centers_ is called the code book and each value returned by predict is the index of the closest code in the code book. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to predict.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight (default: None). Returns
labelsndarray of shape (n_samples,)
Index of the cluster each sample belongs to. | sklearn.modules.generated.sklearn.cluster.minibatchkmeans#sklearn.cluster.MiniBatchKMeans.predict |
score(X, y=None, sample_weight=None) [source]
Opposite of the value of X on the K-means objective. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data.
yIgnored
Not used, present here for API consistency by convention.
sample_weightarray-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations are assigned equal weight. Returns
scorefloat
Opposite of the value of X on the K-means objective. | sklearn.modules.generated.sklearn.cluster.minibatchkmeans#sklearn.cluster.MiniBatchKMeans.score |
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. | sklearn.modules.generated.sklearn.cluster.minibatchkmeans#sklearn.cluster.MiniBatchKMeans.set_params |
transform(X) [source]
Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by transform will typically be dense. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform. Returns
X_newndarray of shape (n_samples, n_clusters)
X transformed in the new space. | sklearn.modules.generated.sklearn.cluster.minibatchkmeans#sklearn.cluster.MiniBatchKMeans.transform |
class sklearn.cluster.OPTICS(*, min_samples=5, max_eps=inf, metric='minkowski', p=2, metric_params=None, cluster_method='xi', eps=None, xi=0.05, predecessor_correction=True, min_cluster_size=None, algorithm='auto', leaf_size=30, n_jobs=None) [source]
Estimate clustering structure from vector array. OPTICS (Ordering Points To Identify the Clustering Structure), closely related to DBSCAN, finds core sample of high density and expands clusters from them [1]. Unlike DBSCAN, keeps cluster hierarchy for a variable neighborhood radius. Better suited for usage on large datasets than the current sklearn implementation of DBSCAN. Clusters are then extracted using a DBSCAN-like method (cluster_method = ‘dbscan’) or an automatic technique proposed in [1] (cluster_method = ‘xi’). This implementation deviates from the original OPTICS by first performing k-nearest-neighborhood searches on all points to identify core sizes, then computing only the distances to unprocessed points when constructing the cluster order. Note that we do not employ a heap to manage the expansion candidates, so the time complexity will be O(n^2). Read more in the User Guide. Parameters
min_samplesint > 1 or float between 0 and 1, default=5
The number of samples in a neighborhood for a point to be considered as a core point. Also, up and down steep regions can’t have more than min_samples consecutive non-steep points. Expressed as an absolute number or a fraction of the number of samples (rounded to be at least 2).
max_epsfloat, default=np.inf
The maximum distance between two samples for one to be considered as in the neighborhood of the other. Default value of np.inf will identify clusters across all scales; reducing max_eps will result in shorter run times.
metricstr or callable, default=’minkowski’
Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy’s metrics, but is less efficient than passing the metric name as a string. If metric is “precomputed”, X is assumed to be a distance matrix and must be square. Valid values for metric are: from scikit-learn: [‘cityblock’, ‘cosine’, ‘euclidean’, ‘l1’, ‘l2’, ‘manhattan’] from scipy.spatial.distance: [‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘correlation’, ‘dice’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘yule’] See the documentation for scipy.spatial.distance for details on these metrics.
pint, default=2
Parameter for the Minkowski metric from pairwise_distances. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
metric_paramsdict, default=None
Additional keyword arguments for the metric function.
cluster_methodstr, default=’xi’
The extraction method used to extract clusters using the calculated reachability and ordering. Possible values are “xi” and “dbscan”.
epsfloat, default=None
The maximum distance between two samples for one to be considered as in the neighborhood of the other. By default it assumes the same value as max_eps. Used only when cluster_method='dbscan'.
xifloat between 0 and 1, default=0.05
Determines the minimum steepness on the reachability plot that constitutes a cluster boundary. For example, an upwards point in the reachability plot is defined by the ratio from one point to its successor being at most 1-xi. Used only when cluster_method='xi'.
predecessor_correctionbool, default=True
Correct clusters according to the predecessors calculated by OPTICS [2]. This parameter has minimal effect on most datasets. Used only when cluster_method='xi'.
min_cluster_sizeint > 1 or float between 0 and 1, default=None
Minimum number of samples in an OPTICS cluster, expressed as an absolute number or a fraction of the number of samples (rounded to be at least 2). If None, the value of min_samples is used instead. Used only when cluster_method='xi'.
algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’
Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree
‘kd_tree’ will use KDTree
‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. (default) Note: fitting on sparse input will override the setting of this parameter, using brute force.
leaf_sizeint, default=30
Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.
n_jobsint, default=None
The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes
labels_ndarray of shape (n_samples,)
Cluster labels for each point in the dataset given to fit(). Noisy samples and points which are not included in a leaf cluster of cluster_hierarchy_ are labeled as -1.
reachability_ndarray of shape (n_samples,)
Reachability distances per sample, indexed by object order. Use clust.reachability_[clust.ordering_] to access in cluster order.
ordering_ndarray of shape (n_samples,)
The cluster ordered list of sample indices.
core_distances_ndarray of shape (n_samples,)
Distance at which each sample becomes a core point, indexed by object order. Points which will never be core have a distance of inf. Use clust.core_distances_[clust.ordering_] to access in cluster order.
predecessor_ndarray of shape (n_samples,)
Point that a sample was reached from, indexed by object order. Seed points have a predecessor of -1.
cluster_hierarchy_ndarray of shape (n_clusters, 2)
The list of clusters in the form of [start, end] in each row, with all indices inclusive. The clusters are ordered according to (end, -start) (ascending) so that larger clusters encompassing smaller clusters come after those smaller ones. Since labels_ does not reflect the hierarchy, usually len(cluster_hierarchy_) > np.unique(optics.labels_). Please also note that these indices are of the ordering_, i.e. X[ordering_][start:end + 1] form a cluster. Only available when cluster_method='xi'. See also
DBSCAN
A similar clustering for a specified neighborhood radius (eps). Our implementation is optimized for runtime. References
1(1,2)
Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, and Jörg Sander. “OPTICS: ordering points to identify the clustering structure.” ACM SIGMOD Record 28, no. 2 (1999): 49-60.
2
Schubert, Erich, Michael Gertz. “Improving the Cluster Structure Extracted from OPTICS Plots.” Proc. of the Conference “Lernen, Wissen, Daten, Analysen” (LWDA) (2018): 318-329. Examples >>> from sklearn.cluster import OPTICS
>>> import numpy as np
>>> X = np.array([[1, 2], [2, 5], [3, 6],
... [8, 7], [8, 8], [7, 3]])
>>> clustering = OPTICS(min_samples=2).fit(X)
>>> clustering.labels_
array([0, 0, 0, 1, 1, 1])
Methods
fit(X[, y]) Perform OPTICS clustering.
fit_predict(X[, y]) Perform clustering on X and returns cluster labels.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]
Perform OPTICS clustering. Extracts an ordered list of points and reachability distances, and performs initial clustering using max_eps distance specified at OPTICS object instantiation. Parameters
Xndarray of shape (n_samples, n_features), or (n_samples, n_samples) if metric=’precomputed’
A feature array, or array of distances between samples if metric=’precomputed’.
yignored
Ignored. Returns
selfinstance of OPTICS
The instance.
fit_predict(X, y=None) [source]
Perform clustering on X and returns cluster labels. Parameters
Xarray-like of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present for API consistency by convention. Returns
labelsndarray of shape (n_samples,), dtype=np.int64
Cluster labels.
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.
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. | sklearn.modules.generated.sklearn.cluster.optics#sklearn.cluster.OPTICS |
sklearn.cluster.OPTICS
class sklearn.cluster.OPTICS(*, min_samples=5, max_eps=inf, metric='minkowski', p=2, metric_params=None, cluster_method='xi', eps=None, xi=0.05, predecessor_correction=True, min_cluster_size=None, algorithm='auto', leaf_size=30, n_jobs=None) [source]
Estimate clustering structure from vector array. OPTICS (Ordering Points To Identify the Clustering Structure), closely related to DBSCAN, finds core sample of high density and expands clusters from them [1]. Unlike DBSCAN, keeps cluster hierarchy for a variable neighborhood radius. Better suited for usage on large datasets than the current sklearn implementation of DBSCAN. Clusters are then extracted using a DBSCAN-like method (cluster_method = ‘dbscan’) or an automatic technique proposed in [1] (cluster_method = ‘xi’). This implementation deviates from the original OPTICS by first performing k-nearest-neighborhood searches on all points to identify core sizes, then computing only the distances to unprocessed points when constructing the cluster order. Note that we do not employ a heap to manage the expansion candidates, so the time complexity will be O(n^2). Read more in the User Guide. Parameters
min_samplesint > 1 or float between 0 and 1, default=5
The number of samples in a neighborhood for a point to be considered as a core point. Also, up and down steep regions can’t have more than min_samples consecutive non-steep points. Expressed as an absolute number or a fraction of the number of samples (rounded to be at least 2).
max_epsfloat, default=np.inf
The maximum distance between two samples for one to be considered as in the neighborhood of the other. Default value of np.inf will identify clusters across all scales; reducing max_eps will result in shorter run times.
metricstr or callable, default=’minkowski’
Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy’s metrics, but is less efficient than passing the metric name as a string. If metric is “precomputed”, X is assumed to be a distance matrix and must be square. Valid values for metric are: from scikit-learn: [‘cityblock’, ‘cosine’, ‘euclidean’, ‘l1’, ‘l2’, ‘manhattan’] from scipy.spatial.distance: [‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘correlation’, ‘dice’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘yule’] See the documentation for scipy.spatial.distance for details on these metrics.
pint, default=2
Parameter for the Minkowski metric from pairwise_distances. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
metric_paramsdict, default=None
Additional keyword arguments for the metric function.
cluster_methodstr, default=’xi’
The extraction method used to extract clusters using the calculated reachability and ordering. Possible values are “xi” and “dbscan”.
epsfloat, default=None
The maximum distance between two samples for one to be considered as in the neighborhood of the other. By default it assumes the same value as max_eps. Used only when cluster_method='dbscan'.
xifloat between 0 and 1, default=0.05
Determines the minimum steepness on the reachability plot that constitutes a cluster boundary. For example, an upwards point in the reachability plot is defined by the ratio from one point to its successor being at most 1-xi. Used only when cluster_method='xi'.
predecessor_correctionbool, default=True
Correct clusters according to the predecessors calculated by OPTICS [2]. This parameter has minimal effect on most datasets. Used only when cluster_method='xi'.
min_cluster_sizeint > 1 or float between 0 and 1, default=None
Minimum number of samples in an OPTICS cluster, expressed as an absolute number or a fraction of the number of samples (rounded to be at least 2). If None, the value of min_samples is used instead. Used only when cluster_method='xi'.
algorithm{‘auto’, ‘ball_tree’, ‘kd_tree’, ‘brute’}, default=’auto’
Algorithm used to compute the nearest neighbors: ‘ball_tree’ will use BallTree
‘kd_tree’ will use KDTree
‘brute’ will use a brute-force search. ‘auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit method. (default) Note: fitting on sparse input will override the setting of this parameter, using brute force.
leaf_sizeint, default=30
Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.
n_jobsint, default=None
The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Attributes
labels_ndarray of shape (n_samples,)
Cluster labels for each point in the dataset given to fit(). Noisy samples and points which are not included in a leaf cluster of cluster_hierarchy_ are labeled as -1.
reachability_ndarray of shape (n_samples,)
Reachability distances per sample, indexed by object order. Use clust.reachability_[clust.ordering_] to access in cluster order.
ordering_ndarray of shape (n_samples,)
The cluster ordered list of sample indices.
core_distances_ndarray of shape (n_samples,)
Distance at which each sample becomes a core point, indexed by object order. Points which will never be core have a distance of inf. Use clust.core_distances_[clust.ordering_] to access in cluster order.
predecessor_ndarray of shape (n_samples,)
Point that a sample was reached from, indexed by object order. Seed points have a predecessor of -1.
cluster_hierarchy_ndarray of shape (n_clusters, 2)
The list of clusters in the form of [start, end] in each row, with all indices inclusive. The clusters are ordered according to (end, -start) (ascending) so that larger clusters encompassing smaller clusters come after those smaller ones. Since labels_ does not reflect the hierarchy, usually len(cluster_hierarchy_) > np.unique(optics.labels_). Please also note that these indices are of the ordering_, i.e. X[ordering_][start:end + 1] form a cluster. Only available when cluster_method='xi'. See also
DBSCAN
A similar clustering for a specified neighborhood radius (eps). Our implementation is optimized for runtime. References
1(1,2)
Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, and Jörg Sander. “OPTICS: ordering points to identify the clustering structure.” ACM SIGMOD Record 28, no. 2 (1999): 49-60.
2
Schubert, Erich, Michael Gertz. “Improving the Cluster Structure Extracted from OPTICS Plots.” Proc. of the Conference “Lernen, Wissen, Daten, Analysen” (LWDA) (2018): 318-329. Examples >>> from sklearn.cluster import OPTICS
>>> import numpy as np
>>> X = np.array([[1, 2], [2, 5], [3, 6],
... [8, 7], [8, 8], [7, 3]])
>>> clustering = OPTICS(min_samples=2).fit(X)
>>> clustering.labels_
array([0, 0, 0, 1, 1, 1])
Methods
fit(X[, y]) Perform OPTICS clustering.
fit_predict(X[, y]) Perform clustering on X and returns cluster labels.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]
Perform OPTICS clustering. Extracts an ordered list of points and reachability distances, and performs initial clustering using max_eps distance specified at OPTICS object instantiation. Parameters
Xndarray of shape (n_samples, n_features), or (n_samples, n_samples) if metric=’precomputed’
A feature array, or array of distances between samples if metric=’precomputed’.
yignored
Ignored. Returns
selfinstance of OPTICS
The instance.
fit_predict(X, y=None) [source]
Perform clustering on X and returns cluster labels. Parameters
Xarray-like of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present for API consistency by convention. Returns
labelsndarray of shape (n_samples,), dtype=np.int64
Cluster labels.
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.
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.
Examples using sklearn.cluster.OPTICS
Demo of OPTICS clustering algorithm
Comparing different clustering algorithms on toy datasets | sklearn.modules.generated.sklearn.cluster.optics |
fit(X, y=None) [source]
Perform OPTICS clustering. Extracts an ordered list of points and reachability distances, and performs initial clustering using max_eps distance specified at OPTICS object instantiation. Parameters
Xndarray of shape (n_samples, n_features), or (n_samples, n_samples) if metric=’precomputed’
A feature array, or array of distances between samples if metric=’precomputed’.
yignored
Ignored. Returns
selfinstance of OPTICS
The instance. | sklearn.modules.generated.sklearn.cluster.optics#sklearn.cluster.OPTICS.fit |
fit_predict(X, y=None) [source]
Perform clustering on X and returns cluster labels. Parameters
Xarray-like of shape (n_samples, n_features)
Input data.
yIgnored
Not used, present for API consistency by convention. Returns
labelsndarray of shape (n_samples,), dtype=np.int64
Cluster labels. | sklearn.modules.generated.sklearn.cluster.optics#sklearn.cluster.OPTICS.fit_predict |
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. | sklearn.modules.generated.sklearn.cluster.optics#sklearn.cluster.OPTICS.get_params |
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. | sklearn.modules.generated.sklearn.cluster.optics#sklearn.cluster.OPTICS.set_params |
class sklearn.cluster.SpectralBiclustering(n_clusters=3, *, method='bistochastic', n_components=6, n_best=3, svd_method='randomized', n_svd_vecs=None, mini_batch=False, init='k-means++', n_init=10, n_jobs='deprecated', random_state=None) [source]
Spectral biclustering (Kluger, 2003). Partitions rows and columns under the assumption that the data has an underlying checkerboard structure. For instance, if there are two row partitions and three column partitions, each row will belong to three biclusters, and each column will belong to two biclusters. The outer product of the corresponding row and column label vectors gives this checkerboard structure. Read more in the User Guide. Parameters
n_clustersint or tuple (n_row_clusters, n_column_clusters), default=3
The number of row and column clusters in the checkerboard structure.
method{‘bistochastic’, ‘scale’, ‘log’}, default=’bistochastic’
Method of normalizing and converting singular vectors into biclusters. May be one of ‘scale’, ‘bistochastic’, or ‘log’. The authors recommend using ‘log’. If the data is sparse, however, log normalization will not work, which is why the default is ‘bistochastic’. Warning if method='log', the data must be sparse.
n_componentsint, default=6
Number of singular vectors to check.
n_bestint, default=3
Number of best singular vectors to which to project the data for clustering.
svd_method{‘randomized’, ‘arpack’}, default=’randomized’
Selects the algorithm for finding singular vectors. May be ‘randomized’ or ‘arpack’. If ‘randomized’, uses randomized_svd, which may be faster for large matrices. If ‘arpack’, uses scipy.sparse.linalg.svds, which is more accurate, but possibly slower in some cases.
n_svd_vecsint, default=None
Number of vectors to use in calculating the SVD. Corresponds to ncv when svd_method=arpack and n_oversamples when svd_method is ‘randomized`.
mini_batchbool, default=False
Whether to use mini-batch k-means, which is faster but may get different results.
init{‘k-means++’, ‘random’} or ndarray of (n_clusters, n_features), default=’k-means++’
Method for initialization of k-means algorithm; defaults to ‘k-means++’.
n_initint, default=10
Number of random initializations that are tried with the k-means algorithm. If mini-batch k-means is used, the best initialization is chosen and the algorithm runs once. Otherwise, the algorithm is run for each initialization and the best solution chosen.
n_jobsint, default=None
The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Deprecated since version 0.23: n_jobs was deprecated in version 0.23 and will be removed in 1.0 (renaming of 0.25).
random_stateint, RandomState instance, default=None
Used for randomizing the singular value decomposition and the k-means initialization. Use an int to make the randomness deterministic. See Glossary. Attributes
rows_array-like of shape (n_row_clusters, n_rows)
Results of the clustering. rows[i, r] is True if cluster i contains row r. Available only after calling fit.
columns_array-like of shape (n_column_clusters, n_columns)
Results of the clustering, like rows.
row_labels_array-like of shape (n_rows,)
Row partition labels.
column_labels_array-like of shape (n_cols,)
Column partition labels. References Kluger, Yuval, et. al., 2003. Spectral biclustering of microarray data: coclustering genes and conditions. Examples >>> from sklearn.cluster import SpectralBiclustering
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
... [4, 7], [3, 5], [3, 6]])
>>> clustering = SpectralBiclustering(n_clusters=2, random_state=0).fit(X)
>>> clustering.row_labels_
array([1, 1, 1, 0, 0, 0], dtype=int32)
>>> clustering.column_labels_
array([0, 1], dtype=int32)
>>> clustering
SpectralBiclustering(n_clusters=2, random_state=0)
Methods
fit(X[, y]) Creates a biclustering for X.
get_indices(i) Row and column indices of the i’th bicluster.
get_params([deep]) Get parameters for this estimator.
get_shape(i) Shape of the i’th bicluster.
get_submatrix(i, data) Return the submatrix corresponding to bicluster i.
set_params(**params) Set the parameters of this estimator.
property biclusters_
Convenient way to get row and column indicators together. Returns the rows_ and columns_ members.
fit(X, y=None) [source]
Creates a biclustering for X. Parameters
Xarray-like of shape (n_samples, n_features)
yIgnored
get_indices(i) [source]
Row and column indices of the i’th bicluster. Only works if rows_ and columns_ attributes exist. Parameters
iint
The index of the cluster. Returns
row_indndarray, dtype=np.intp
Indices of rows in the dataset that belong to the bicluster.
col_indndarray, dtype=np.intp
Indices of columns in the dataset that belong to the bicluster.
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_shape(i) [source]
Shape of the i’th bicluster. Parameters
iint
The index of the cluster. Returns
n_rowsint
Number of rows in the bicluster.
n_colsint
Number of columns in the bicluster.
get_submatrix(i, data) [source]
Return the submatrix corresponding to bicluster i. Parameters
iint
The index of the cluster.
dataarray-like of shape (n_samples, n_features)
The data. Returns
submatrixndarray of shape (n_rows, n_cols)
The submatrix corresponding to bicluster i. Notes Works with sparse matrices. Only works if rows_ and columns_ attributes exist.
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. | sklearn.modules.generated.sklearn.cluster.spectralbiclustering#sklearn.cluster.SpectralBiclustering |
sklearn.cluster.SpectralBiclustering
class sklearn.cluster.SpectralBiclustering(n_clusters=3, *, method='bistochastic', n_components=6, n_best=3, svd_method='randomized', n_svd_vecs=None, mini_batch=False, init='k-means++', n_init=10, n_jobs='deprecated', random_state=None) [source]
Spectral biclustering (Kluger, 2003). Partitions rows and columns under the assumption that the data has an underlying checkerboard structure. For instance, if there are two row partitions and three column partitions, each row will belong to three biclusters, and each column will belong to two biclusters. The outer product of the corresponding row and column label vectors gives this checkerboard structure. Read more in the User Guide. Parameters
n_clustersint or tuple (n_row_clusters, n_column_clusters), default=3
The number of row and column clusters in the checkerboard structure.
method{‘bistochastic’, ‘scale’, ‘log’}, default=’bistochastic’
Method of normalizing and converting singular vectors into biclusters. May be one of ‘scale’, ‘bistochastic’, or ‘log’. The authors recommend using ‘log’. If the data is sparse, however, log normalization will not work, which is why the default is ‘bistochastic’. Warning if method='log', the data must be sparse.
n_componentsint, default=6
Number of singular vectors to check.
n_bestint, default=3
Number of best singular vectors to which to project the data for clustering.
svd_method{‘randomized’, ‘arpack’}, default=’randomized’
Selects the algorithm for finding singular vectors. May be ‘randomized’ or ‘arpack’. If ‘randomized’, uses randomized_svd, which may be faster for large matrices. If ‘arpack’, uses scipy.sparse.linalg.svds, which is more accurate, but possibly slower in some cases.
n_svd_vecsint, default=None
Number of vectors to use in calculating the SVD. Corresponds to ncv when svd_method=arpack and n_oversamples when svd_method is ‘randomized`.
mini_batchbool, default=False
Whether to use mini-batch k-means, which is faster but may get different results.
init{‘k-means++’, ‘random’} or ndarray of (n_clusters, n_features), default=’k-means++’
Method for initialization of k-means algorithm; defaults to ‘k-means++’.
n_initint, default=10
Number of random initializations that are tried with the k-means algorithm. If mini-batch k-means is used, the best initialization is chosen and the algorithm runs once. Otherwise, the algorithm is run for each initialization and the best solution chosen.
n_jobsint, default=None
The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Deprecated since version 0.23: n_jobs was deprecated in version 0.23 and will be removed in 1.0 (renaming of 0.25).
random_stateint, RandomState instance, default=None
Used for randomizing the singular value decomposition and the k-means initialization. Use an int to make the randomness deterministic. See Glossary. Attributes
rows_array-like of shape (n_row_clusters, n_rows)
Results of the clustering. rows[i, r] is True if cluster i contains row r. Available only after calling fit.
columns_array-like of shape (n_column_clusters, n_columns)
Results of the clustering, like rows.
row_labels_array-like of shape (n_rows,)
Row partition labels.
column_labels_array-like of shape (n_cols,)
Column partition labels. References Kluger, Yuval, et. al., 2003. Spectral biclustering of microarray data: coclustering genes and conditions. Examples >>> from sklearn.cluster import SpectralBiclustering
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
... [4, 7], [3, 5], [3, 6]])
>>> clustering = SpectralBiclustering(n_clusters=2, random_state=0).fit(X)
>>> clustering.row_labels_
array([1, 1, 1, 0, 0, 0], dtype=int32)
>>> clustering.column_labels_
array([0, 1], dtype=int32)
>>> clustering
SpectralBiclustering(n_clusters=2, random_state=0)
Methods
fit(X[, y]) Creates a biclustering for X.
get_indices(i) Row and column indices of the i’th bicluster.
get_params([deep]) Get parameters for this estimator.
get_shape(i) Shape of the i’th bicluster.
get_submatrix(i, data) Return the submatrix corresponding to bicluster i.
set_params(**params) Set the parameters of this estimator.
property biclusters_
Convenient way to get row and column indicators together. Returns the rows_ and columns_ members.
fit(X, y=None) [source]
Creates a biclustering for X. Parameters
Xarray-like of shape (n_samples, n_features)
yIgnored
get_indices(i) [source]
Row and column indices of the i’th bicluster. Only works if rows_ and columns_ attributes exist. Parameters
iint
The index of the cluster. Returns
row_indndarray, dtype=np.intp
Indices of rows in the dataset that belong to the bicluster.
col_indndarray, dtype=np.intp
Indices of columns in the dataset that belong to the bicluster.
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_shape(i) [source]
Shape of the i’th bicluster. Parameters
iint
The index of the cluster. Returns
n_rowsint
Number of rows in the bicluster.
n_colsint
Number of columns in the bicluster.
get_submatrix(i, data) [source]
Return the submatrix corresponding to bicluster i. Parameters
iint
The index of the cluster.
dataarray-like of shape (n_samples, n_features)
The data. Returns
submatrixndarray of shape (n_rows, n_cols)
The submatrix corresponding to bicluster i. Notes Works with sparse matrices. Only works if rows_ and columns_ attributes exist.
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.
Examples using sklearn.cluster.SpectralBiclustering
A demo of the Spectral Biclustering algorithm | sklearn.modules.generated.sklearn.cluster.spectralbiclustering |
property biclusters_
Convenient way to get row and column indicators together. Returns the rows_ and columns_ members. | sklearn.modules.generated.sklearn.cluster.spectralbiclustering#sklearn.cluster.SpectralBiclustering.biclusters_ |
fit(X, y=None) [source]
Creates a biclustering for X. Parameters
Xarray-like of shape (n_samples, n_features)
yIgnored | sklearn.modules.generated.sklearn.cluster.spectralbiclustering#sklearn.cluster.SpectralBiclustering.fit |
get_indices(i) [source]
Row and column indices of the i’th bicluster. Only works if rows_ and columns_ attributes exist. Parameters
iint
The index of the cluster. Returns
row_indndarray, dtype=np.intp
Indices of rows in the dataset that belong to the bicluster.
col_indndarray, dtype=np.intp
Indices of columns in the dataset that belong to the bicluster. | sklearn.modules.generated.sklearn.cluster.spectralbiclustering#sklearn.cluster.SpectralBiclustering.get_indices |
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. | sklearn.modules.generated.sklearn.cluster.spectralbiclustering#sklearn.cluster.SpectralBiclustering.get_params |
get_shape(i) [source]
Shape of the i’th bicluster. Parameters
iint
The index of the cluster. Returns
n_rowsint
Number of rows in the bicluster.
n_colsint
Number of columns in the bicluster. | sklearn.modules.generated.sklearn.cluster.spectralbiclustering#sklearn.cluster.SpectralBiclustering.get_shape |
get_submatrix(i, data) [source]
Return the submatrix corresponding to bicluster i. Parameters
iint
The index of the cluster.
dataarray-like of shape (n_samples, n_features)
The data. Returns
submatrixndarray of shape (n_rows, n_cols)
The submatrix corresponding to bicluster i. Notes Works with sparse matrices. Only works if rows_ and columns_ attributes exist. | sklearn.modules.generated.sklearn.cluster.spectralbiclustering#sklearn.cluster.SpectralBiclustering.get_submatrix |
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. | sklearn.modules.generated.sklearn.cluster.spectralbiclustering#sklearn.cluster.SpectralBiclustering.set_params |
class sklearn.cluster.SpectralClustering(n_clusters=8, *, eigen_solver=None, n_components=None, random_state=None, n_init=10, gamma=1.0, affinity='rbf', n_neighbors=10, eigen_tol=0.0, assign_labels='kmeans', degree=3, coef0=1, kernel_params=None, n_jobs=None, verbose=False) [source]
Apply clustering to a projection of the normalized Laplacian. In practice Spectral Clustering is very useful when the structure of the individual clusters is highly non-convex or more generally when a measure of the center and spread of the cluster is not a suitable description of the complete cluster. For instance when clusters are nested circles on the 2D plane. If affinity is the adjacency matrix of a graph, this method can be used to find normalized graph cuts. When calling fit, an affinity matrix is constructed using either kernel function such the Gaussian (aka RBF) kernel of the euclidean distanced d(X, X): np.exp(-gamma * d(X,X) ** 2)
or a k-nearest neighbors connectivity matrix. Alternatively, using precomputed, a user-provided affinity matrix can be used. Read more in the User Guide. Parameters
n_clustersint, default=8
The dimension of the projection subspace.
eigen_solver{‘arpack’, ‘lobpcg’, ‘amg’}, default=None
The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities. If None, then 'arpack' is used.
n_componentsint, default=n_clusters
Number of eigen vectors to use for the spectral embedding
random_stateint, RandomState instance, default=None
A pseudo random number generator used for the initialization of the lobpcg eigen vectors decomposition when eigen_solver='amg' and by the K-Means initialization. Use an int to make the randomness deterministic. See Glossary.
n_initint, default=10
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.
gammafloat, default=1.0
Kernel coefficient for rbf, poly, sigmoid, laplacian and chi2 kernels. Ignored for affinity='nearest_neighbors'.
affinitystr or callable, default=’rbf’
How to construct the affinity matrix.
‘nearest_neighbors’ : construct the affinity matrix by computing a graph of nearest neighbors. ‘rbf’ : construct the affinity matrix using a radial basis function (RBF) kernel. ‘precomputed’ : interpret X as a precomputed affinity matrix. ‘precomputed_nearest_neighbors’ : interpret X as a sparse graph of precomputed nearest neighbors, and constructs the affinity matrix by selecting the n_neighbors nearest neighbors. one of the kernels supported by pairwise_kernels. Only kernels that produce similarity scores (non-negative values that increase with similarity) should be used. This property is not checked by the clustering algorithm.
n_neighborsint, default=10
Number of neighbors to use when constructing the affinity matrix using the nearest neighbors method. Ignored for affinity='rbf'.
eigen_tolfloat, default=0.0
Stopping criterion for eigendecomposition of the Laplacian matrix when eigen_solver='arpack'.
assign_labels{‘kmeans’, ‘discretize’}, default=’kmeans’
The strategy to use to assign labels in the embedding space. There are two ways to assign labels after the laplacian embedding. k-means can be applied and is a popular choice. But it can also be sensitive to initialization. Discretization is another approach which is less sensitive to random initialization.
degreefloat, default=3
Degree of the polynomial kernel. Ignored by other kernels.
coef0float, default=1
Zero coefficient for polynomial and sigmoid kernels. Ignored by other kernels.
kernel_paramsdict of str to any, default=None
Parameters (keyword arguments) and values for kernel passed as callable object. Ignored by other kernels.
n_jobsint, default=None
The number of parallel jobs to run when affinity='nearest_neighbors' or affinity='precomputed_nearest_neighbors'. The neighbors search will be done in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
verbosebool, default=False
Verbosity mode. New in version 0.24. Attributes
affinity_matrix_array-like of shape (n_samples, n_samples)
Affinity matrix used for clustering. Available only if after calling fit.
labels_ndarray of shape (n_samples,)
Labels of each point Notes If you have an affinity matrix, such as a distance matrix, for which 0 means identical elements, and high values means very dissimilar elements, it can be transformed in a similarity matrix that is well suited for the algorithm by applying the Gaussian (RBF, heat) kernel: np.exp(- dist_matrix ** 2 / (2. * delta ** 2))
Where delta is a free parameter representing the width of the Gaussian kernel. Another alternative is to take a symmetric version of the k nearest neighbors connectivity matrix of the points. If the pyamg package is installed, it is used: this greatly speeds up computation. References Normalized cuts and image segmentation, 2000 Jianbo Shi, Jitendra Malik http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.160.2324
A Tutorial on Spectral Clustering, 2007 Ulrike von Luxburg http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323
Multiclass spectral clustering, 2003 Stella X. Yu, Jianbo Shi https://www1.icsi.berkeley.edu/~stellayu/publication/doc/2003kwayICCV.pdf
Examples >>> from sklearn.cluster import SpectralClustering
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
... [4, 7], [3, 5], [3, 6]])
>>> clustering = SpectralClustering(n_clusters=2,
... assign_labels="discretize",
... random_state=0).fit(X)
>>> clustering.labels_
array([1, 1, 1, 0, 0, 0])
>>> clustering
SpectralClustering(assign_labels='discretize', n_clusters=2,
random_state=0)
Methods
fit(X[, y]) Perform spectral clustering from features, or affinity matrix.
fit_predict(X[, y]) Perform spectral clustering from features, or affinity matrix, and return cluster labels.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]
Perform spectral clustering from features, or affinity matrix. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse matrix is provided in a format other than csr_matrix, csc_matrix, or coo_matrix, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
self
fit_predict(X, y=None) [source]
Perform spectral clustering from features, or affinity matrix, and return cluster labels. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse matrix is provided in a format other than csr_matrix, csc_matrix, or coo_matrix, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels.
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.
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. | sklearn.modules.generated.sklearn.cluster.spectralclustering#sklearn.cluster.SpectralClustering |
sklearn.cluster.SpectralClustering
class sklearn.cluster.SpectralClustering(n_clusters=8, *, eigen_solver=None, n_components=None, random_state=None, n_init=10, gamma=1.0, affinity='rbf', n_neighbors=10, eigen_tol=0.0, assign_labels='kmeans', degree=3, coef0=1, kernel_params=None, n_jobs=None, verbose=False) [source]
Apply clustering to a projection of the normalized Laplacian. In practice Spectral Clustering is very useful when the structure of the individual clusters is highly non-convex or more generally when a measure of the center and spread of the cluster is not a suitable description of the complete cluster. For instance when clusters are nested circles on the 2D plane. If affinity is the adjacency matrix of a graph, this method can be used to find normalized graph cuts. When calling fit, an affinity matrix is constructed using either kernel function such the Gaussian (aka RBF) kernel of the euclidean distanced d(X, X): np.exp(-gamma * d(X,X) ** 2)
or a k-nearest neighbors connectivity matrix. Alternatively, using precomputed, a user-provided affinity matrix can be used. Read more in the User Guide. Parameters
n_clustersint, default=8
The dimension of the projection subspace.
eigen_solver{‘arpack’, ‘lobpcg’, ‘amg’}, default=None
The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities. If None, then 'arpack' is used.
n_componentsint, default=n_clusters
Number of eigen vectors to use for the spectral embedding
random_stateint, RandomState instance, default=None
A pseudo random number generator used for the initialization of the lobpcg eigen vectors decomposition when eigen_solver='amg' and by the K-Means initialization. Use an int to make the randomness deterministic. See Glossary.
n_initint, default=10
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.
gammafloat, default=1.0
Kernel coefficient for rbf, poly, sigmoid, laplacian and chi2 kernels. Ignored for affinity='nearest_neighbors'.
affinitystr or callable, default=’rbf’
How to construct the affinity matrix.
‘nearest_neighbors’ : construct the affinity matrix by computing a graph of nearest neighbors. ‘rbf’ : construct the affinity matrix using a radial basis function (RBF) kernel. ‘precomputed’ : interpret X as a precomputed affinity matrix. ‘precomputed_nearest_neighbors’ : interpret X as a sparse graph of precomputed nearest neighbors, and constructs the affinity matrix by selecting the n_neighbors nearest neighbors. one of the kernels supported by pairwise_kernels. Only kernels that produce similarity scores (non-negative values that increase with similarity) should be used. This property is not checked by the clustering algorithm.
n_neighborsint, default=10
Number of neighbors to use when constructing the affinity matrix using the nearest neighbors method. Ignored for affinity='rbf'.
eigen_tolfloat, default=0.0
Stopping criterion for eigendecomposition of the Laplacian matrix when eigen_solver='arpack'.
assign_labels{‘kmeans’, ‘discretize’}, default=’kmeans’
The strategy to use to assign labels in the embedding space. There are two ways to assign labels after the laplacian embedding. k-means can be applied and is a popular choice. But it can also be sensitive to initialization. Discretization is another approach which is less sensitive to random initialization.
degreefloat, default=3
Degree of the polynomial kernel. Ignored by other kernels.
coef0float, default=1
Zero coefficient for polynomial and sigmoid kernels. Ignored by other kernels.
kernel_paramsdict of str to any, default=None
Parameters (keyword arguments) and values for kernel passed as callable object. Ignored by other kernels.
n_jobsint, default=None
The number of parallel jobs to run when affinity='nearest_neighbors' or affinity='precomputed_nearest_neighbors'. The neighbors search will be done in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
verbosebool, default=False
Verbosity mode. New in version 0.24. Attributes
affinity_matrix_array-like of shape (n_samples, n_samples)
Affinity matrix used for clustering. Available only if after calling fit.
labels_ndarray of shape (n_samples,)
Labels of each point Notes If you have an affinity matrix, such as a distance matrix, for which 0 means identical elements, and high values means very dissimilar elements, it can be transformed in a similarity matrix that is well suited for the algorithm by applying the Gaussian (RBF, heat) kernel: np.exp(- dist_matrix ** 2 / (2. * delta ** 2))
Where delta is a free parameter representing the width of the Gaussian kernel. Another alternative is to take a symmetric version of the k nearest neighbors connectivity matrix of the points. If the pyamg package is installed, it is used: this greatly speeds up computation. References Normalized cuts and image segmentation, 2000 Jianbo Shi, Jitendra Malik http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.160.2324
A Tutorial on Spectral Clustering, 2007 Ulrike von Luxburg http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323
Multiclass spectral clustering, 2003 Stella X. Yu, Jianbo Shi https://www1.icsi.berkeley.edu/~stellayu/publication/doc/2003kwayICCV.pdf
Examples >>> from sklearn.cluster import SpectralClustering
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
... [4, 7], [3, 5], [3, 6]])
>>> clustering = SpectralClustering(n_clusters=2,
... assign_labels="discretize",
... random_state=0).fit(X)
>>> clustering.labels_
array([1, 1, 1, 0, 0, 0])
>>> clustering
SpectralClustering(assign_labels='discretize', n_clusters=2,
random_state=0)
Methods
fit(X[, y]) Perform spectral clustering from features, or affinity matrix.
fit_predict(X[, y]) Perform spectral clustering from features, or affinity matrix, and return cluster labels.
get_params([deep]) Get parameters for this estimator.
set_params(**params) Set the parameters of this estimator.
fit(X, y=None) [source]
Perform spectral clustering from features, or affinity matrix. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse matrix is provided in a format other than csr_matrix, csc_matrix, or coo_matrix, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
self
fit_predict(X, y=None) [source]
Perform spectral clustering from features, or affinity matrix, and return cluster labels. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse matrix is provided in a format other than csr_matrix, csc_matrix, or coo_matrix, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels.
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.
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.
Examples using sklearn.cluster.SpectralClustering
Comparing different clustering algorithms on toy datasets | sklearn.modules.generated.sklearn.cluster.spectralclustering |
fit(X, y=None) [source]
Perform spectral clustering from features, or affinity matrix. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse matrix is provided in a format other than csr_matrix, csc_matrix, or coo_matrix, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
self | sklearn.modules.generated.sklearn.cluster.spectralclustering#sklearn.cluster.SpectralClustering.fit |
fit_predict(X, y=None) [source]
Perform spectral clustering from features, or affinity matrix, and return cluster labels. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples)
Training instances to cluster, or similarities / affinities between instances if affinity='precomputed'. If a sparse matrix is provided in a format other than csr_matrix, csc_matrix, or coo_matrix, it will be converted into a sparse csr_matrix.
yIgnored
Not used, present here for API consistency by convention. Returns
labelsndarray of shape (n_samples,)
Cluster labels. | sklearn.modules.generated.sklearn.cluster.spectralclustering#sklearn.cluster.SpectralClustering.fit_predict |
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. | sklearn.modules.generated.sklearn.cluster.spectralclustering#sklearn.cluster.SpectralClustering.get_params |
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. | sklearn.modules.generated.sklearn.cluster.spectralclustering#sklearn.cluster.SpectralClustering.set_params |
class sklearn.cluster.SpectralCoclustering(n_clusters=3, *, svd_method='randomized', n_svd_vecs=None, mini_batch=False, init='k-means++', n_init=10, n_jobs='deprecated', random_state=None) [source]
Spectral Co-Clustering algorithm (Dhillon, 2001). Clusters rows and columns of an array X to solve the relaxed normalized cut of the bipartite graph created from X as follows: the edge between row vertex i and column vertex j has weight X[i, j]. The resulting bicluster structure is block-diagonal, since each row and each column belongs to exactly one bicluster. Supports sparse matrices, as long as they are nonnegative. Read more in the User Guide. Parameters
n_clustersint, default=3
The number of biclusters to find.
svd_method{‘randomized’, ‘arpack’}, default=’randomized’
Selects the algorithm for finding singular vectors. May be ‘randomized’ or ‘arpack’. If ‘randomized’, use sklearn.utils.extmath.randomized_svd, which may be faster for large matrices. If ‘arpack’, use scipy.sparse.linalg.svds, which is more accurate, but possibly slower in some cases.
n_svd_vecsint, default=None
Number of vectors to use in calculating the SVD. Corresponds to ncv when svd_method=arpack and n_oversamples when svd_method is ‘randomized`.
mini_batchbool, default=False
Whether to use mini-batch k-means, which is faster but may get different results.
init{‘k-means++’, ‘random’, or ndarray of shape (n_clusters, n_features), default=’k-means++’
Method for initialization of k-means algorithm; defaults to ‘k-means++’.
n_initint, default=10
Number of random initializations that are tried with the k-means algorithm. If mini-batch k-means is used, the best initialization is chosen and the algorithm runs once. Otherwise, the algorithm is run for each initialization and the best solution chosen.
n_jobsint, default=None
The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Deprecated since version 0.23: n_jobs was deprecated in version 0.23 and will be removed in 1.0 (renaming of 0.25).
random_stateint, RandomState instance, default=None
Used for randomizing the singular value decomposition and the k-means initialization. Use an int to make the randomness deterministic. See Glossary. Attributes
rows_array-like of shape (n_row_clusters, n_rows)
Results of the clustering. rows[i, r] is True if cluster i contains row r. Available only after calling fit.
columns_array-like of shape (n_column_clusters, n_columns)
Results of the clustering, like rows.
row_labels_array-like of shape (n_rows,)
The bicluster label of each row.
column_labels_array-like of shape (n_cols,)
The bicluster label of each column. References Dhillon, Inderjit S, 2001. Co-clustering documents and words using bipartite spectral graph partitioning. Examples >>> from sklearn.cluster import SpectralCoclustering
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
... [4, 7], [3, 5], [3, 6]])
>>> clustering = SpectralCoclustering(n_clusters=2, random_state=0).fit(X)
>>> clustering.row_labels_
array([0, 1, 1, 0, 0, 0], dtype=int32)
>>> clustering.column_labels_
array([0, 0], dtype=int32)
>>> clustering
SpectralCoclustering(n_clusters=2, random_state=0)
Methods
fit(X[, y]) Creates a biclustering for X.
get_indices(i) Row and column indices of the i’th bicluster.
get_params([deep]) Get parameters for this estimator.
get_shape(i) Shape of the i’th bicluster.
get_submatrix(i, data) Return the submatrix corresponding to bicluster i.
set_params(**params) Set the parameters of this estimator.
property biclusters_
Convenient way to get row and column indicators together. Returns the rows_ and columns_ members.
fit(X, y=None) [source]
Creates a biclustering for X. Parameters
Xarray-like of shape (n_samples, n_features)
yIgnored
get_indices(i) [source]
Row and column indices of the i’th bicluster. Only works if rows_ and columns_ attributes exist. Parameters
iint
The index of the cluster. Returns
row_indndarray, dtype=np.intp
Indices of rows in the dataset that belong to the bicluster.
col_indndarray, dtype=np.intp
Indices of columns in the dataset that belong to the bicluster.
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_shape(i) [source]
Shape of the i’th bicluster. Parameters
iint
The index of the cluster. Returns
n_rowsint
Number of rows in the bicluster.
n_colsint
Number of columns in the bicluster.
get_submatrix(i, data) [source]
Return the submatrix corresponding to bicluster i. Parameters
iint
The index of the cluster.
dataarray-like of shape (n_samples, n_features)
The data. Returns
submatrixndarray of shape (n_rows, n_cols)
The submatrix corresponding to bicluster i. Notes Works with sparse matrices. Only works if rows_ and columns_ attributes exist.
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. | sklearn.modules.generated.sklearn.cluster.spectralcoclustering#sklearn.cluster.SpectralCoclustering |
sklearn.cluster.SpectralCoclustering
class sklearn.cluster.SpectralCoclustering(n_clusters=3, *, svd_method='randomized', n_svd_vecs=None, mini_batch=False, init='k-means++', n_init=10, n_jobs='deprecated', random_state=None) [source]
Spectral Co-Clustering algorithm (Dhillon, 2001). Clusters rows and columns of an array X to solve the relaxed normalized cut of the bipartite graph created from X as follows: the edge between row vertex i and column vertex j has weight X[i, j]. The resulting bicluster structure is block-diagonal, since each row and each column belongs to exactly one bicluster. Supports sparse matrices, as long as they are nonnegative. Read more in the User Guide. Parameters
n_clustersint, default=3
The number of biclusters to find.
svd_method{‘randomized’, ‘arpack’}, default=’randomized’
Selects the algorithm for finding singular vectors. May be ‘randomized’ or ‘arpack’. If ‘randomized’, use sklearn.utils.extmath.randomized_svd, which may be faster for large matrices. If ‘arpack’, use scipy.sparse.linalg.svds, which is more accurate, but possibly slower in some cases.
n_svd_vecsint, default=None
Number of vectors to use in calculating the SVD. Corresponds to ncv when svd_method=arpack and n_oversamples when svd_method is ‘randomized`.
mini_batchbool, default=False
Whether to use mini-batch k-means, which is faster but may get different results.
init{‘k-means++’, ‘random’, or ndarray of shape (n_clusters, n_features), default=’k-means++’
Method for initialization of k-means algorithm; defaults to ‘k-means++’.
n_initint, default=10
Number of random initializations that are tried with the k-means algorithm. If mini-batch k-means is used, the best initialization is chosen and the algorithm runs once. Otherwise, the algorithm is run for each initialization and the best solution chosen.
n_jobsint, default=None
The number of jobs to use for the computation. This works by breaking down the pairwise matrix into n_jobs even slices and computing them in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Deprecated since version 0.23: n_jobs was deprecated in version 0.23 and will be removed in 1.0 (renaming of 0.25).
random_stateint, RandomState instance, default=None
Used for randomizing the singular value decomposition and the k-means initialization. Use an int to make the randomness deterministic. See Glossary. Attributes
rows_array-like of shape (n_row_clusters, n_rows)
Results of the clustering. rows[i, r] is True if cluster i contains row r. Available only after calling fit.
columns_array-like of shape (n_column_clusters, n_columns)
Results of the clustering, like rows.
row_labels_array-like of shape (n_rows,)
The bicluster label of each row.
column_labels_array-like of shape (n_cols,)
The bicluster label of each column. References Dhillon, Inderjit S, 2001. Co-clustering documents and words using bipartite spectral graph partitioning. Examples >>> from sklearn.cluster import SpectralCoclustering
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
... [4, 7], [3, 5], [3, 6]])
>>> clustering = SpectralCoclustering(n_clusters=2, random_state=0).fit(X)
>>> clustering.row_labels_
array([0, 1, 1, 0, 0, 0], dtype=int32)
>>> clustering.column_labels_
array([0, 0], dtype=int32)
>>> clustering
SpectralCoclustering(n_clusters=2, random_state=0)
Methods
fit(X[, y]) Creates a biclustering for X.
get_indices(i) Row and column indices of the i’th bicluster.
get_params([deep]) Get parameters for this estimator.
get_shape(i) Shape of the i’th bicluster.
get_submatrix(i, data) Return the submatrix corresponding to bicluster i.
set_params(**params) Set the parameters of this estimator.
property biclusters_
Convenient way to get row and column indicators together. Returns the rows_ and columns_ members.
fit(X, y=None) [source]
Creates a biclustering for X. Parameters
Xarray-like of shape (n_samples, n_features)
yIgnored
get_indices(i) [source]
Row and column indices of the i’th bicluster. Only works if rows_ and columns_ attributes exist. Parameters
iint
The index of the cluster. Returns
row_indndarray, dtype=np.intp
Indices of rows in the dataset that belong to the bicluster.
col_indndarray, dtype=np.intp
Indices of columns in the dataset that belong to the bicluster.
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_shape(i) [source]
Shape of the i’th bicluster. Parameters
iint
The index of the cluster. Returns
n_rowsint
Number of rows in the bicluster.
n_colsint
Number of columns in the bicluster.
get_submatrix(i, data) [source]
Return the submatrix corresponding to bicluster i. Parameters
iint
The index of the cluster.
dataarray-like of shape (n_samples, n_features)
The data. Returns
submatrixndarray of shape (n_rows, n_cols)
The submatrix corresponding to bicluster i. Notes Works with sparse matrices. Only works if rows_ and columns_ attributes exist.
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.
Examples using sklearn.cluster.SpectralCoclustering
A demo of the Spectral Co-Clustering algorithm
Biclustering documents with the Spectral Co-clustering algorithm | sklearn.modules.generated.sklearn.cluster.spectralcoclustering |
property biclusters_
Convenient way to get row and column indicators together. Returns the rows_ and columns_ members. | sklearn.modules.generated.sklearn.cluster.spectralcoclustering#sklearn.cluster.SpectralCoclustering.biclusters_ |
fit(X, y=None) [source]
Creates a biclustering for X. Parameters
Xarray-like of shape (n_samples, n_features)
yIgnored | sklearn.modules.generated.sklearn.cluster.spectralcoclustering#sklearn.cluster.SpectralCoclustering.fit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.