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 _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
def test_dbscan_input_not_modified_precomputed_sparse_nodiag(csr_container): """Check that we don't modify in-place the pre-computed sparse matrix. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/27508 """ X = np.random.RandomState(0).rand(10, 10) # Add zeros on the...
Check that we don't modify in-place the pre-computed sparse matrix. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/27508
test_dbscan_input_not_modified_precomputed_sparse_nodiag
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_dbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_dbscan.py
BSD-3-Clause
def test_outlier_data(outlier_type): """ Tests if np.inf and np.nan data are each treated as special outliers. """ outlier = { "infinite": np.inf, "missing": np.nan, }[outlier_type] prob_check = { "infinite": lambda x, y: x == y, "missing": lambda x, y: np.isnan(x...
Tests if np.inf and np.nan data are each treated as special outliers.
test_outlier_data
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_distance_matrix(): """ Tests that HDBSCAN works with precomputed distance matrices, and throws the appropriate errors when needed. """ D = euclidean_distances(X) D_original = D.copy() labels = HDBSCAN(metric="precomputed", copy=True).fit_predict(D) assert_allclose(D, D_...
Tests that HDBSCAN works with precomputed distance matrices, and throws the appropriate errors when needed.
test_hdbscan_distance_matrix
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_sparse_distance_matrix(sparse_constructor): """ Tests that HDBSCAN works with sparse distance matrices. """ D = distance.squareform(distance.pdist(X)) D /= np.max(D) threshold = stats.scoreatpercentile(D.flatten(), 50) D[D >= threshold] = 0.0 D = sparse_constructor(D) ...
Tests that HDBSCAN works with sparse distance matrices.
test_hdbscan_sparse_distance_matrix
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_feature_array(): """ Tests that HDBSCAN works with feature array, including an arbitrary goodness of fit check. Note that the check is a simple heuristic. """ labels = HDBSCAN().fit_predict(X) # Check that clustering is arbitrarily good # This is a heuristic to guard agains...
Tests that HDBSCAN works with feature array, including an arbitrary goodness of fit check. Note that the check is a simple heuristic.
test_hdbscan_feature_array
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_algorithms(algo, metric): """ Tests that HDBSCAN works with the expected combinations of algorithms and metrics, or raises the expected errors. """ labels = HDBSCAN(algorithm=algo).fit_predict(X) check_label_quality(labels) # Validation for brute is handled by `pairwise_dis...
Tests that HDBSCAN works with the expected combinations of algorithms and metrics, or raises the expected errors.
test_hdbscan_algorithms
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_dbscan_clustering(): """ Tests that HDBSCAN can generate a sufficiently accurate dbscan clustering. This test is more of a sanity check than a rigorous evaluation. """ clusterer = HDBSCAN().fit(X) labels = clusterer.dbscan_clustering(0.3) # We use a looser threshold due to dbscan p...
Tests that HDBSCAN can generate a sufficiently accurate dbscan clustering. This test is more of a sanity check than a rigorous evaluation.
test_dbscan_clustering
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_best_balltree_metric(): """ Tests that HDBSCAN using `BallTree` works. """ labels = HDBSCAN( metric="seuclidean", metric_params={"V": np.ones(X.shape[1])} ).fit_predict(X) check_label_quality(labels)
Tests that HDBSCAN using `BallTree` works.
test_hdbscan_best_balltree_metric
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_min_cluster_size(): """ Test that the smallest non-noise cluster has at least `min_cluster_size` many points """ for min_cluster_size in range(2, len(X), 1): labels = HDBSCAN(min_cluster_size=min_cluster_size).fit_predict(X) true_labels = [label for label in labels i...
Test that the smallest non-noise cluster has at least `min_cluster_size` many points
test_hdbscan_min_cluster_size
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_callable_metric(): """ Tests that HDBSCAN works when passed a callable metric. """ metric = distance.euclidean labels = HDBSCAN(metric=metric).fit_predict(X) check_label_quality(labels)
Tests that HDBSCAN works when passed a callable metric.
test_hdbscan_callable_metric
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_precomputed_non_brute(tree): """ Tests that HDBSCAN correctly raises an error when passing precomputed data while requesting a tree-based algorithm. """ hdb = HDBSCAN(metric="precomputed", algorithm=tree) msg = "precomputed is not a valid metric for" with pytest.raises(Value...
Tests that HDBSCAN correctly raises an error when passing precomputed data while requesting a tree-based algorithm.
test_hdbscan_precomputed_non_brute
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_sparse(csr_container): """ Tests that HDBSCAN works correctly when passing sparse feature data. Evaluates correctness by comparing against the same data passed as a dense array. """ dense_labels = HDBSCAN().fit(X).labels_ check_label_quality(dense_labels) _X_sparse = c...
Tests that HDBSCAN works correctly when passing sparse feature data. Evaluates correctness by comparing against the same data passed as a dense array.
test_hdbscan_sparse
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_centers(algorithm): """ Tests that HDBSCAN centers are calculated and stored properly, and are accurate to the data. """ centers = [(0.0, 0.0), (3.0, 3.0)] H, _ = make_blobs(n_samples=2000, random_state=0, centers=centers, cluster_std=0.5) hdb = HDBSCAN(store_centers="both")...
Tests that HDBSCAN centers are calculated and stored properly, and are accurate to the data.
test_hdbscan_centers
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_allow_single_cluster_with_epsilon(): """ Tests that HDBSCAN single-cluster selection with epsilon works correctly. """ rng = np.random.RandomState(0) no_structure = rng.rand(150, 2) # without epsilon we should see many noise points as children of root. labels = HDBSCAN( ...
Tests that HDBSCAN single-cluster selection with epsilon works correctly.
test_hdbscan_allow_single_cluster_with_epsilon
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_better_than_dbscan(): """ Validate that HDBSCAN can properly cluster this difficult synthetic dataset. Note that DBSCAN fails on this (see HDBSCAN plotting example) """ centers = [[-0.85, -0.85], [-0.85, 0.85], [3, 3], [3, -3]] X, y = make_blobs( n_samples=750, ...
Validate that HDBSCAN can properly cluster this difficult synthetic dataset. Note that DBSCAN fails on this (see HDBSCAN plotting example)
test_hdbscan_better_than_dbscan
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_sparse_distances_too_few_nonzero(csr_container): """ Tests that HDBSCAN raises the correct error when there are too few non-zero distances. """ X = csr_container(np.zeros((10, 10))) msg = "There exists points with fewer than" with pytest.raises(ValueError, match=msg): ...
Tests that HDBSCAN raises the correct error when there are too few non-zero distances.
test_hdbscan_sparse_distances_too_few_nonzero
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_sparse_distances_disconnected_graph(csr_container): """ Tests that HDBSCAN raises the correct error when the distance matrix has multiple connected components. """ # Create symmetric sparse matrix with 2 connected components X = np.zeros((20, 20)) X[:5, :5] = 1 X[5:, 15:...
Tests that HDBSCAN raises the correct error when the distance matrix has multiple connected components.
test_hdbscan_sparse_distances_disconnected_graph
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_tree_invalid_metric(): """ Tests that HDBSCAN correctly raises an error for invalid metric choices. """ metric_callable = lambda x: x msg = ( ".* is not a valid metric for a .*-based algorithm\\. Please select a different" " metric\\." ) # Callables are not ...
Tests that HDBSCAN correctly raises an error for invalid metric choices.
test_hdbscan_tree_invalid_metric
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_too_many_min_samples(): """ Tests that HDBSCAN correctly raises an error when setting `min_samples` larger than the number of samples. """ hdb = HDBSCAN(min_samples=len(X) + 1) msg = r"min_samples (.*) must be at most" with pytest.raises(ValueError, match=msg): hdb.f...
Tests that HDBSCAN correctly raises an error when setting `min_samples` larger than the number of samples.
test_hdbscan_too_many_min_samples
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_precomputed_dense_nan(): """ Tests that HDBSCAN correctly raises an error when providing precomputed distances with `np.nan` values. """ X_nan = X.copy() X_nan[0, 0] = np.nan msg = "np.nan values found in precomputed-dense" hdb = HDBSCAN(metric="precomputed") with py...
Tests that HDBSCAN correctly raises an error when providing precomputed distances with `np.nan` values.
test_hdbscan_precomputed_dense_nan
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_labelling_distinct(global_random_seed, allow_single_cluster, epsilon): """ Tests that the `_do_labelling` helper function correctly assigns labels. """ n_samples = 48 X, y = make_blobs( n_samples, random_state=global_random_seed, # Ensure the clusters are distinct wi...
Tests that the `_do_labelling` helper function correctly assigns labels.
test_labelling_distinct
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_labelling_thresholding(): """ Tests that the `_do_labelling` helper function correctly thresholds the incoming lambda values given various `cluster_selection_epsilon` values. """ n_samples = 5 MAX_LAMBDA = 1.5 condensed_tree = np.array( [ (5, 2, MAX_LAMBDA, 1), ...
Tests that the `_do_labelling` helper function correctly thresholds the incoming lambda values given various `cluster_selection_epsilon` values.
test_labelling_thresholding
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_error_precomputed_and_store_centers(store_centers): """Check that we raise an error if the centers are requested together with a precomputed input matrix. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/27893 """ rng = np.random.RandomState(0) X...
Check that we raise an error if the centers are requested together with a precomputed input matrix. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/27893
test_hdbscan_error_precomputed_and_store_centers
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_hdbscan_cosine_metric_invalid_algorithm(invalid_algo): """Test that HDBSCAN raises an informative error is raised when an unsupported algorithm is used with the "cosine" metric. """ hdbscan = HDBSCAN(metric="cosine", algorithm=invalid_algo) with pytest.raises(ValueError, match="cosine is no...
Test that HDBSCAN raises an informative error is raised when an unsupported algorithm is used with the "cosine" metric.
test_hdbscan_cosine_metric_invalid_algorithm
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hdbscan.py
BSD-3-Clause
def test_agglomerative_clustering_memory_mapped(): """AgglomerativeClustering must work on mem-mapped dataset. Non-regression test for issue #19875. """ rng = np.random.RandomState(0) Xmm = create_memmap_backed_data(rng.randn(50, 100)) AgglomerativeClustering(metric="euclidean", linkage="single...
AgglomerativeClustering must work on mem-mapped dataset. Non-regression test for issue #19875.
test_agglomerative_clustering_memory_mapped
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hierarchical.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hierarchical.py
BSD-3-Clause
def test_mst_linkage_core_memory_mapped(metric_param_grid): """The MST-LINKAGE-CORE algorithm must work on mem-mapped dataset. Non-regression test for issue #19875. """ rng = np.random.RandomState(seed=1) X = rng.normal(size=(20, 4)) Xmm = create_memmap_backed_data(X) metric, param_grid = m...
The MST-LINKAGE-CORE algorithm must work on mem-mapped dataset. Non-regression test for issue #19875.
test_mst_linkage_core_memory_mapped
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hierarchical.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hierarchical.py
BSD-3-Clause
def test_precomputed_connectivity_metric_with_2_connected_components(): """Check that connecting components works when connectivity and affinity are both precomputed and the number of connected components is greater than 1. Non-regression test for #16151. """ connectivity_matrix = np.array( ...
Check that connecting components works when connectivity and affinity are both precomputed and the number of connected components is greater than 1. Non-regression test for #16151.
test_precomputed_connectivity_metric_with_2_connected_components
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_hierarchical.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_hierarchical.py
BSD-3-Clause
def test_kmeans_init_auto_with_initial_centroids(Estimator, init, expected_n_init): """Check that `n_init="auto"` chooses the right number of initializations. Non-regression test for #26657: https://github.com/scikit-learn/scikit-learn/pull/26657 """ n_sample, n_features, n_clusters = 100, 10, 5 ...
Check that `n_init="auto"` chooses the right number of initializations. Non-regression test for #26657: https://github.com/scikit-learn/scikit-learn/pull/26657
test_kmeans_init_auto_with_initial_centroids
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_k_means.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_k_means.py
BSD-3-Clause
def test_kmeans_with_array_like_or_np_scalar_init(kwargs): """Check that init works with numpy scalar strings. Non-regression test for #21964. """ X = np.asarray([[0, 0], [0.5, 0], [0.5, 1], [1, 1]], dtype=np.float64) clustering = KMeans(n_clusters=2, **kwargs) # Does not raise clustering....
Check that init works with numpy scalar strings. Non-regression test for #21964.
test_kmeans_with_array_like_or_np_scalar_init
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_k_means.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_k_means.py
BSD-3-Clause
def test_predict_does_not_change_cluster_centers(csr_container): """Check that predict does not change cluster centers. Non-regression test for gh-24253. """ X, _ = make_blobs(n_samples=200, n_features=10, centers=10, random_state=0) if csr_container is not None: X = csr_container(X) k...
Check that predict does not change cluster centers. Non-regression test for gh-24253.
test_predict_does_not_change_cluster_centers
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_k_means.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_k_means.py
BSD-3-Clause
def test_sample_weight_init(init, global_random_seed): """Check that sample weight is used during init. `_init_centroids` is shared across all classes inheriting from _BaseKMeans so it's enough to check for KMeans. """ rng = np.random.RandomState(global_random_seed) X, _ = make_blobs( n...
Check that sample weight is used during init. `_init_centroids` is shared across all classes inheriting from _BaseKMeans so it's enough to check for KMeans.
test_sample_weight_init
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_k_means.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_k_means.py
BSD-3-Clause
def test_sample_weight_zero(init, global_random_seed): """Check that if sample weight is 0, this sample won't be chosen. `_init_centroids` is shared across all classes inheriting from _BaseKMeans so it's enough to check for KMeans. """ rng = np.random.RandomState(global_random_seed) X, _ = make...
Check that if sample weight is 0, this sample won't be chosen. `_init_centroids` is shared across all classes inheriting from _BaseKMeans so it's enough to check for KMeans.
test_sample_weight_zero
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_k_means.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_k_means.py
BSD-3-Clause
def test_relocating_with_duplicates(algorithm, array_constr): """Check that kmeans stops when there are more centers than non-duplicate samples Non-regression test for issue: https://github.com/scikit-learn/scikit-learn/issues/28055 """ X = np.array([[0, 0], [1, 1], [1, 1], [1, 0], [0, 1]]) km ...
Check that kmeans stops when there are more centers than non-duplicate samples Non-regression test for issue: https://github.com/scikit-learn/scikit-learn/issues/28055
test_relocating_with_duplicates
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_k_means.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_k_means.py
BSD-3-Clause
def test_optics_input_not_modified_precomputed_sparse_nodiag( csr_container, global_random_seed ): """Check that we don't modify in-place the pre-computed sparse matrix. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/27508 """ X = np.random.RandomState(global_random...
Check that we don't modify in-place the pre-computed sparse matrix. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/27508
test_optics_input_not_modified_precomputed_sparse_nodiag
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_optics.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_optics.py
BSD-3-Clause
def test_optics_predecessor_correction_ordering(): """Check that cluster correction using predecessor is working as expected. In the following example, the predecessor correction was not working properly since it was not using the right indices. This non-regression test check that reordering the data ...
Check that cluster correction using predecessor is working as expected. In the following example, the predecessor correction was not working properly since it was not using the right indices. This non-regression test check that reordering the data does not change the results. Non-regression test for:...
test_optics_predecessor_correction_ordering
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_optics.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_optics.py
BSD-3-Clause
def test_spectral_clustering_np_matrix_raises(): """Check that spectral_clustering raises an informative error when passed a np.matrix. See #10993""" X = np.matrix([[0.0, 2.0], [2.0, 0.0]]) msg = r"np\.matrix is not supported. Please convert to a numpy array" with pytest.raises(TypeError, match=msg...
Check that spectral_clustering raises an informative error when passed a np.matrix. See #10993
test_spectral_clustering_np_matrix_raises
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_spectral.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_spectral.py
BSD-3-Clause
def test_spectral_clustering_not_infinite_loop(capsys, monkeypatch): """Check that discretize raises LinAlgError when svd never converges. Non-regression test for #21380 """ def new_svd(*args, **kwargs): raise LinAlgError() monkeypatch.setattr(np.linalg, "svd", new_svd) vectors = np.o...
Check that discretize raises LinAlgError when svd never converges. Non-regression test for #21380
test_spectral_clustering_not_infinite_loop
python
scikit-learn/scikit-learn
sklearn/cluster/tests/test_spectral.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/tests/test_spectral.py
BSD-3-Clause
def _brute_mst(mutual_reachability, min_samples): """ Builds a minimum spanning tree (MST) from the provided mutual-reachability values. This function dispatches to a custom Cython implementation for dense arrays, and `scipy.sparse.csgraph.minimum_spanning_tree` for sparse arrays/matrices. Para...
Builds a minimum spanning tree (MST) from the provided mutual-reachability values. This function dispatches to a custom Cython implementation for dense arrays, and `scipy.sparse.csgraph.minimum_spanning_tree` for sparse arrays/matrices. Parameters ---------- mututal_reachability_graph: {nd...
_brute_mst
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/hdbscan.py
BSD-3-Clause
def _process_mst(min_spanning_tree): """ Builds a single-linkage tree (SLT) from the provided minimum spanning tree (MST). The MST is first sorted then processed by a custom Cython routine. Parameters ---------- min_spanning_tree : ndarray of shape (n_samples - 1,), dtype=MST_edge_dtype ...
Builds a single-linkage tree (SLT) from the provided minimum spanning tree (MST). The MST is first sorted then processed by a custom Cython routine. Parameters ---------- min_spanning_tree : ndarray of shape (n_samples - 1,), dtype=MST_edge_dtype The MST representation of the mutual-reacha...
_process_mst
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/hdbscan.py
BSD-3-Clause
def _hdbscan_brute( X, min_samples=5, alpha=None, metric="euclidean", n_jobs=None, copy=False, **metric_params, ): """ Builds a single-linkage tree (SLT) from the input data `X`. If `metric="precomputed"` then `X` must be a symmetric array of distances. Otherwise, the pairwis...
Builds a single-linkage tree (SLT) from the input data `X`. If `metric="precomputed"` then `X` must be a symmetric array of distances. Otherwise, the pairwise distances are calculated directly and passed to `mutual_reachability_graph`. Parameters ---------- X : ndarray of shape (n_samples,...
_hdbscan_brute
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/hdbscan.py
BSD-3-Clause
def _hdbscan_prims( X, algo, min_samples=5, alpha=1.0, metric="euclidean", leaf_size=40, n_jobs=None, **metric_params, ): """ Builds a single-linkage tree (SLT) from the input data `X`. If `metric="precomputed"` then `X` must be a symmetric array of distances. Otherwise, ...
Builds a single-linkage tree (SLT) from the input data `X`. If `metric="precomputed"` then `X` must be a symmetric array of distances. Otherwise, the pairwise distances are calculated directly and passed to `mutual_reachability_graph`. Parameters ---------- X : ndarray of shape (n_samples,...
_hdbscan_prims
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/hdbscan.py
BSD-3-Clause
def remap_single_linkage_tree(tree, internal_to_raw, non_finite): """ Takes an internal single_linkage_tree structure and adds back in a set of points that were initially detected as non-finite and returns that new tree. These points will all be merged into the final node at np.inf distance and cons...
Takes an internal single_linkage_tree structure and adds back in a set of points that were initially detected as non-finite and returns that new tree. These points will all be merged into the final node at np.inf distance and considered noise points. Parameters ---------- tree : ndarray of...
remap_single_linkage_tree
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/hdbscan.py
BSD-3-Clause
def _get_finite_row_indices(matrix): """ Returns the indices of the purely finite rows of a sparse matrix or dense ndarray """ if issparse(matrix): row_indices = np.array( [i for i, row in enumerate(matrix.tolil().data) if np.all(np.isfinite(row))] ) else: (ro...
Returns the indices of the purely finite rows of a sparse matrix or dense ndarray
_get_finite_row_indices
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/hdbscan.py
BSD-3-Clause
def fit(self, X, y=None): """Find clusters based on hierarchical density-based clustering. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ ndarray of shape (n_samples, n_samples) A feature array, or array of distan...
Find clusters based on hierarchical density-based clustering. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features), or ndarray of shape (n_samples, n_samples) A feature array, or array of distances between samples if `met...
fit
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/hdbscan.py
BSD-3-Clause
def _weighted_cluster_center(self, X): """Calculate and store the centroids/medoids of each cluster. This requires `X` to be a raw feature array, not precomputed distances. Rather than return outputs directly, this helper method instead stores them in the `self.{centroids, medoids}_` at...
Calculate and store the centroids/medoids of each cluster. This requires `X` to be a raw feature array, not precomputed distances. Rather than return outputs directly, this helper method instead stores them in the `self.{centroids, medoids}_` attributes. The choice for which attributes ...
_weighted_cluster_center
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/hdbscan.py
BSD-3-Clause
def dbscan_clustering(self, cut_distance, min_cluster_size=5): """Return clustering given by DBSCAN without border points. Return clustering that would be equivalent to running DBSCAN* for a particular cut_distance (or epsilon) DBSCAN* can be thought of as DBSCAN without the border poin...
Return clustering given by DBSCAN without border points. Return clustering that would be equivalent to running DBSCAN* for a particular cut_distance (or epsilon) DBSCAN* can be thought of as DBSCAN without the border points. As such these results may differ slightly from `cluster.DBSCA...
dbscan_clustering
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/hdbscan.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/hdbscan.py
BSD-3-Clause
def test_mutual_reachability_graph_error_sparse_format(): """Check that we raise an error if the sparse format is not CSR.""" rng = np.random.RandomState(0) X = rng.randn(10, 10) X = X.T @ X np.fill_diagonal(X, 0.0) X = _convert_container(X, "sparse_csc") err_msg = "Only sparse CSR matrices...
Check that we raise an error if the sparse format is not CSR.
test_mutual_reachability_graph_error_sparse_format
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/tests/test_reachibility.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/tests/test_reachibility.py
BSD-3-Clause
def test_mutual_reachability_graph_inplace(array_type): """Check that the operation is happening inplace.""" rng = np.random.RandomState(0) X = rng.randn(10, 10) X = X.T @ X np.fill_diagonal(X, 0.0) X = _convert_container(X, array_type) mr_graph = mutual_reachability_graph(X) assert id...
Check that the operation is happening inplace.
test_mutual_reachability_graph_inplace
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/tests/test_reachibility.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/tests/test_reachibility.py
BSD-3-Clause
def test_mutual_reachability_graph_equivalence_dense_sparse(): """Check that we get the same results for dense and sparse implementation.""" rng = np.random.RandomState(0) X = rng.randn(5, 5) X_dense = X.T @ X X_sparse = _convert_container(X_dense, "sparse_csr") mr_graph_dense = mutual_reachabi...
Check that we get the same results for dense and sparse implementation.
test_mutual_reachability_graph_equivalence_dense_sparse
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/tests/test_reachibility.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/tests/test_reachibility.py
BSD-3-Clause
def test_mutual_reachability_graph_preserves_dtype(array_type, dtype): """Check that the computation preserve dtype thanks to fused types.""" rng = np.random.RandomState(0) X = rng.randn(10, 10) X = (X.T @ X).astype(dtype) np.fill_diagonal(X, 0.0) X = _convert_container(X, array_type) asser...
Check that the computation preserve dtype thanks to fused types.
test_mutual_reachability_graph_preserves_dtype
python
scikit-learn/scikit-learn
sklearn/cluster/_hdbscan/tests/test_reachibility.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/_hdbscan/tests/test_reachibility.py
BSD-3-Clause
def _transformers(self): """ Internal list of transformer only containing the name and transformers, dropping the columns. DO NOT USE: This is for the implementation of get_params via BaseComposition._get_params which expects lists of tuples of len 2. To iterate through...
Internal list of transformer only containing the name and transformers, dropping the columns. DO NOT USE: This is for the implementation of get_params via BaseComposition._get_params which expects lists of tuples of len 2. To iterate through the transformers, use ``self._iter`...
_transformers
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _transformers(self, value): """DO NOT USE: This is for the implementation of set_params via BaseComposition._get_params which gives lists of tuples of len 2. """ try: self.transformers = [ (name, trans, col) for ((name, trans), (_, _, col))...
DO NOT USE: This is for the implementation of set_params via BaseComposition._get_params which gives lists of tuples of len 2.
_transformers
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def set_output(self, *, transform=None): """Set the output container when `"transform"` and `"fit_transform"` are called. Calling `set_output` will set the output of all estimators in `transformers` and `transformers_`. Parameters ---------- transform : {"default", "pan...
Set the output container when `"transform"` and `"fit_transform"` are called. Calling `set_output` will set the output of all estimators in `transformers` and `transformers_`. Parameters ---------- transform : {"default", "pandas", "polars"}, default=None Configure ...
set_output
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _iter(self, fitted, column_as_labels, skip_drop, skip_empty_columns): """ Generate (name, trans, columns, weight) tuples. Parameters ---------- fitted : bool If True, use the fitted transformers (``self.transformers_``) to iterate through transformer...
Generate (name, trans, columns, weight) tuples. Parameters ---------- fitted : bool If True, use the fitted transformers (``self.transformers_``) to iterate through transformers, else use the transformers passed by the user (``self.transformers``). ...
_iter
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _validate_transformers(self): """Validate names of transformers and the transformers themselves. This checks whether given transformers have the required methods, i.e. `fit` or `fit_transform` and `transform` implemented. """ if not self.transformers: return ...
Validate names of transformers and the transformers themselves. This checks whether given transformers have the required methods, i.e. `fit` or `fit_transform` and `transform` implemented.
_validate_transformers
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _validate_column_callables(self, X): """ Converts callable column specifications. This stores a dictionary of the form `{step_name: column_indices}` and calls the `columns` on `X` if `columns` is a callable for a given transformer. The results are then stored in `se...
Converts callable column specifications. This stores a dictionary of the form `{step_name: column_indices}` and calls the `columns` on `X` if `columns` is a callable for a given transformer. The results are then stored in `self._transformer_to_input_indices`.
_validate_column_callables
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _validate_remainder(self, X): """ Validates ``remainder`` and defines ``_remainder`` targeting the remaining columns. """ cols = set(chain(*self._transformer_to_input_indices.values())) remaining = sorted(set(range(self.n_features_in_)) - cols) self._transform...
Validates ``remainder`` and defines ``_remainder`` targeting the remaining columns.
_validate_remainder
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def named_transformers_(self): """Access the fitted transformer by name. Read-only attribute to access any transformer by given name. Keys are transformer names and values are the fitted transformer objects. """ # Use Bunch object to improve autocomplete return B...
Access the fitted transformer by name. Read-only attribute to access any transformer by given name. Keys are transformer names and values are the fitted transformer objects.
named_transformers_
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _get_feature_name_out_for_transformer(self, name, trans, feature_names_in): """Gets feature names of transformer. Used in conjunction with self._iter(fitted=True) in get_feature_names_out. """ column_indices = self._transformer_to_input_indices[name] names = feature_names_in...
Gets feature names of transformer. Used in conjunction with self._iter(fitted=True) in get_feature_names_out.
_get_feature_name_out_for_transformer
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.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. - If `input_features` is `None`, then `feature_names_in_` is ...
Get output feature names for transformation. Parameters ---------- input_features : array-like of str or None, default=None Input features. - If `input_features` is `None`, then `feature_names_in_` is used as feature names in. If `feature_names_in_` is not...
get_feature_names_out
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _update_fitted_transformers(self, transformers): """Set self.transformers_ from given transformers. Parameters ---------- transformers : list of estimators The fitted estimators as the output of `self._call_func_on_transformers(func=_fit_transform_one, ...)`....
Set self.transformers_ from given transformers. Parameters ---------- transformers : list of estimators The fitted estimators as the output of `self._call_func_on_transformers(func=_fit_transform_one, ...)`. That function doesn't include 'drop' or transformer...
_update_fitted_transformers
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _validate_output(self, result): """ Ensure that the output of each transformer is 2D. Otherwise hstack can raise an error or produce incorrect results. """ names = [ name for name, _, _, _ in self._iter( fitted=True, col...
Ensure that the output of each transformer is 2D. Otherwise hstack can raise an error or produce incorrect results.
_validate_output
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _record_output_indices(self, Xs): """ Record which transformer produced which column. """ idx = 0 self.output_indices_ = {} for transformer_idx, (name, _, _, _) in enumerate( self._iter( fitted=True, column_as_labels=False,...
Record which transformer produced which column.
_record_output_indices
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _call_func_on_transformers(self, X, y, func, column_as_labels, routed_params): """ Private function to fit and/or transform on demand. Parameters ---------- X : {array-like, dataframe} of shape (n_samples, n_features) The data to be used in fit and/or transform. ...
Private function to fit and/or transform on demand. Parameters ---------- X : {array-like, dataframe} of shape (n_samples, n_features) The data to be used in fit and/or transform. y : array-like of shape (n_samples,) Targets. func : callable ...
_call_func_on_transformers
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def fit(self, X, y=None, **params): """Fit all transformers using X. Parameters ---------- X : {array-like, dataframe} of shape (n_samples, n_features) Input data, of which specified subsets are used to fit the transformers. y : array-like of shape (n_sa...
Fit all transformers using X. Parameters ---------- X : {array-like, dataframe} of shape (n_samples, n_features) Input data, of which specified subsets are used to fit the transformers. y : array-like of shape (n_samples,...), default=None Targets fo...
fit
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def fit_transform(self, X, y=None, **params): """Fit all transformers, transform the data and concatenate results. Parameters ---------- X : {array-like, dataframe} of shape (n_samples, n_features) Input data, of which specified subsets are used to fit the transf...
Fit all transformers, transform the data and concatenate results. Parameters ---------- X : {array-like, dataframe} of shape (n_samples, n_features) Input data, of which specified subsets are used to fit the transformers. y : array-like of shape (n_samples,), de...
fit_transform
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def transform(self, X, **params): """Transform X separately by each transformer, concatenate results. Parameters ---------- X : {array-like, dataframe} of shape (n_samples, n_features) The data to be transformed by subset. **params : dict, default=None P...
Transform X separately by each transformer, concatenate results. Parameters ---------- X : {array-like, dataframe} of shape (n_samples, n_features) The data to be transformed by subset. **params : dict, default=None Parameters to be passed to the underlying tran...
transform
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _hstack(self, Xs, *, n_samples): """Stacks Xs horizontally. This allows subclasses to control the stacking behavior, while reusing everything else from ColumnTransformer. Parameters ---------- Xs : list of {array-like, sparse matrix, dataframe} The conta...
Stacks Xs horizontally. This allows subclasses to control the stacking behavior, while reusing everything else from ColumnTransformer. Parameters ---------- Xs : list of {array-like, sparse matrix, dataframe} The container to concatenate. n_samples : int ...
_hstack
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _get_empty_routing(self): """Return empty routing. Used while routing can be disabled. TODO: Remove when ``set_config(enable_metadata_routing=False)`` is no more an option. """ return Bunch( **{ name: Bunch(**{method: {} for method in MET...
Return empty routing. Used while routing can be disabled. TODO: Remove when ``set_config(enable_metadata_routing=False)`` is no more an option.
_get_empty_routing
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _check_X(X): """Use check_array only when necessary, e.g. on lists and other non-array-likes.""" if ( (hasattr(X, "__array__") and hasattr(X, "shape")) or hasattr(X, "__dataframe__") or sparse.issparse(X) ): return X return check_array(X, ensure_all_finite="allow-nan"...
Use check_array only when necessary, e.g. on lists and other non-array-likes.
_check_X
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _is_empty_column_selection(column): """ Return True if the column selection is empty (empty list or all-False boolean array). """ if hasattr(column, "dtype") and np.issubdtype(column.dtype, np.bool_): return not column.any() elif hasattr(column, "__len__"): return len(column...
Return True if the column selection is empty (empty list or all-False boolean array).
_is_empty_column_selection
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _get_transformer_list(estimators): """ Construct (name, trans, column) tuples from list """ transformers, columns = zip(*estimators) names, _ = zip(*_name_estimators(transformers)) transformer_list = list(zip(names, transformers, columns)) return transformer_list
Construct (name, trans, column) tuples from list
_get_transformer_list
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def __call__(self, df): """Callable for column selection to be used by a :class:`ColumnTransformer`. Parameters ---------- df : dataframe of shape (n_features, n_samples) DataFrame to select columns from. """ if not hasattr(df, "iloc"): ra...
Callable for column selection to be used by a :class:`ColumnTransformer`. Parameters ---------- df : dataframe of shape (n_features, n_samples) DataFrame to select columns from.
__call__
python
scikit-learn/scikit-learn
sklearn/compose/_column_transformer.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_column_transformer.py
BSD-3-Clause
def _fit_transformer(self, y): """Check transformer and fit transformer. Create the default transformer, fit it and make additional inverse check on a subset (optional). """ if self.transformer is not None and ( self.func is not None or self.inverse_func is not None...
Check transformer and fit transformer. Create the default transformer, fit it and make additional inverse check on a subset (optional).
_fit_transformer
python
scikit-learn/scikit-learn
sklearn/compose/_target.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_target.py
BSD-3-Clause
def fit(self, X, y, **fit_params): """Fit the model according to the given training data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the nu...
Fit the model according to the given training data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of s...
fit
python
scikit-learn/scikit-learn
sklearn/compose/_target.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_target.py
BSD-3-Clause