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 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_dbscan_clustering_outlier_data(cut_distance):
"""
Tests if np.inf and np.nan data are each treated as special outliers.
"""
missing_label = _OUTLIER_ENCODING["missing"]["label"]
infinite_label = _OUTLIER_ENCODING["infinite"]["label"]
X_outlier = X.copy()
X_outlier[0] = [np.inf, 1]
... |
Tests if np.inf and np.nan data are each treated as special outliers.
| test_dbscan_clustering_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_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 _add_prefix_for_feature_names_out(self, transformer_with_feature_names_out):
"""Add prefix for feature names out that includes the transformer names.
Parameters
----------
transformer_with_feature_names_out : list of tuples of (str, array-like of str)
The tuple consisten... | Add prefix for feature names out that includes the transformer names.
Parameters
----------
transformer_with_feature_names_out : list of tuples of (str, array-like of str)
The tuple consistent of the transformer's name and its feature names out.
Returns
-------
... | _add_prefix_for_feature_names_out | python | scikit-learn/scikit-learn | sklearn/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 get_metadata_routing(self):
"""Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.4
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.met... | Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.4
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating... | get_metadata_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 |
def predict(self, X, **predict_params):
"""Predict using the base regressor, applying inverse.
The regressor is used to predict and the `inverse_func` or
`inverse_transform` is applied before returning the prediction.
Parameters
----------
X : {array-like, sparse matrix... | Predict using the base regressor, applying inverse.
The regressor is used to predict and the `inverse_func` or
`inverse_transform` is applied before returning the prediction.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Samp... | predict | 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 n_features_in_(self):
"""Number of features seen during :term:`fit`."""
# For consistency with other estimators we raise a AttributeError so
# that hasattr() returns False the estimator isn't fitted.
try:
check_is_fitted(self)
except NotFittedError as nfe:
... | Number of features seen during :term:`fit`. | n_features_in_ | 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 get_metadata_routing(self):
"""Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.6
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.met... | Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.6
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating... | get_metadata_routing | 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 test_column_transformer_remainder_dtypes(cols1, cols2, expected_remainder_cols):
"""Check that the remainder columns format matches the format of the other
columns when they're all strings or masks.
"""
X = np.ones((1, 3))
if isinstance(cols1, list) and isinstance(cols1[0], str):
pd = p... | Check that the remainder columns format matches the format of the other
columns when they're all strings or masks.
| test_column_transformer_remainder_dtypes | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_force_int_remainder_cols_deprecation(force_int_remainder_cols):
"""Check that ColumnTransformer raises a FutureWarning when
force_int_remainder_cols is set.
"""
X = np.ones((1, 3))
ct = ColumnTransformer(
[("T1", Trans(), [0]), ("T2", Trans(), [1])],
remainder="passthrough",... | Check that ColumnTransformer raises a FutureWarning when
force_int_remainder_cols is set.
| test_force_int_remainder_cols_deprecation | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_feature_names_out_pandas(selector):
"""Checks name when selecting only the second column"""
pd = pytest.importorskip("pandas")
df = pd.DataFrame({"col1": ["a", "a", "b"], "col2": ["z", "z", "z"]})
ct = ColumnTransformer([("ohe", OneHotEncoder(), selector)])
ct.fit(df)
assert_array_equa... | Checks name when selecting only the second column | test_feature_names_out_pandas | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_feature_names_out_non_pandas(selector):
"""Checks name when selecting the second column with numpy array"""
X = [["a", "z"], ["a", "z"], ["b", "z"]]
ct = ColumnTransformer([("ohe", OneHotEncoder(), selector)])
ct.fit(X)
assert_array_equal(ct.get_feature_names_out(), ["ohe__x1_z"]) | Checks name when selecting the second column with numpy array | test_feature_names_out_non_pandas | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_column_transformer_reordered_column_names_remainder(
explicit_colname, remainder
):
"""Test the interaction between remainder and column transformer"""
pd = pytest.importorskip("pandas")
X_fit_array = np.array([[0, 1, 2], [2, 4, 6]]).T
X_fit_df = pd.DataFrame(X_fit_array, columns=["first",... | Test the interaction between remainder and column transformer | test_column_transformer_reordered_column_names_remainder | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_feature_name_validation_missing_columns_drop_passthough():
"""Test the interaction between {'drop', 'passthrough'} and
missing column names."""
pd = pytest.importorskip("pandas")
X = np.ones(shape=(3, 4))
df = pd.DataFrame(X, columns=["a", "b", "c", "d"])
df_dropped = df.drop("c", axi... | Test the interaction between {'drop', 'passthrough'} and
missing column names. | test_feature_name_validation_missing_columns_drop_passthough | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_feature_names_in_():
"""Feature names are stored in column transformer.
Column transformer deliberately does not check for column name consistency.
It only checks that the non-dropped names seen in `fit` are seen
in `transform`. This behavior is already tested in
`test_feature_name_validat... | Feature names are stored in column transformer.
Column transformer deliberately does not check for column name consistency.
It only checks that the non-dropped names seen in `fit` are seen
in `transform`. This behavior is already tested in
`test_feature_name_validation_missing_columns_drop_passthough` | test_feature_names_in_ | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_column_transform_set_output_mixed(remainder, fit_transform):
"""Check ColumnTransformer outputs mixed types correctly."""
pd = pytest.importorskip("pandas")
df = pd.DataFrame(
{
"pet": pd.Series(["dog", "cat", "snake"], dtype="category"),
"color": pd.Series(["green",... | Check ColumnTransformer outputs mixed types correctly. | test_column_transform_set_output_mixed | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_transformers_with_pandas_out_but_not_feature_names_out(
trans_1, expected_verbose_names, expected_non_verbose_names
):
"""Check that set_config(transform="pandas") is compatible with more transformers.
Specifically, if transformers returns a DataFrame, but does not define
`get_feature_names_ou... | Check that set_config(transform="pandas") is compatible with more transformers.
Specifically, if transformers returns a DataFrame, but does not define
`get_feature_names_out`.
| test_transformers_with_pandas_out_but_not_feature_names_out | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_empty_selection_pandas_output(empty_selection):
"""Check that pandas output works when there is an empty selection.
Non-regression test for gh-25487
"""
pd = pytest.importorskip("pandas")
X = pd.DataFrame([[1.0, 2.2], [3.0, 1.0]], columns=["a", "b"])
ct = ColumnTransformer(
[
... | Check that pandas output works when there is an empty selection.
Non-regression test for gh-25487
| test_empty_selection_pandas_output | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_raise_error_if_index_not_aligned():
"""Check column transformer raises error if indices are not aligned.
Non-regression test for gh-26210.
"""
pd = pytest.importorskip("pandas")
X = pd.DataFrame([[1.0, 2.2], [3.0, 1.0]], columns=["a", "b"], index=[8, 3])
reset_index_transformer = Func... | Check column transformer raises error if indices are not aligned.
Non-regression test for gh-26210.
| test_raise_error_if_index_not_aligned | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_remainder_set_output():
"""Check that the output is set for the remainder.
Non-regression test for #26306.
"""
pd = pytest.importorskip("pandas")
df = pd.DataFrame({"a": [True, False, True], "b": [1, 2, 3]})
ct = make_column_transformer(
(VarianceThreshold(), make_column_sele... | Check that the output is set for the remainder.
Non-regression test for #26306.
| test_remainder_set_output | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_transform_pd_na():
"""Check behavior when a tranformer's output contains pandas.NA
It should raise an error unless the output config is set to 'pandas'.
"""
pd = pytest.importorskip("pandas")
if not hasattr(pd, "Float64Dtype"):
pytest.skip(
"The issue with pd.NA tested ... | Check behavior when a tranformer's output contains pandas.NA
It should raise an error unless the output config is set to 'pandas'.
| test_transform_pd_na | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_dataframe_different_dataframe_libraries():
"""Check fitting and transforming on pandas and polars dataframes."""
pd = pytest.importorskip("pandas")
pl = pytest.importorskip("polars")
X_train_np = np.array([[0, 1], [2, 4], [4, 5]])
X_test_np = np.array([[1, 2], [1, 3], [2, 3]])
# Fit on... | Check fitting and transforming on pandas and polars dataframes. | test_dataframe_different_dataframe_libraries | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_column_transformer_remainder_passthrough_naming_consistency(transform_output):
"""Check that when `remainder="passthrough"`, inconsistent naming is handled
correctly by the underlying `FunctionTransformer`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/28232
... | Check that when `remainder="passthrough"`, inconsistent naming is handled
correctly by the underlying `FunctionTransformer`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/28232
| test_column_transformer_remainder_passthrough_naming_consistency | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_column_transformer_column_renaming(dataframe_lib):
"""Check that we properly rename columns when using `ColumnTransformer` and
selected columns are redundant between transformers.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/28260
"""
lib = pytest.import... | Check that we properly rename columns when using `ColumnTransformer` and
selected columns are redundant between transformers.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/28260
| test_column_transformer_column_renaming | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_column_transformer_error_with_duplicated_columns(dataframe_lib):
"""Check that we raise an error when using `ColumnTransformer` and
the columns names are duplicated between transformers."""
lib = pytest.importorskip(dataframe_lib)
df = lib.DataFrame({"x1": [1, 2, 3], "x2": [10, 20, 30], "x3": ... | Check that we raise an error when using `ColumnTransformer` and
the columns names are duplicated between transformers. | test_column_transformer_error_with_duplicated_columns | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_column_transformer_auto_memmap():
"""Check that ColumnTransformer works in parallel with joblib's auto-memmapping.
non-regression test for issue #28781
"""
X = np.random.RandomState(0).uniform(size=(3, 4))
scaler = StandardScaler(copy=False)
transformer = ColumnTransformer(
t... | Check that ColumnTransformer works in parallel with joblib's auto-memmapping.
non-regression test for issue #28781
| test_column_transformer_auto_memmap | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_routing_passed_metadata_not_supported(method):
"""Test that the right error message is raised when metadata is passed while
not supported when `enable_metadata_routing=False`."""
X = np.array([[0, 1, 2], [2, 4, 6]]).T
y = [1, 2, 3]
trs = ColumnTransformer([("trans", Trans(), [0])]).fit(X, ... | Test that the right error message is raised when metadata is passed while
not supported when `enable_metadata_routing=False`. | test_routing_passed_metadata_not_supported | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.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.