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 _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 _warn_mkl_vcomp(self, n_active_threads):
"""Warn when vcomp and mkl are both present"""
warnings.warn(
"KMeans 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 environment"... | Warn when vcomp and mkl are both present | _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 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 _warn_mkl_vcomp(self, n_active_threads):
"""Warn when vcomp and mkl are both present"""
warnings.warn(
"MiniBatchKMeans is known to have a memory leak on "
"Windows with MKL, when there are less chunks than "
"available threads. You can prevent it by setting "
... | Warn when vcomp and mkl are both present | _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 _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 |
def _update_filter_sdas(sdas, mib, xi_complement, reachability_plot):
"""Update steep down areas (SDAs) using the new maximum in between (mib)
value, and the given complement of xi, i.e. ``1 - xi``.
"""
if np.isinf(mib):
return []
res = [
sda for sda in sdas if mib <= reachability_pl... | Update steep down areas (SDAs) using the new maximum in between (mib)
value, and the given complement of xi, i.e. ``1 - xi``.
| _update_filter_sdas | 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 _correct_predecessor(reachability_plot, predecessor_plot, ordering, s, e):
"""Correct for predecessors.
Applies Algorithm 2 of [1]_.
Input parameters are ordered by the computer OPTICS ordering.
.. [1] Schubert, Erich, Michael Gertz.
"Improving the Cluster Structure Extracted from OPTICS P... | Correct for predecessors.
Applies Algorithm 2 of [1]_.
Input parameters are ordered by the computer OPTICS ordering.
.. [1] Schubert, Erich, Michael Gertz.
"Improving the Cluster Structure Extracted from OPTICS Plots." Proc. of
the Conference "Lernen, Wissen, Daten, Analysen" (LWDA) (2018):... | _correct_predecessor | 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 _xi_cluster(
reachability_plot,
predecessor_plot,
ordering,
xi,
min_samples,
min_cluster_size,
predecessor_correction,
):
"""Automatically extract clusters according to the Xi-steep method.
This is rouphly an implementation of Figure 19 of the OPTICS paper.
Parameters
-... | Automatically extract clusters according to the Xi-steep method.
This is rouphly an implementation of Figure 19 of the OPTICS paper.
Parameters
----------
reachability_plot : array-like of shape (n_samples,)
The reachability plot, i.e. reachability ordered according to
the calculated o... | _xi_cluster | 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 _extract_xi_labels(ordering, clusters):
"""Extracts the labels from the clusters returned by `_xi_cluster`.
We rely on the fact that clusters are stored
with the smaller clusters coming before the larger ones.
Parameters
----------
ordering : array-like of shape (n_samples,)
The ord... | Extracts the labels from the clusters returned by `_xi_cluster`.
We rely on the fact that clusters are stored
with the smaller clusters coming before the larger ones.
Parameters
----------
ordering : array-like of shape (n_samples,)
The ordering of points calculated by OPTICS
clusters ... | _extract_xi_labels | 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_qr(vectors):
"""Find the discrete partition closest to the eigenvector embedding.
This implementation was proposed in [1]_.
.. versionadded:: 1.1
Parameters
----------
vectors : array-like, shape: (n_samples, n_clusters)
The embedding space of the sampl... | Find the discrete partition closest to the eigenvector embedding.
This implementation was proposed in [1]_.
.. versionadded:: 1.1
Parameters
----------
vectors : array-like, shape: (n_samples, n_clusters)
The embedding space of the samples.
Returns
---... | cluster_qr | python | scikit-learn/scikit-learn | sklearn/cluster/_spectral.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_spectral.py | BSD-3-Clause |
def discretize(
vectors, *, copy=True, max_svd_restarts=30, n_iter_max=20, random_state=None
):
"""Search for a partition matrix which is closest to the eigenvector embedding.
This implementation was proposed in [1]_.
Parameters
----------
vectors : array-like of shape (n_samples, n_clusters)
... | Search for a partition matrix which is closest to the eigenvector embedding.
This implementation was proposed in [1]_.
Parameters
----------
vectors : array-like of shape (n_samples, n_clusters)
The embedding space of the samples.
copy : bool, default=True
Whether to copy vectors,... | discretize | python | scikit-learn/scikit-learn | sklearn/cluster/_spectral.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_spectral.py | BSD-3-Clause |
def spectral_clustering(
affinity,
*,
n_clusters=8,
n_components=None,
eigen_solver=None,
random_state=None,
n_init=10,
eigen_tol="auto",
assign_labels="kmeans",
verbose=False,
):
"""Apply clustering to a projection of the normalized Laplacian.
In practice Spectral Clust... | 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.... | spectral_clustering | python | scikit-learn/scikit-learn | sklearn/cluster/_spectral.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_spectral.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Perform spectral clustering from features, or affinity matrix.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
(n_samples, n_samples)
Training instances to cluster, similarities / affini... | Perform spectral clustering from features, or affinity matrix.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples)
Training instances to cluster, similarities / affinities between
instances if `... | fit | python | scikit-learn/scikit-learn | sklearn/cluster/_spectral.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_spectral.py | BSD-3-Clause |
def test_affinity_propagation(global_random_seed, global_dtype):
"""Test consistency of the affinity propagations."""
S = -euclidean_distances(X.astype(global_dtype, copy=False), squared=True)
preference = np.median(S) * 10
cluster_centers_indices, labels = affinity_propagation(
S, preference=pr... | Test consistency of the affinity propagations. | test_affinity_propagation | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_affinity_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_affinity_propagation.py | BSD-3-Clause |
def test_affinity_propagation_precomputed():
"""Check equality of precomputed affinity matrix to internally computed affinity
matrix.
"""
S = -euclidean_distances(X, squared=True)
preference = np.median(S) * 10
af = AffinityPropagation(
preference=preference, affinity="precomputed", rand... | Check equality of precomputed affinity matrix to internally computed affinity
matrix.
| test_affinity_propagation_precomputed | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_affinity_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_affinity_propagation.py | BSD-3-Clause |
def test_affinity_propagation_no_copy():
"""Check behaviour of not copying the input data."""
S = -euclidean_distances(X, squared=True)
S_original = S.copy()
preference = np.median(S) * 10
assert not np.allclose(S.diagonal(), preference)
# with copy=True S should not be modified
affinity_pr... | Check behaviour of not copying the input data. | test_affinity_propagation_no_copy | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_affinity_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_affinity_propagation.py | BSD-3-Clause |
def test_affinity_propagation_affinity_shape():
"""Check the shape of the affinity matrix when using `affinity_propagation."""
S = -euclidean_distances(X, squared=True)
err_msg = "The matrix of similarities must be a square array"
with pytest.raises(ValueError, match=err_msg):
affinity_propagati... | Check the shape of the affinity matrix when using `affinity_propagation. | test_affinity_propagation_affinity_shape | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_affinity_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_affinity_propagation.py | BSD-3-Clause |
def test_affinity_propagation_random_state():
"""Check that different random states lead to different initialisations
by looking at the center locations after two iterations.
"""
centers = [[1, 1], [-1, -1], [1, -1]]
X, labels_true = make_blobs(
n_samples=300, centers=centers, cluster_std=0.... | Check that different random states lead to different initialisations
by looking at the center locations after two iterations.
| test_affinity_propagation_random_state | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_affinity_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_affinity_propagation.py | BSD-3-Clause |
def test_affinity_propagation_convergence_warning_dense_sparse(container, global_dtype):
"""
Check that having sparse or dense `centers` format should not
influence the convergence.
Non-regression test for gh-13334.
"""
centers = container(np.zeros((1, 10)))
rng = np.random.RandomState(42)
... |
Check that having sparse or dense `centers` format should not
influence the convergence.
Non-regression test for gh-13334.
| test_affinity_propagation_convergence_warning_dense_sparse | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_affinity_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_affinity_propagation.py | BSD-3-Clause |
def test_affinity_propagation_equal_points():
"""Make sure we do not assign multiple clusters to equal points.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/pull/20043
"""
X = np.zeros((8, 1))
af = AffinityPropagation(affinity="euclidean", damping=0.5, random_state=42).f... | Make sure we do not assign multiple clusters to equal points.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/pull/20043
| test_affinity_propagation_equal_points | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_affinity_propagation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_affinity_propagation.py | BSD-3-Clause |
def _do_scale_test(scaled):
"""Check that rows sum to one constant, and columns to another."""
row_sum = scaled.sum(axis=1)
col_sum = scaled.sum(axis=0)
if issparse(scaled):
row_sum = np.asarray(row_sum).squeeze()
col_sum = np.asarray(col_sum).squeeze()
assert_array_almost_equal(row_... | Check that rows sum to one constant, and columns to another. | _do_scale_test | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_bicluster.py | BSD-3-Clause |
def _do_bistochastic_test(scaled):
"""Check that rows and columns sum to the same constant."""
_do_scale_test(scaled)
assert_almost_equal(scaled.sum(axis=0).mean(), scaled.sum(axis=1).mean(), decimal=1) | Check that rows and columns sum to the same constant. | _do_bistochastic_test | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_bicluster.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_bicluster.py | BSD-3-Clause |
def check_threshold(birch_instance, threshold):
"""Use the leaf linked list for traversal"""
current_leaf = birch_instance.dummy_leaf_.next_leaf_
while current_leaf:
subclusters = current_leaf.subclusters_
for sc in subclusters:
assert threshold >= sc.radius
current_leaf ... | Use the leaf linked list for traversal | check_threshold | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_birch.py | BSD-3-Clause |
def test_both_subclusters_updated():
"""Check that both subclusters are updated when a node a split, even when there are
duplicated data points. Non-regression test for #23269.
"""
X = np.array(
[
[-2.6192791, -1.5053215],
[-2.9993038, -1.6863596],
[-2.372491... | Check that both subclusters are updated when a node a split, even when there are
duplicated data points. Non-regression test for #23269.
| test_both_subclusters_updated | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_birch.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_birch.py | BSD-3-Clause |
def test_three_clusters(bisecting_strategy, init):
"""Tries to perform bisect k-means for three clusters to check
if splitting data is performed correctly.
"""
X = np.array(
[[1, 1], [10, 1], [3, 1], [10, 0], [2, 1], [10, 2], [10, 8], [10, 9], [10, 10]]
)
bisect_means = BisectingKMeans(
... | Tries to perform bisect k-means for three clusters to check
if splitting data is performed correctly.
| test_three_clusters | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_bisect_k_means.py | BSD-3-Clause |
def test_sparse(csr_container):
"""Test Bisecting K-Means with sparse data.
Checks if labels and centers are the same between dense and sparse.
"""
rng = np.random.RandomState(0)
X = rng.rand(20, 2)
X[X < 0.8] = 0
X_csr = csr_container(X)
bisect_means = BisectingKMeans(n_clusters=3, ... | Test Bisecting K-Means with sparse data.
Checks if labels and centers are the same between dense and sparse.
| test_sparse | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_bisect_k_means.py | BSD-3-Clause |
def test_n_clusters(n_clusters):
"""Test if resulting labels are in range [0, n_clusters - 1]."""
rng = np.random.RandomState(0)
X = rng.rand(10, 2)
bisect_means = BisectingKMeans(n_clusters=n_clusters, random_state=0)
bisect_means.fit(X)
assert_array_equal(np.unique(bisect_means.labels_), np... | Test if resulting labels are in range [0, n_clusters - 1]. | test_n_clusters | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_bisect_k_means.py | BSD-3-Clause |
def test_fit_predict(csr_container):
"""Check if labels from fit(X) method are same as from fit(X).predict(X)."""
rng = np.random.RandomState(0)
X = rng.rand(10, 2)
if csr_container is not None:
X[X < 0.8] = 0
X = csr_container(X)
bisect_means = BisectingKMeans(n_clusters=3, rando... | Check if labels from fit(X) method are same as from fit(X).predict(X). | test_fit_predict | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_bisect_k_means.py | BSD-3-Clause |
def test_dtype_preserved(csr_container, global_dtype):
"""Check that centers dtype is the same as input data dtype."""
rng = np.random.RandomState(0)
X = rng.rand(10, 2).astype(global_dtype, copy=False)
if csr_container is not None:
X[X < 0.8] = 0
X = csr_container(X)
km = Bisectin... | Check that centers dtype is the same as input data dtype. | test_dtype_preserved | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_bisect_k_means.py | BSD-3-Clause |
def test_float32_float64_equivalence(csr_container):
"""Check that the results are the same between float32 and float64."""
rng = np.random.RandomState(0)
X = rng.rand(10, 2)
if csr_container is not None:
X[X < 0.8] = 0
X = csr_container(X)
km64 = BisectingKMeans(n_clusters=3, rand... | Check that the results are the same between float32 and float64. | test_float32_float64_equivalence | python | scikit-learn/scikit-learn | sklearn/cluster/tests/test_bisect_k_means.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_bisect_k_means.py | BSD-3-Clause |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.