code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def inverse_transform(self, X, **params):
"""Apply `inverse_transform` for each step in a reverse order.
All estimators in the pipeline must support `inverse_transform`.
Parameters
----------
X : array-like of shape (n_samples, n_transformed_features)
Data samples, ... | Apply `inverse_transform` for each step in a reverse order.
All estimators in the pipeline must support `inverse_transform`.
Parameters
----------
X : array-like of shape (n_samples, n_transformed_features)
Data samples, where ``n_samples`` is the number of samples and
... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def score(self, X, y=None, sample_weight=None, **params):
"""Transform the data, and apply `score` with the final estimator.
Call `transform` of each transformer in the pipeline. The transformed
data are finally passed to the final estimator that calls
`score` method. Only valid if the ... | Transform the data, and apply `score` with the final estimator.
Call `transform` of each transformer in the pipeline. The transformed
data are finally passed to the final estimator that calls
`score` method. Only valid if the final estimator implements `score`.
Parameters
-----... | score | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def get_feature_names_out(self, input_features=None):
"""Get output feature names for transformation.
Transform input features using the pipeline.
Parameters
----------
input_features : array-like of str or None, default=None
Input features.
Returns
... | Get output feature names for transformation.
Transform input features using the pipeline.
Parameters
----------
input_features : array-like of str or None, default=None
Input features.
Returns
-------
feature_names_out : ndarray of str objects
... | get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def __sklearn_is_fitted__(self):
"""Indicate whether pipeline has been fit.
This is done by checking whether the last non-`passthrough` step of the
pipeline is fitted.
An empty pipeline is considered fitted.
"""
# First find the last step that is not 'passthrough'
... | Indicate whether pipeline has been fit.
This is done by checking whether the last non-`passthrough` step of the
pipeline is fitted.
An empty pipeline is considered fitted.
| __sklearn_is_fitted__ | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def _transform_one(transformer, X, y, weight, params):
"""Call transform and apply weight to output.
Parameters
----------
transformer : estimator
Estimator to be used for transformation.
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Input data to be transformed.... | Call transform and apply weight to output.
Parameters
----------
transformer : estimator
Estimator to be used for transformation.
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Input data to be transformed.
y : ndarray of shape (n_samples,)
Ignored.
... | _transform_one | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def _fit_transform_one(
transformer, X, y, weight, message_clsname="", message=None, params=None
):
"""
Fits ``transformer`` to ``X`` and ``y``. The transformed result is returned
with the fitted transformer. If ``weight`` is not ``None``, the result will
be multiplied by ``weight``.
``params``... |
Fits ``transformer`` to ``X`` and ``y``. The transformed result is returned
with the fitted transformer. If ``weight`` is not ``None``, the result will
be multiplied by ``weight``.
``params`` needs to be of the form ``process_routing()["step_name"]``.
| _fit_transform_one | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def set_output(self, *, transform=None):
"""Set the output container when `"transform"` and `"fit_transform"` are called.
`set_output` will set the output of all estimators in `transformer_list`.
Parameters
----------
transform : {"default", "pandas", "polars"}, default=None
... | Set the output container when `"transform"` and `"fit_transform"` are called.
`set_output` will set the output of all estimators in `transformer_list`.
Parameters
----------
transform : {"default", "pandas", "polars"}, default=None
Configure output of `transform` and `fit_t... | set_output | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def _iter(self):
"""
Generate (name, trans, weight) tuples excluding None and
'drop' transformers.
"""
get_weight = (self.transformer_weights or {}).get
for name, trans in self.transformer_list:
if trans == "drop":
continue
if tra... |
Generate (name, trans, weight) tuples excluding None and
'drop' transformers.
| _iter | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def get_feature_names_out(self, input_features=None):
"""Get output feature names for transformation.
Parameters
----------
input_features : array-like of str or None, default=None
Input features.
Returns
-------
feature_names_out : ndarray of str ob... | Get output feature names for transformation.
Parameters
----------
input_features : array-like of str or None, default=None
Input features.
Returns
-------
feature_names_out : ndarray of str objects
Transformed feature names.
| get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def _add_prefix_for_feature_names_out(self, transformer_with_feature_names_out):
"""Add prefix for feature names out that includes the transformer names.
Parameters
----------
transformer_with_feature_names_out : list of tuples of (str, array-like of str)
The tuple consisten... | Add prefix for feature names out that includes the transformer names.
Parameters
----------
transformer_with_feature_names_out : list of tuples of (str, array-like of str)
The tuple consistent of the transformer's name and its feature names out.
Returns
-------
... | _add_prefix_for_feature_names_out | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def fit(self, X, y=None, **fit_params):
"""Fit all transformers using X.
Parameters
----------
X : iterable or array-like, depending on transformers
Input data, used to fit transformers.
y : array-like of shape (n_samples, n_outputs), default=None
Target... | Fit all transformers using X.
Parameters
----------
X : iterable or array-like, depending on transformers
Input data, used to fit transformers.
y : array-like of shape (n_samples, n_outputs), default=None
Targets for supervised learning.
**fit_params : ... | fit | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def fit_transform(self, X, y=None, **params):
"""Fit all transformers, transform the data and concatenate results.
Parameters
----------
X : iterable or array-like, depending on transformers
Input data to be transformed.
y : array-like of shape (n_samples, n_outputs... | Fit all transformers, transform the data and concatenate results.
Parameters
----------
X : iterable or array-like, depending on transformers
Input data to be transformed.
y : array-like of shape (n_samples, n_outputs), default=None
Targets for supervised learni... | fit_transform | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def _parallel_func(self, X, y, func, routed_params):
"""Runs func in parallel on X and y"""
self.transformer_list = list(self.transformer_list)
self._validate_transformers()
self._validate_transformer_weights()
transformers = list(self._iter())
return Parallel(n_jobs=sel... | Runs func in parallel on X and y | _parallel_func | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def transform(self, X, **params):
"""Transform X separately by each transformer, concatenate results.
Parameters
----------
X : iterable or array-like, depending on transformers
Input data to be transformed.
**params : dict, default=None
Parameters rout... | Transform X separately by each transformer, concatenate results.
Parameters
----------
X : iterable or array-like, depending on transformers
Input data to be transformed.
**params : dict, default=None
Parameters routed to the `transform` method of the sub-trans... | transform | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def get_metadata_routing(self):
"""Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.5
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.met... | Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.5
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating... | get_metadata_routing | python | scikit-learn/scikit-learn | sklearn/pipeline.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py | BSD-3-Clause |
def johnson_lindenstrauss_min_dim(n_samples, *, eps=0.1):
"""Find a 'safe' number of components to randomly project to.
The distortion introduced by a random projection `p` only changes the
distance between two points by a factor (1 +- eps) in a euclidean space
with good probability. The projection `p`... | Find a 'safe' number of components to randomly project to.
The distortion introduced by a random projection `p` only changes the
distance between two points by a factor (1 +- eps) in a euclidean space
with good probability. The projection `p` is an eps-embedding as defined
by:
.. code-block:: text... | johnson_lindenstrauss_min_dim | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def _check_density(density, n_features):
"""Factorize density check according to Li et al."""
if density == "auto":
density = 1 / np.sqrt(n_features)
elif density <= 0 or density > 1:
raise ValueError("Expected density in range ]0, 1], got: %r" % density)
return density | Factorize density check according to Li et al. | _check_density | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def _check_input_size(n_components, n_features):
"""Factorize argument checking for random matrix generation."""
if n_components <= 0:
raise ValueError(
"n_components must be strictly positive, got %d" % n_components
)
if n_features <= 0:
raise ValueError("n_features must... | Factorize argument checking for random matrix generation. | _check_input_size | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def _gaussian_random_matrix(n_components, n_features, random_state=None):
"""Generate a dense Gaussian random matrix.
The components of the random matrix are drawn from
N(0, 1.0 / n_components).
Read more in the :ref:`User Guide <gaussian_random_matrix>`.
Parameters
----------
n_comp... | Generate a dense Gaussian random matrix.
The components of the random matrix are drawn from
N(0, 1.0 / n_components).
Read more in the :ref:`User Guide <gaussian_random_matrix>`.
Parameters
----------
n_components : int,
Dimensionality of the target projection space.
n_featu... | _gaussian_random_matrix | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def _make_random_matrix(self, n_components, n_features):
"""Generate the random projection matrix.
Parameters
----------
n_components : int,
Dimensionality of the target projection space.
n_features : int,
Dimensionality of the original source space.
... | Generate the random projection matrix.
Parameters
----------
n_components : int,
Dimensionality of the target projection space.
n_features : int,
Dimensionality of the original source space.
Returns
-------
components : {ndarray, sparse ... | _make_random_matrix | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def _compute_inverse_components(self):
"""Compute the pseudo-inverse of the (densified) components."""
components = self.components_
if sp.issparse(components):
components = components.toarray()
return linalg.pinv(components, check_finite=False) | Compute the pseudo-inverse of the (densified) components. | _compute_inverse_components | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Generate a sparse random projection matrix.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training set: only the shape is used to find optimal random
matrix dimensions based on the theory referenc... | Generate a sparse random projection matrix.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training set: only the shape is used to find optimal random
matrix dimensions based on the theory referenced in the
afore mentioned... | fit | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def inverse_transform(self, X):
"""Project data back to its original space.
Returns an array X_original whose transform would be X. Note that even
if X is sparse, X_original is dense: this may use a lot of RAM.
If `compute_inverse_components` is False, the inverse of the components is
... | Project data back to its original space.
Returns an array X_original whose transform would be X. Note that even
if X is sparse, X_original is dense: this may use a lot of RAM.
If `compute_inverse_components` is False, the inverse of the components is
computed during each call to `inver... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def _make_random_matrix(self, n_components, n_features):
"""Generate the random projection matrix.
Parameters
----------
n_components : int,
Dimensionality of the target projection space.
n_features : int,
Dimensionality of the original source space.
... | Generate the random projection matrix.
Parameters
----------
n_components : int,
Dimensionality of the target projection space.
n_features : int,
Dimensionality of the original source space.
Returns
-------
components : ndarray of shape ... | _make_random_matrix | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def transform(self, X):
"""Project the data by using matrix product with the random matrix.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The input data to project into a smaller dimensional space.
Returns
-------
... | Project the data by using matrix product with the random matrix.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The input data to project into a smaller dimensional space.
Returns
-------
X_new : ndarray of shape (n_sampl... | transform | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def _make_random_matrix(self, n_components, n_features):
"""Generate the random projection matrix
Parameters
----------
n_components : int
Dimensionality of the target projection space.
n_features : int
Dimensionality of the original source space.
... | Generate the random projection matrix
Parameters
----------
n_components : int
Dimensionality of the target projection space.
n_features : int
Dimensionality of the original source space.
Returns
-------
components : sparse matrix of sha... | _make_random_matrix | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def transform(self, X):
"""Project the data by using matrix product with the random matrix.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The input data to project into a smaller dimensional space.
Returns
-------
... | Project the data by using matrix product with the random matrix.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The input data to project into a smaller dimensional space.
Returns
-------
X_new : {ndarray, sparse matrix} ... | transform | python | scikit-learn/scikit-learn | sklearn/random_projection.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/random_projection.py | BSD-3-Clause |
def _get_threadlocal_config():
"""Get a threadlocal **mutable** configuration. If the configuration
does not exist, copy the default global configuration."""
if not hasattr(_threadlocal, "global_config"):
_threadlocal.global_config = _global_config.copy()
return _threadlocal.global_config | Get a threadlocal **mutable** configuration. If the configuration
does not exist, copy the default global configuration. | _get_threadlocal_config | python | scikit-learn/scikit-learn | sklearn/_config.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_config.py | BSD-3-Clause |
def get_config():
"""Retrieve current values for configuration set by :func:`set_config`.
Returns
-------
config : dict
Keys are parameter names that can be passed to :func:`set_config`.
See Also
--------
config_context : Context manager for global scikit-learn configuration.
s... | Retrieve current values for configuration set by :func:`set_config`.
Returns
-------
config : dict
Keys are parameter names that can be passed to :func:`set_config`.
See Also
--------
config_context : Context manager for global scikit-learn configuration.
set_config : Set global sc... | get_config | python | scikit-learn/scikit-learn | sklearn/_config.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_config.py | BSD-3-Clause |
def setup_module(module):
"""Fixture for the tests to assure globally controllable seeding of RNGs"""
import numpy as np
# Check if a random seed exists in the environment, if not create one.
_random_seed = os.environ.get("SKLEARN_SEED", None)
if _random_seed is None:
_random_seed = np.ran... | Fixture for the tests to assure globally controllable seeding of RNGs | setup_module | python | scikit-learn/scikit-learn | sklearn/__init__.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/__init__.py | BSD-3-Clause |
def affinity_propagation(
S,
*,
preference=None,
convergence_iter=15,
max_iter=200,
damping=0.5,
copy=True,
verbose=False,
return_n_iter=False,
random_state=None,
):
"""Perform Affinity Propagation Clustering of data.
Read more in the :ref:`User Guide <affinity_propagati... | Perform Affinity Propagation Clustering of data.
Read more in the :ref:`User Guide <affinity_propagation>`.
Parameters
----------
S : array-like of shape (n_samples, n_samples)
Matrix of similarities between points.
preference : array-like of shape (n_samples,) or float, default=None
... | affinity_propagation | python | scikit-learn/scikit-learn | sklearn/cluster/_affinity_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_affinity_propagation.py | BSD-3-Clause |
def fit(self, X, y=None):
"""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 simila... | 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
... | fit | python | scikit-learn/scikit-learn | sklearn/cluster/_affinity_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_affinity_propagation.py | BSD-3-Clause |
def predict(self, X):
"""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_... | 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
... | predict | python | scikit-learn/scikit-learn | sklearn/cluster/_affinity_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_affinity_propagation.py | BSD-3-Clause |
def _fix_connectivity(X, connectivity, affinity):
"""
Fixes the connectivity matrix.
The different steps are:
- copies it
- makes it symmetric
- converts it to LIL if necessary
- completes it if necessary.
Parameters
----------
X : array-like of shape (n_samples, n_features)
... |
Fixes the connectivity matrix.
The different steps are:
- copies it
- makes it symmetric
- converts it to LIL if necessary
- completes it if necessary.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Feature matrix representing `n_samples` samples to... | _fix_connectivity | python | scikit-learn/scikit-learn | sklearn/cluster/_agglomerative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_agglomerative.py | BSD-3-Clause |
def _single_linkage_tree(
connectivity,
n_samples,
n_nodes,
n_clusters,
n_connected_components,
return_distance,
):
"""
Perform single linkage clustering on sparse data via the minimum
spanning tree from scipy.sparse.csgraph, then using union-find to label.
The parent array is th... |
Perform single linkage clustering on sparse data via the minimum
spanning tree from scipy.sparse.csgraph, then using union-find to label.
The parent array is then generated by walking through the tree.
| _single_linkage_tree | python | scikit-learn/scikit-learn | sklearn/cluster/_agglomerative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_agglomerative.py | BSD-3-Clause |
def _hc_cut(n_clusters, children, n_leaves):
"""Function cutting the ward tree for a given number of clusters.
Parameters
----------
n_clusters : int or ndarray
The number of clusters to form.
children : ndarray of shape (n_nodes-1, 2)
The children of each non-leaf node. Values les... | Function cutting the ward tree for a given number of clusters.
Parameters
----------
n_clusters : int or ndarray
The number of clusters to form.
children : ndarray of shape (n_nodes-1, 2)
The children of each non-leaf node. Values less than `n_samples`
correspond to leaves of t... | _hc_cut | python | scikit-learn/scikit-learn | sklearn/cluster/_agglomerative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_agglomerative.py | BSD-3-Clause |
def _fit(self, X):
"""Fit without validation
Parameters
----------
X : ndarray of shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, or distances between instances if
``metric='precomputed'``.
Returns
-------
... | Fit without validation
Parameters
----------
X : ndarray of shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, or distances between instances if
``metric='precomputed'``.
Returns
-------
self : object
... | _fit | python | scikit-learn/scikit-learn | sklearn/cluster/_agglomerative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_agglomerative.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the hierarchical clustering on the data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data.
y : Ignored
Not used, present here for API consistency by convention.
Returns
-----... | Fit the hierarchical clustering on the data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data.
y : Ignored
Not used, present here for API consistency by convention.
Returns
-------
self : object
... | fit | python | scikit-learn/scikit-learn | sklearn/cluster/_agglomerative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_agglomerative.py | BSD-3-Clause |
def _scale_normalize(X):
"""Normalize ``X`` by scaling rows and columns independently.
Returns the normalized matrix and the row and column scaling
factors.
"""
X = make_nonnegative(X)
row_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=1))).squeeze()
col_diag = np.asarray(1.0 / np.sqrt(X.sum(ax... | Normalize ``X`` by scaling rows and columns independently.
Returns the normalized matrix and the row and column scaling
factors.
| _scale_normalize | python | scikit-learn/scikit-learn | sklearn/cluster/_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bicluster.py | BSD-3-Clause |
def _bistochastic_normalize(X, max_iter=1000, tol=1e-5):
"""Normalize rows and columns of ``X`` simultaneously so that all
rows sum to one constant and all columns sum to a different
constant.
"""
# According to paper, this can also be done more efficiently with
# deviation reduction and balanci... | Normalize rows and columns of ``X`` simultaneously so that all
rows sum to one constant and all columns sum to a different
constant.
| _bistochastic_normalize | python | scikit-learn/scikit-learn | sklearn/cluster/_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bicluster.py | BSD-3-Clause |
def _log_normalize(X):
"""Normalize ``X`` according to Kluger's log-interactions scheme."""
X = make_nonnegative(X, min_value=1)
if issparse(X):
raise ValueError(
"Cannot compute log of a sparse matrix,"
" because log(x) diverges to -infinity as x"
" goes to 0."
... | Normalize ``X`` according to Kluger's log-interactions scheme. | _log_normalize | python | scikit-learn/scikit-learn | sklearn/cluster/_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bicluster.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Create a biclustering for X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
self ... | Create a biclustering for X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
self : object
SpectralBicluste... | fit | python | scikit-learn/scikit-learn | sklearn/cluster/_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bicluster.py | BSD-3-Clause |
def _svd(self, array, n_components, n_discard):
"""Returns first `n_components` left and right singular
vectors u and v, discarding the first `n_discard`.
"""
if self.svd_method == "randomized":
kwargs = {}
if self.n_svd_vecs is not None:
kwargs["n... | Returns first `n_components` left and right singular
vectors u and v, discarding the first `n_discard`.
| _svd | python | scikit-learn/scikit-learn | sklearn/cluster/_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bicluster.py | BSD-3-Clause |
def _fit_best_piecewise(self, vectors, n_best, n_clusters):
"""Find the ``n_best`` vectors that are best approximated by piecewise
constant vectors.
The piecewise vectors are found by k-means; the best is chosen
according to Euclidean distance.
"""
def make_piecewise(v... | Find the ``n_best`` vectors that are best approximated by piecewise
constant vectors.
The piecewise vectors are found by k-means; the best is chosen
according to Euclidean distance.
| _fit_best_piecewise | python | scikit-learn/scikit-learn | sklearn/cluster/_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bicluster.py | BSD-3-Clause |
def _project_and_cluster(self, data, vectors, n_clusters):
"""Project ``data`` to ``vectors`` and cluster the result."""
projected = safe_sparse_dot(data, vectors)
_, labels = self._k_means(projected, n_clusters)
return labels | Project ``data`` to ``vectors`` and cluster the result. | _project_and_cluster | python | scikit-learn/scikit-learn | sklearn/cluster/_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bicluster.py | BSD-3-Clause |
def _iterate_sparse_X(X):
"""This little hack returns a densified row when iterating over a sparse
matrix, instead of constructing a sparse matrix for every row that is
expensive.
"""
n_samples = X.shape[0]
X_indices = X.indices
X_data = X.data
X_indptr = X.indptr
for i in range(n_s... | This little hack returns a densified row when iterating over a sparse
matrix, instead of constructing a sparse matrix for every row that is
expensive.
| _iterate_sparse_X | python | scikit-learn/scikit-learn | sklearn/cluster/_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_birch.py | BSD-3-Clause |
def _split_node(node, threshold, branching_factor):
"""The node has to be split if there is no place for a new subcluster
in the node.
1. Two empty nodes and two empty subclusters are initialized.
2. The pair of distant subclusters are found.
3. The properties of the empty subclusters and nodes are ... | The node has to be split if there is no place for a new subcluster
in the node.
1. Two empty nodes and two empty subclusters are initialized.
2. The pair of distant subclusters are found.
3. The properties of the empty subclusters and nodes are updated
according to the nearest distance between th... | _split_node | python | scikit-learn/scikit-learn | sklearn/cluster/_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_birch.py | BSD-3-Clause |
def update_split_subclusters(self, subcluster, new_subcluster1, new_subcluster2):
"""Remove a subcluster from a node and update it with the
split subclusters.
"""
ind = self.subclusters_.index(subcluster)
self.subclusters_[ind] = new_subcluster1
self.init_centroids_[ind] ... | Remove a subcluster from a node and update it with the
split subclusters.
| update_split_subclusters | python | scikit-learn/scikit-learn | sklearn/cluster/_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_birch.py | BSD-3-Clause |
def insert_cf_subcluster(self, subcluster):
"""Insert a new subcluster into the node."""
if not self.subclusters_:
self.append_subcluster(subcluster)
return False
threshold = self.threshold
branching_factor = self.branching_factor
# We need to find the cl... | Insert a new subcluster into the node. | insert_cf_subcluster | python | scikit-learn/scikit-learn | sklearn/cluster/_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_birch.py | BSD-3-Clause |
def merge_subcluster(self, nominee_cluster, threshold):
"""Check if a cluster is worthy enough to be merged. If
yes then merge.
"""
new_ss = self.squared_sum_ + nominee_cluster.squared_sum_
new_ls = self.linear_sum_ + nominee_cluster.linear_sum_
new_n = self.n_samples_ + ... | Check if a cluster is worthy enough to be merged. If
yes then merge.
| merge_subcluster | python | scikit-learn/scikit-learn | sklearn/cluster/_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_birch.py | BSD-3-Clause |
def _get_leaves(self):
"""
Retrieve the leaves of the CF Node.
Returns
-------
leaves : list of shape (n_leaves,)
List of the leaf nodes.
"""
leaf_ptr = self.dummy_leaf_.next_leaf_
leaves = []
while leaf_ptr is not None:
le... |
Retrieve the leaves of the CF Node.
Returns
-------
leaves : list of shape (n_leaves,)
List of the leaf nodes.
| _get_leaves | python | scikit-learn/scikit-learn | sklearn/cluster/_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_birch.py | BSD-3-Clause |
def partial_fit(self, X=None, y=None):
"""
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 globa... |
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.
y : ... | partial_fit | python | scikit-learn/scikit-learn | sklearn/cluster/_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_birch.py | BSD-3-Clause |
def predict(self, X):
"""
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
-------
... |
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
-------
labels : ndarray of shape(n_sa... | predict | python | scikit-learn/scikit-learn | sklearn/cluster/_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_birch.py | BSD-3-Clause |
def _predict(self, X):
"""Predict data using the ``centroids_`` of subclusters."""
kwargs = {"Y_norm_squared": self._subcluster_norms}
with config_context(assume_finite=True):
argmin = pairwise_distances_argmin(
X, self.subcluster_centers_, metric_kwargs=kwargs
... | Predict data using the ``centroids_`` of subclusters. | _predict | python | scikit-learn/scikit-learn | sklearn/cluster/_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_birch.py | BSD-3-Clause |
def transform(self, X):
"""
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)
... |
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
... | transform | python | scikit-learn/scikit-learn | sklearn/cluster/_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_birch.py | BSD-3-Clause |
def _global_clustering(self, X=None):
"""
Global clustering for the subclusters obtained after fitting
"""
clusterer = self.n_clusters
centroids = self.subcluster_centers_
compute_labels = (X is not None) and self.compute_labels
# Preprocessing for the global clu... |
Global clustering for the subclusters obtained after fitting
| _global_clustering | python | scikit-learn/scikit-learn | sklearn/cluster/_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_birch.py | BSD-3-Clause |
def __init__(self, center, indices, score):
"""Create a new cluster node in the tree.
The node holds the center of this cluster and the indices of the data points
that belong to it.
"""
self.center = center
self.indices = indices
self.score = score
self.... | Create a new cluster node in the tree.
The node holds the center of this cluster and the indices of the data points
that belong to it.
| __init__ | python | scikit-learn/scikit-learn | sklearn/cluster/_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bisect_k_means.py | BSD-3-Clause |
def split(self, labels, centers, scores):
"""Split the cluster node into two subclusters."""
self.left = _BisectingTree(
indices=self.indices[labels == 0], center=centers[0], score=scores[0]
)
self.right = _BisectingTree(
indices=self.indices[labels == 1], center=... | Split the cluster node into two subclusters. | split | python | scikit-learn/scikit-learn | sklearn/cluster/_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bisect_k_means.py | BSD-3-Clause |
def get_cluster_to_bisect(self):
"""Return the cluster node to bisect next.
It's based on the score of the cluster, which can be either the number of
data points assigned to that cluster or the inertia of that cluster
(see `bisecting_strategy` for details).
"""
max_score... | Return the cluster node to bisect next.
It's based on the score of the cluster, which can be either the number of
data points assigned to that cluster or the inertia of that cluster
(see `bisecting_strategy` for details).
| get_cluster_to_bisect | python | scikit-learn/scikit-learn | sklearn/cluster/_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bisect_k_means.py | BSD-3-Clause |
def iter_leaves(self):
"""Iterate over all the cluster leaves in the tree."""
if self.left is None:
yield self
else:
yield from self.left.iter_leaves()
yield from self.right.iter_leaves() | Iterate over all the cluster leaves in the tree. | iter_leaves | python | scikit-learn/scikit-learn | sklearn/cluster/_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bisect_k_means.py | BSD-3-Clause |
def _warn_mkl_vcomp(self, n_active_threads):
"""Warn when vcomp and mkl are both present"""
warnings.warn(
"BisectingKMeans is known to have a memory leak on Windows "
"with MKL, when there are less chunks than available "
"threads. You can avoid it by setting the env... | Warn when vcomp and mkl are both present | _warn_mkl_vcomp | python | scikit-learn/scikit-learn | sklearn/cluster/_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bisect_k_means.py | BSD-3-Clause |
def _inertia_per_cluster(self, X, centers, labels, sample_weight):
"""Calculate the sum of squared errors (inertia) per cluster.
Parameters
----------
X : {ndarray, csr_matrix} of shape (n_samples, n_features)
The input samples.
centers : ndarray of shape (n_cluster... | Calculate the sum of squared errors (inertia) per cluster.
Parameters
----------
X : {ndarray, csr_matrix} of shape (n_samples, n_features)
The input samples.
centers : ndarray of shape (n_clusters=2, n_features)
The cluster centers.
labels : ndarray of... | _inertia_per_cluster | python | scikit-learn/scikit-learn | sklearn/cluster/_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bisect_k_means.py | BSD-3-Clause |
def _bisect(self, X, x_squared_norms, sample_weight, cluster_to_bisect):
"""Split a cluster into 2 subsclusters.
Parameters
----------
X : {ndarray, csr_matrix} of shape (n_samples, n_features)
Training instances to cluster.
x_squared_norms : ndarray of shape (n_sam... | Split a cluster into 2 subsclusters.
Parameters
----------
X : {ndarray, csr_matrix} of shape (n_samples, n_features)
Training instances to cluster.
x_squared_norms : ndarray of shape (n_samples,)
Squared euclidean norm of each data point.
sample_weight... | _bisect | python | scikit-learn/scikit-learn | sklearn/cluster/_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bisect_k_means.py | BSD-3-Clause |
def fit(self, X, y=None, sample_weight=None):
"""Compute bisecting k-means clustering.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster.
.. note:: The data will be converted to C ordering,
... | Compute bisecting k-means clustering.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster.
.. note:: The data will be converted to C ordering,
which will cause a memory copy
... | fit | python | scikit-learn/scikit-learn | sklearn/cluster/_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bisect_k_means.py | BSD-3-Clause |
def predict(self, X):
"""Predict which cluster each sample in X belongs to.
Prediction is made by going down the hierarchical tree
in searching of closest leaf cluster.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by ... | Predict which cluster each sample in X belongs to.
Prediction is made by going down the hierarchical tree
in searching of closest leaf cluster.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
... | predict | python | scikit-learn/scikit-learn | sklearn/cluster/_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bisect_k_means.py | BSD-3-Clause |
def _predict_recursive(self, X, sample_weight, cluster_node):
"""Predict recursively by going down the hierarchical tree.
Parameters
----------
X : {ndarray, csr_matrix} of shape (n_samples, n_features)
The data points, currently assigned to `cluster_node`, to predict betwee... | Predict recursively by going down the hierarchical tree.
Parameters
----------
X : {ndarray, csr_matrix} of shape (n_samples, n_features)
The data points, currently assigned to `cluster_node`, to predict between
the subclusters of this node.
sample_weight : ndar... | _predict_recursive | python | scikit-learn/scikit-learn | sklearn/cluster/_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_bisect_k_means.py | BSD-3-Clause |
def 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,
):
"""Perform DBSCAN clustering from vector array or distance matrix.
Read more in the :ref:`User Guide <dbscan>`.
... | Perform DBSCAN clustering from vector array or distance matrix.
Read more in the :ref:`User Guide <dbscan>`.
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... | dbscan | python | scikit-learn/scikit-learn | sklearn/cluster/_dbscan.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_dbscan.py | BSD-3-Clause |
def fit(self, X, y=None, sample_weight=None):
"""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 dis... | 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='precomput... | fit | python | scikit-learn/scikit-learn | sklearn/cluster/_dbscan.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_dbscan.py | BSD-3-Clause |
def transform(self, X):
"""
Transform a new matrix using the built clustering.
Parameters
----------
X : array-like of shape (n_samples, n_features) or \
(n_samples, n_samples)
A M by N array of M observations in N dimensions or a length
M... |
Transform a new matrix using the built clustering.
Parameters
----------
X : array-like of shape (n_samples, n_features) or (n_samples, n_samples)
A M by N array of M observations in N dimensions or a length
M array of M one-dimensional observati... | transform | python | scikit-learn/scikit-learn | sklearn/cluster/_feature_agglomeration.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_feature_agglomeration.py | BSD-3-Clause |
def inverse_transform(self, X):
"""
Inverse the transformation and return a vector of size `n_features`.
Parameters
----------
X : array-like of shape (n_samples, n_clusters) or (n_clusters,)
The values to be assigned to each cluster of samples.
Returns
... |
Inverse the transformation and return a vector of size `n_features`.
Parameters
----------
X : array-like of shape (n_samples, n_clusters) or (n_clusters,)
The values to be assigned to each cluster of samples.
Returns
-------
X_original : ndarray of... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/cluster/_feature_agglomeration.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_feature_agglomeration.py | BSD-3-Clause |
def kmeans_plusplus(
X,
n_clusters,
*,
sample_weight=None,
x_squared_norms=None,
random_state=None,
n_local_trials=None,
):
"""Init n_clusters seeds according to k-means++.
.. versionadded:: 0.24
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples,... | Init n_clusters seeds according to k-means++.
.. versionadded:: 0.24
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to pick seeds from.
n_clusters : int
The number of centroids to initialize.
sample_weight : array-like of shape... | kmeans_plusplus | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _kmeans_plusplus(
X, n_clusters, x_squared_norms, sample_weight, random_state, n_local_trials=None
):
"""Computational component for initialization of n_clusters by
k-means++. Prior validation of data is assumed.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_feat... | Computational component for initialization of n_clusters by
k-means++. Prior validation of data is assumed.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The data to pick seeds for.
n_clusters : int
The number of seeds to choose.
sample_we... | _kmeans_plusplus | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _tolerance(X, tol):
"""Return a tolerance which is dependent on the dataset."""
if tol == 0:
return 0
if sp.issparse(X):
variances = mean_variance_axis(X, axis=0)[1]
else:
variances = np.var(X, axis=0)
return np.mean(variances) * tol | Return a tolerance which is dependent on the dataset. | _tolerance | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def k_means(
X,
n_clusters,
*,
sample_weight=None,
init="k-means++",
n_init="auto",
max_iter=300,
verbose=False,
tol=1e-4,
random_state=None,
copy_x=True,
algorithm="lloyd",
return_n_iter=False,
):
"""Perform K-means clustering algorithm.
Read more in the :re... | Perform K-means clustering algorithm.
Read more in the :ref:`User Guide <k_means>`.
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 mem... | k_means | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _kmeans_single_elkan(
X,
sample_weight,
centers_init,
max_iter=300,
verbose=False,
tol=1e-4,
n_threads=1,
):
"""A single run of k-means elkan, assumes preparation completed prior.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
... | A single run of k-means elkan, assumes preparation completed prior.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The observations to cluster. If sparse matrix, must be in CSR format.
sample_weight : array-like of shape (n_samples,)
The weights for... | _kmeans_single_elkan | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _kmeans_single_lloyd(
X,
sample_weight,
centers_init,
max_iter=300,
verbose=False,
tol=1e-4,
n_threads=1,
):
"""A single run of k-means lloyd, assumes preparation completed prior.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
... | A single run of k-means lloyd, assumes preparation completed prior.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The observations to cluster. If sparse matrix, must be in CSR format.
sample_weight : ndarray of shape (n_samples,)
The weights for ea... | _kmeans_single_lloyd | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _labels_inertia(X, sample_weight, centers, n_threads=1, return_inertia=True):
"""E step of the K-means EM algorithm.
Compute the labels and the inertia of the given samples and centers.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The input sample... | E step of the K-means EM algorithm.
Compute the labels and the inertia of the given samples and centers.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The input samples to assign to the labels. If sparse matrix, must
be in CSR format.
sample_w... | _labels_inertia | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _warn_mkl_vcomp(self, n_active_threads):
"""Issue an estimator specific warning when vcomp and mkl are both present
This method is called by `_check_mkl_vcomp`.
""" | Issue an estimator specific warning when vcomp and mkl are both present
This method is called by `_check_mkl_vcomp`.
| _warn_mkl_vcomp | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _check_mkl_vcomp(self, X, n_samples):
"""Check when vcomp and mkl are both present"""
# The BLAS call inside a prange in lloyd_iter_chunked_dense is known to
# cause a small memory leak when there are less chunks than the number
# of available threads. It only happens when the OpenMP... | Check when vcomp and mkl are both present | _check_mkl_vcomp | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _validate_center_shape(self, X, centers):
"""Check if centers is compatible with X and n_clusters."""
if centers.shape[0] != self.n_clusters:
raise ValueError(
f"The shape of the initial centers {centers.shape} does not "
f"match the number of clusters {se... | Check if centers is compatible with X and n_clusters. | _validate_center_shape | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _init_centroids(
self,
X,
x_squared_norms,
init,
random_state,
sample_weight,
init_size=None,
n_centroids=None,
):
"""Compute the initial centroids.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_sam... | Compute the initial centroids.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The input samples.
x_squared_norms : ndarray of shape (n_samples,)
Squared euclidean norm of each data point. Pass it if you have it
at... | _init_centroids | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def predict(self, X):
"""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
-------... | 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, spar... | predict | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def transform(self, X):
"""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 : {arra... | 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_... | transform | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def score(self, X, y=None, sample_weight=None):
"""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.
y : Ignored
Not used, present here for API consistenc... | 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.
y : Ignored
Not used, present here for API consistency by convention.
sample_weight : array-like of sha... | score | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def fit(self, X, y=None, sample_weight=None):
"""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, whic... | 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 ... | fit | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _mini_batch_step(
X,
sample_weight,
centers,
centers_new,
weight_sums,
random_state,
random_reassign=False,
reassignment_ratio=0.01,
verbose=False,
n_threads=1,
):
"""Incremental update of the centers for the Minibatch K-Means algorithm.
Parameters
----------
... | Incremental update of the centers for the Minibatch K-Means algorithm.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The original data array. If sparse, must be in CSR format.
x_squared_norms : ndarray of shape (n_samples,)
Squared euclidean norm ... | _mini_batch_step | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _mini_batch_convergence(
self, step, n_steps, n_samples, centers_squared_diff, batch_inertia
):
"""Helper function to encapsulate the early stopping logic"""
# Normalize inertia to be able to compare values when
# batch_size changes
batch_inertia /= self._batch_size
... | Helper function to encapsulate the early stopping logic | _mini_batch_convergence | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def _random_reassign(self):
"""Check if a random reassignment needs to be done.
Do random reassignments each time 10 * n_clusters samples have been
processed.
If there are empty clusters we always want to reassign.
"""
self._n_since_last_reassign += self._batch_size
... | Check if a random reassignment needs to be done.
Do random reassignments each time 10 * n_clusters samples have been
processed.
If there are empty clusters we always want to reassign.
| _random_reassign | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def fit(self, X, y=None, sample_weight=None):
"""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... | 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 co... | fit | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def partial_fit(self, X, y=None, sample_weight=None):
"""Update k means estimate on a single mini-batch X.
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... | Update k means estimate on a single mini-batch X.
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
... | partial_fit | python | scikit-learn/scikit-learn | sklearn/cluster/_kmeans.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_kmeans.py | BSD-3-Clause |
def estimate_bandwidth(X, *, quantile=0.3, n_samples=None, random_state=0, n_jobs=None):
"""Estimate the bandwidth to use with the mean-shift algorithm.
This function takes time at least quadratic in `n_samples`. For large
datasets, it is wise to subsample by setting `n_samples`. Alternatively,
the par... | Estimate the bandwidth to use with the mean-shift algorithm.
This function takes time at least quadratic in `n_samples`. For large
datasets, it is wise to subsample by setting `n_samples`. Alternatively,
the parameter `bandwidth` can be set to a small value without estimating
it.
Parameters
--... | estimate_bandwidth | python | scikit-learn/scikit-learn | sklearn/cluster/_mean_shift.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_mean_shift.py | BSD-3-Clause |
def mean_shift(
X,
*,
bandwidth=None,
seeds=None,
bin_seeding=False,
min_bin_freq=1,
cluster_all=True,
max_iter=300,
n_jobs=None,
):
"""Perform mean shift clustering of data using a flat kernel.
Read more in the :ref:`User Guide <mean_shift>`.
Parameters
----------
... | Perform mean shift clustering of data using a flat kernel.
Read more in the :ref:`User Guide <mean_shift>`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data.
bandwidth : float, default=None
Kernel bandwidth. If not None, must be in the range [0, +i... | mean_shift | python | scikit-learn/scikit-learn | sklearn/cluster/_mean_shift.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_mean_shift.py | BSD-3-Clause |
def get_bin_seeds(X, bin_size, min_bin_freq=1):
"""Find seeds for mean_shift.
Finds seeds by first binning data onto a grid whose lines are
spaced bin_size apart, and then choosing those bins with at least
min_bin_freq points.
Parameters
----------
X : array-like of shape (n_samples, n_fe... | Find seeds for mean_shift.
Finds seeds by first binning data onto a grid whose lines are
spaced bin_size apart, and then choosing those bins with at least
min_bin_freq points.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input points, the same points that will... | get_bin_seeds | python | scikit-learn/scikit-learn | sklearn/cluster/_mean_shift.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_mean_shift.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Perform clustering.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Samples to cluster.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
self : ob... | Perform clustering.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Samples to cluster.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
self : object
Fitted instance.
... | fit | python | scikit-learn/scikit-learn | sklearn/cluster/_mean_shift.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_mean_shift.py | BSD-3-Clause |
def predict(self, X):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like of shape (n_samples, n_features)
New data to predict.
Returns
-------
labels : ndarray of shape (n_samples,)
Index of t... | Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like of shape (n_samples, n_features)
New data to predict.
Returns
-------
labels : ndarray of shape (n_samples,)
Index of the cluster each sample belongs to... | predict | python | scikit-learn/scikit-learn | sklearn/cluster/_mean_shift.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_mean_shift.py | BSD-3-Clause |
def fit(self, X, y=None):
"""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
----------
X : {ndarray, sparse... | 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
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_featu... | fit | python | scikit-learn/scikit-learn | sklearn/cluster/_optics.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_optics.py | BSD-3-Clause |
def _compute_core_distances_(X, neighbors, min_samples, working_memory):
"""Compute the k-th nearest neighbor of each sample.
Equivalent to neighbors.kneighbors(X, self.min_samples)[0][:, -1]
but with more memory efficiency.
Parameters
----------
X : array-like of shape (n_samples, n_features)... | Compute the k-th nearest neighbor of each sample.
Equivalent to neighbors.kneighbors(X, self.min_samples)[0][:, -1]
but with more memory efficiency.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data.
neighbors : NearestNeighbors instance
The fitted ... | _compute_core_distances_ | python | scikit-learn/scikit-learn | sklearn/cluster/_optics.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_optics.py | BSD-3-Clause |
def cluster_optics_dbscan(*, reachability, core_distances, ordering, eps):
"""Perform DBSCAN extraction for an arbitrary epsilon.
Extracting the clusters runs in linear time. Note that this results in
``labels_`` which are close to a :class:`~sklearn.cluster.DBSCAN` with
similar settings and ``eps``, o... | Perform DBSCAN extraction for an arbitrary epsilon.
Extracting the clusters runs in linear time. Note that this results in
``labels_`` which are close to a :class:`~sklearn.cluster.DBSCAN` with
similar settings and ``eps``, only if ``eps`` is close to ``max_eps``.
Parameters
----------
reachab... | cluster_optics_dbscan | python | scikit-learn/scikit-learn | sklearn/cluster/_optics.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_optics.py | BSD-3-Clause |
def cluster_optics_xi(
*,
reachability,
predecessor,
ordering,
min_samples,
min_cluster_size=None,
xi=0.05,
predecessor_correction=True,
):
"""Automatically extract clusters according to the Xi-steep method.
Parameters
----------
reachability : ndarray of shape (n_sample... | Automatically extract clusters according to the Xi-steep method.
Parameters
----------
reachability : ndarray of shape (n_samples,)
Reachability distances calculated by OPTICS (`reachability_`).
predecessor : ndarray of shape (n_samples,)
Predecessors calculated by OPTICS.
orderin... | cluster_optics_xi | python | scikit-learn/scikit-learn | sklearn/cluster/_optics.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_optics.py | BSD-3-Clause |
def _extend_region(steep_point, xward_point, start, min_samples):
"""Extend the area until it's maximal.
It's the same function for both upward and downward reagions, depending on
the given input parameters. Assuming:
- steep_{upward/downward}: bool array indicating whether a point is a
... | Extend the area until it's maximal.
It's the same function for both upward and downward reagions, depending on
the given input parameters. Assuming:
- steep_{upward/downward}: bool array indicating whether a point is a
steep {upward/downward};
- upward/downward: bool array indicating... | _extend_region | python | scikit-learn/scikit-learn | sklearn/cluster/_optics.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_optics.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.