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_classification_report_labels_subset_superset(labels, show_micro_avg): """Check the behaviour of passing `labels` as a superset or subset of the labels. WHen a superset, we expect to show the "accuracy" in the report while it should be the micro-averaging if this is a subset. Non-regression tes...
Check the behaviour of passing `labels` as a superset or subset of the labels. WHen a superset, we expect to show the "accuracy" in the report while it should be the micro-averaging if this is a subset. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/27927
test_classification_report_labels_subset_superset
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_confusion_matrix_single_label(): """Test `confusion_matrix` warns when only one label found.""" y_test = [0, 0, 0, 0] y_pred = [0, 0, 0, 0] with pytest.warns(UserWarning, match="A single label was found in"): confusion_matrix(y_pred, y_test)
Test `confusion_matrix` warns when only one label found.
test_confusion_matrix_single_label
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_likelihood_ratios_raise_warning_deprecation(raise_warning): """Test that class_likelihood_ratios raises a `FutureWarning` when `raise_warning` param is set.""" y_true = np.array([1, 0]) y_pred = np.array([1, 0]) msg = "`raise_warning` was deprecated in version 1.7 and will be removed in 1....
Test that class_likelihood_ratios raises a `FutureWarning` when `raise_warning` param is set.
test_likelihood_ratios_raise_warning_deprecation
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_likelihood_ratios_replace_undefined_by_worst(): """Test that class_likelihood_ratios returns the worst scores `1.0` for both LR+ and LR- when `replace_undefined_by=1` is set.""" # This data causes fp=0 (0 false positives) in the confusion_matrix and a division # by zero that affects the positiv...
Test that class_likelihood_ratios returns the worst scores `1.0` for both LR+ and LR- when `replace_undefined_by=1` is set.
test_likelihood_ratios_replace_undefined_by_worst
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_likelihood_ratios_wrong_dict_replace_undefined_by(replace_undefined_by): """Test that class_likelihood_ratios raises a `ValueError` if the input dict for `replace_undefined_by` is in the wrong format or contains impossible values.""" y_true = np.array([1, 0]) y_pred = np.array([1, 0]) msg ...
Test that class_likelihood_ratios raises a `ValueError` if the input dict for `replace_undefined_by` is in the wrong format or contains impossible values.
test_likelihood_ratios_wrong_dict_replace_undefined_by
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_likelihood_ratios_replace_undefined_by_0_fp(replace_undefined_by, expected): """Test that the `replace_undefined_by` param returns the right value for the positive_likelihood_ratio as defined by the user.""" # This data causes fp=0 (0 false positives) in the confusion_matrix and a division # by...
Test that the `replace_undefined_by` param returns the right value for the positive_likelihood_ratio as defined by the user.
test_likelihood_ratios_replace_undefined_by_0_fp
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_likelihood_ratios_replace_undefined_by_0_tn(replace_undefined_by, expected): """Test that the `replace_undefined_by` param returns the right value for the negative_likelihood_ratio as defined by the user.""" # This data causes tn=0 (0 true negatives) in the confusion_matrix and a division # by ...
Test that the `replace_undefined_by` param returns the right value for the negative_likelihood_ratio as defined by the user.
test_likelihood_ratios_replace_undefined_by_0_tn
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_cohen_kappa_score_error_wrong_label(): """Test that correct error is raised when users pass labels that are not in y1.""" labels = [1, 2] y1 = np.array(["a"] * 5 + ["b"] * 5) y2 = np.array(["b"] * 10) with pytest.raises( ValueError, match="At least one label in `labels` must be pres...
Test that correct error is raised when users pass labels that are not in y1.
test_cohen_kappa_score_error_wrong_label
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_zero_division_nan_no_warning(metric, y_true, y_pred, zero_division): """Check the behaviour of `zero_division` when setting to 0, 1 or np.nan. No warnings should be raised. """ with warnings.catch_warnings(): warnings.simplefilter("error") result = metric(y_true, y_pred, zero_di...
Check the behaviour of `zero_division` when setting to 0, 1 or np.nan. No warnings should be raised.
test_zero_division_nan_no_warning
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_zero_division_nan_warning(metric, y_true, y_pred): """Check the behaviour of `zero_division` when setting to "warn". A `UndefinedMetricWarning` should be raised. """ with pytest.warns(UndefinedMetricWarning): result = metric(y_true, y_pred, zero_division="warn") assert result == 0.0
Check the behaviour of `zero_division` when setting to "warn". A `UndefinedMetricWarning` should be raised.
test_zero_division_nan_warning
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_confusion_matrix_pandas_nullable(dtype): """Checks that confusion_matrix works with pandas nullable dtypes. Non-regression test for gh-25635. """ pd = pytest.importorskip("pandas") y_ndarray = np.array([1, 0, 0, 1, 0, 1, 1, 0, 1]) y_true = pd.Series(y_ndarray, dtype=dtype) y_predi...
Checks that confusion_matrix works with pandas nullable dtypes. Non-regression test for gh-25635.
test_confusion_matrix_pandas_nullable
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_log_loss_eps(dtype): """Check the behaviour internal eps that changes depending on the input dtype. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/24315 """ y_true = np.array([0, 1], dtype=dtype) y_pred = np.array([1, 0], dtype=dtype) loss = log_loss(...
Check the behaviour internal eps that changes depending on the input dtype. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/24315
test_log_loss_eps
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_log_loss_not_probabilities_warning(dtype): """Check that log_loss raises a warning when y_pred values don't sum to 1.""" y_true = np.array([0, 1, 1, 0]) y_pred = np.array([[0.2, 0.7], [0.6, 0.3], [0.4, 0.7], [0.8, 0.3]], dtype=dtype) with pytest.warns(UserWarning, match="The y_prob values do n...
Check that log_loss raises a warning when y_pred values don't sum to 1.
test_log_loss_not_probabilities_warning
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_log_loss_perfect_predictions(y_true, y_pred): """Check that log_loss returns 0 for perfect predictions.""" # Because of the clipping, the result is not exactly 0 assert log_loss(y_true, y_pred) == pytest.approx(0)
Check that log_loss returns 0 for perfect predictions.
test_log_loss_perfect_predictions
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_classification_metric_pos_label_types(metric, classes): """Check that the metric works with different types of `pos_label`. We can expect `pos_label` to be a bool, an integer, a float, a string. No error should be raised for those types. """ rng = np.random.RandomState(42) n_samples, p...
Check that the metric works with different types of `pos_label`. We can expect `pos_label` to be a bool, an integer, a float, a string. No error should be raised for those types.
test_classification_metric_pos_label_types
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_classification_metric_division_by_zero_nan_validaton(scoring): """Check that we validate `np.nan` properly for classification metrics. With `n_jobs=2` in cross-validation, the `np.nan` used for the singleton will be different in the sub-process and we should not use the `is` operator but `math...
Check that we validate `np.nan` properly for classification metrics. With `n_jobs=2` in cross-validation, the `np.nan` used for the singleton will be different in the sub-process and we should not use the `is` operator but `math.isnan`. Non-regression test for: https://github.com/scikit-learn/scik...
test_classification_metric_division_by_zero_nan_validaton
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_d2_log_loss_score_missing_labels(): """Check that d2_log_loss_score works when not all labels are present in y_true non-regression test for https://github.com/scikit-learn/scikit-learn/issues/30713 """ y_true = [2, 0, 2, 0] labels = [0, 1, 2] sample_weight = [1.4, 0.6, 0.7, 0.3] y_...
Check that d2_log_loss_score works when not all labels are present in y_true non-regression test for https://github.com/scikit-learn/scikit-learn/issues/30713
test_d2_log_loss_score_missing_labels
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_d2_log_loss_score_label_order(): """Check that d2_log_loss_score doesn't depend on the order of the labels.""" y_true = [2, 0, 2, 0] y_pred = np.tile([1, 0, 0], (4, 1)) d2_score = d2_log_loss_score(y_true, y_pred, labels=[0, 1, 2]) d2_score_other = d2_log_loss_score(y_true, y_pred, labels=...
Check that d2_log_loss_score doesn't depend on the order of the labels.
test_d2_log_loss_score_label_order
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def test_d2_log_loss_score_raises(): """Test that d2_log_loss_score raises the appropriate errors on invalid inputs.""" y_true = [0, 1, 2] y_pred = [[0.2, 0.8], [0.5, 0.5], [0.4, 0.6]] err = "contain different number of classes" with pytest.raises(ValueError, match=err): d2_log_loss_scor...
Test that d2_log_loss_score raises the appropriate errors on invalid inputs.
test_d2_log_loss_score_raises
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_classification.py
BSD-3-Clause
def precision_recall_curve_padded_thresholds(*args, **kwargs): """ The dimensions of precision-recall pairs and the threshold array as returned by the precision_recall_curve do not match. See func:`sklearn.metrics.precision_recall_curve` This prevents implicit conversion of return value triple to a...
The dimensions of precision-recall pairs and the threshold array as returned by the precision_recall_curve do not match. See func:`sklearn.metrics.precision_recall_curve` This prevents implicit conversion of return value triple to an higher dimensional np.array of dtype('float64') (it will be of d...
precision_recall_curve_padded_thresholds
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_common.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_common.py
BSD-3-Clause
def test_classification_inf_nan_input(metric, y_true, y_score): """check that classification metrics raise a message mentioning the occurrence of non-finite values in the target vectors.""" if not np.isfinite(y_true).all(): input_name = "y_true" if np.isnan(y_true).any(): unexpec...
check that classification metrics raise a message mentioning the occurrence of non-finite values in the target vectors.
test_classification_inf_nan_input
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_common.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_common.py
BSD-3-Clause
def test_classification_binary_continuous_input(metric): """check that classification metrics raise a message of mixed type data with continuous/binary target vectors.""" y_true, y_score = ["a", "b", "a"], [0.1, 0.2, 0.3] err_msg = ( "Classification metrics can't handle a mix of binary and conti...
check that classification metrics raise a message of mixed type data with continuous/binary target vectors.
test_classification_binary_continuous_input
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_common.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_common.py
BSD-3-Clause
def _get_metric_kwargs_for_array_api_testing(metric, params): """Helper function to enable specifying a variety of additional params and their corresponding values, so that they can be passed to a metric function when testing for array api compliance.""" metric_kwargs_combinations = [{}] for param, ...
Helper function to enable specifying a variety of additional params and their corresponding values, so that they can be passed to a metric function when testing for array api compliance.
_get_metric_kwargs_for_array_api_testing
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_common.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_common.py
BSD-3-Clause
def test_returned_value_consistency(name): """Ensure that the returned values of all metrics are consistent. It can either be a float, a numpy array, or a tuple of floats or numpy arrays. It should not be a numpy float64 or float32. """ rng = np.random.RandomState(0) y_true = rng.randint(0, 2,...
Ensure that the returned values of all metrics are consistent. It can either be a float, a numpy array, or a tuple of floats or numpy arrays. It should not be a numpy float64 or float32.
test_returned_value_consistency
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_common.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_common.py
BSD-3-Clause
def test_nan_euclidean_support(pairwise_distances_func): """Check that `nan_euclidean` is lenient with `nan` values.""" X = [[0, 1], [1, np.nan], [2, 3], [3, 5]] output = pairwise_distances_func(X, X, metric="nan_euclidean") assert not np.isnan(output).any()
Check that `nan_euclidean` is lenient with `nan` values.
test_nan_euclidean_support
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise.py
BSD-3-Clause
def test_nan_euclidean_constant_input_argmin(): """Check that the behavior of constant input is the same in the case of full of nan vector and full of zero vector. """ X_nan = [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]] argmin_nan = pairwise_distances_argmin(X_nan, X_nan, metric="nan_euc...
Check that the behavior of constant input is the same in the case of full of nan vector and full of zero vector.
test_nan_euclidean_constant_input_argmin
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise.py
BSD-3-Clause
def test_pairwise_dist_custom_metric_for_string(X, Y, expected_distance): """Check pairwise_distances with lists of strings as input.""" def dummy_string_similarity(x, y): return np.abs(len(x) - len(y)) actual_distance = pairwise_distances(X=X, Y=Y, metric=dummy_string_similarity) assert_allcl...
Check pairwise_distances with lists of strings as input.
test_pairwise_dist_custom_metric_for_string
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise.py
BSD-3-Clause
def test_pairwise_dist_custom_metric_for_bool(): """Check that pairwise_distances does not convert boolean input to float when using a custom metric. """ def dummy_bool_dist(v1, v2): # dummy distance func using `&` and thus relying on the input data being boolean return 1 - (v1 & v2).su...
Check that pairwise_distances does not convert boolean input to float when using a custom metric.
test_pairwise_dist_custom_metric_for_bool
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise.py
BSD-3-Clause
def _get_metric_params_list(metric: str, n_features: int, seed: int = 1): """Return list of dummy DistanceMetric kwargs for tests.""" # Distinguishing on cases not to compute unneeded datastructures. rng = np.random.RandomState(seed) if metric == "minkowski": minkowski_kwargs = [ d...
Return list of dummy DistanceMetric kwargs for tests.
_get_metric_params_list
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise_distances_reduction.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py
BSD-3-Clause
def assert_same_distances_for_common_neighbors( query_idx, dist_row_a, dist_row_b, indices_row_a, indices_row_b, rtol, atol, ): """Check that the distances of common neighbors are equal up to tolerance. This does not check if there are missing neighbors in either result set. Mis...
Check that the distances of common neighbors are equal up to tolerance. This does not check if there are missing neighbors in either result set. Missingness is handled by assert_no_missing_neighbors.
assert_same_distances_for_common_neighbors
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise_distances_reduction.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py
BSD-3-Clause
def assert_no_missing_neighbors( query_idx, dist_row_a, dist_row_b, indices_row_a, indices_row_b, threshold, ): """Compare the indices of neighbors in two results sets. Any neighbor index with a distance below the precision threshold should match one in the other result set. We igno...
Compare the indices of neighbors in two results sets. Any neighbor index with a distance below the precision threshold should match one in the other result set. We ignore the last few neighbors beyond the threshold as those can typically be missing due to rounding errors. For radius queries, the thres...
assert_no_missing_neighbors
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise_distances_reduction.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py
BSD-3-Clause
def assert_compatible_argkmin_results( neighbors_dists_a, neighbors_dists_b, neighbors_indices_a, neighbors_indices_b, rtol=1e-5, atol=1e-6, ): """Assert that argkmin results are valid up to rounding errors. This function asserts that the results of argkmin queries are valid up to: ...
Assert that argkmin results are valid up to rounding errors. This function asserts that the results of argkmin queries are valid up to: - rounding error tolerance on distance values; - permutations of indices for distances values that differ up to the expected precision level. Furthermore, the d...
assert_compatible_argkmin_results
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise_distances_reduction.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py
BSD-3-Clause
def assert_compatible_radius_results( neighbors_dists_a, neighbors_dists_b, neighbors_indices_a, neighbors_indices_b, radius, check_sorted=True, rtol=1e-5, atol=1e-6, ): """Assert that radius neighborhood results are valid up to: - relative and absolute tolerance on computed d...
Assert that radius neighborhood results are valid up to: - relative and absolute tolerance on computed distance values - permutations of indices for distances values that differ up to a precision level - missing or extra last elements if their distance is close to the radius To b...
assert_compatible_radius_results
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise_distances_reduction.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py
BSD-3-Clause
def test_chunk_size_agnosticism( global_random_seed, Dispatcher, dtype, n_features=100, ): """Check that results do not depend on the chunk size.""" rng = np.random.RandomState(global_random_seed) spread = 100 n_samples_X, n_samples_Y = rng.choice([97, 100, 101, 500], size=2, replace=Fal...
Check that results do not depend on the chunk size.
test_chunk_size_agnosticism
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise_distances_reduction.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py
BSD-3-Clause
def test_n_threads_agnosticism( global_random_seed, Dispatcher, dtype, n_features=100, ): """Check that results do not depend on the number of threads.""" rng = np.random.RandomState(global_random_seed) n_samples_X, n_samples_Y = rng.choice([97, 100, 101, 500], size=2, replace=False) spr...
Check that results do not depend on the number of threads.
test_n_threads_agnosticism
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise_distances_reduction.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py
BSD-3-Clause
def test_format_agnosticism( global_random_seed, Dispatcher, dtype, csr_container, ): """Check that results do not depend on the format (dense, sparse) of the input.""" rng = np.random.RandomState(global_random_seed) spread = 100 n_samples, n_features = 100, 100 X = rng.rand(n_sampl...
Check that results do not depend on the format (dense, sparse) of the input.
test_format_agnosticism
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise_distances_reduction.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py
BSD-3-Clause
def test_strategies_consistency( global_random_seed, global_dtype, Dispatcher, n_features=10, ): """Check that the results do not depend on the strategy used.""" rng = np.random.RandomState(global_random_seed) metric = rng.choice( np.array( [ "euclidean", ...
Check that the results do not depend on the strategy used.
test_strategies_consistency
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise_distances_reduction.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py
BSD-3-Clause
def test_memmap_backed_data( metric, Dispatcher, dtype, ): """Check that the results do not depend on the datasets writability.""" rng = np.random.RandomState(0) spread = 100 n_samples, n_features = 128, 10 X = rng.rand(n_samples, n_features).astype(dtype) * spread Y = rng.rand(n_sam...
Check that the results do not depend on the datasets writability.
test_memmap_backed_data
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_pairwise_distances_reduction.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_pairwise_distances_reduction.py
BSD-3-Clause
def _auc(y_true, y_score): """Alternative implementation to check for correctness of `roc_auc_score`.""" pos_label = np.unique(y_true)[1] # Count the number of times positive samples are correctly ranked above # negative samples. pos = y_score[y_true == pos_label] neg = y_score[y_true != po...
Alternative implementation to check for correctness of `roc_auc_score`.
_auc
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py
BSD-3-Clause
def _average_precision(y_true, y_score): """Alternative implementation to check for correctness of `average_precision_score`. Note that this implementation fails on some edge cases. For example, for constant predictions e.g. [0.5, 0.5, 0.5], y_true = [1, 0, 0] returns an average precision of 0.33.....
Alternative implementation to check for correctness of `average_precision_score`. Note that this implementation fails on some edge cases. For example, for constant predictions e.g. [0.5, 0.5, 0.5], y_true = [1, 0, 0] returns an average precision of 0.33... but y_true = [0, 0, 1] returns 1.0.
_average_precision
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py
BSD-3-Clause
def _average_precision_slow(y_true, y_score): """A second alternative implementation of average precision that closely follows the Wikipedia article's definition (see References). This should give identical results as `average_precision_score` for all inputs. References ---------- .. [1] `Wikip...
A second alternative implementation of average precision that closely follows the Wikipedia article's definition (see References). This should give identical results as `average_precision_score` for all inputs. References ---------- .. [1] `Wikipedia entry for the Average precision <https://...
_average_precision_slow
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py
BSD-3-Clause
def _partial_roc_auc_score(y_true, y_predict, max_fpr): """Alternative implementation to check for correctness of `roc_auc_score` with `max_fpr` set. """ def _partial_roc(y_true, y_predict, max_fpr): fpr, tpr, _ = roc_curve(y_true, y_predict) new_fpr = fpr[fpr <= max_fpr] new_fp...
Alternative implementation to check for correctness of `roc_auc_score` with `max_fpr` set.
_partial_roc_auc_score
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py
BSD-3-Clause
def test_precision_recall_curve_drop_intermediate(): """Check the behaviour of the `drop_intermediate` parameter.""" y_true = [0, 0, 0, 0, 1, 1] y_score = [0.0, 0.2, 0.5, 0.6, 0.7, 1.0] precision, recall, thresholds = precision_recall_curve( y_true, y_score, drop_intermediate=True ) asse...
Check the behaviour of the `drop_intermediate` parameter.
test_precision_recall_curve_drop_intermediate
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py
BSD-3-Clause
def _my_lrap(y_true, y_score): """Simple implementation of label ranking average precision""" check_consistent_length(y_true, y_score) y_true = check_array(y_true) y_score = check_array(y_score) n_samples, n_labels = y_true.shape score = np.empty((n_samples,)) for i in range(n_samples): ...
Simple implementation of label ranking average precision
_my_lrap
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py
BSD-3-Clause
def test_ndcg_negative_ndarray_error(): """Check `ndcg_score` exception when `y_true` contains negative values.""" y_true = np.array([[-0.89, -0.53, -0.47, 0.39, 0.56]]) y_score = np.array([[0.07, 0.31, 0.75, 0.33, 0.27]]) expected_message = "ndcg_score should not be used on negative y_true values" ...
Check `ndcg_score` exception when `y_true` contains negative values.
test_ndcg_negative_ndarray_error
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py
BSD-3-Clause
def test_ndcg_error_single_document(): """Check that we raise an informative error message when trying to compute NDCG with a single document.""" err_msg = ( "Computing NDCG is only meaningful when there is more than 1 document. " "Got 1 instead." ) with pytest.raises(ValueError, mat...
Check that we raise an informative error message when trying to compute NDCG with a single document.
test_ndcg_error_single_document
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py
BSD-3-Clause
def test_top_k_accuracy_score_multiclass_with_labels( y_true, true_score, labels, labels_as_ndarray ): """Test when labels and y_score are multiclass.""" if labels_as_ndarray: labels = np.asarray(labels) y_score = np.array( [ [0.4, 0.3, 0.2, 0.1], [0.1, 0.3, 0.4, ...
Test when labels and y_score are multiclass.
test_top_k_accuracy_score_multiclass_with_labels
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py
BSD-3-Clause
def test_roc_curve_with_probablity_estimates(global_random_seed): """Check that thresholds do not exceed 1.0 when `y_score` is a probability estimate. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/26193 """ rng = np.random.RandomState(global_random_seed) y_tru...
Check that thresholds do not exceed 1.0 when `y_score` is a probability estimate. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/26193
test_roc_curve_with_probablity_estimates
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_ranking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_ranking.py
BSD-3-Clause
def test_multimetric_scorer_exception_handling(raise_exc): """Check that the calling of the `_MultimetricScorer` returns exception messages in the result dict for the failing scorers in case of `raise_exc` is `False` and if `raise_exc` is `True`, then the proper exception is raised. """ scorers ...
Check that the calling of the `_MultimetricScorer` returns exception messages in the result dict for the failing scorers in case of `raise_exc` is `False` and if `raise_exc` is `True`, then the proper exception is raised.
test_multimetric_scorer_exception_handling
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def string_labeled_classification_problem(): """Train a classifier on binary problem with string target. The classifier is trained on a binary classification problem where the minority class of interest has a string label that is intentionally not the greatest class label using the lexicographic order....
Train a classifier on binary problem with string target. The classifier is trained on a binary classification problem where the minority class of interest has a string label that is intentionally not the greatest class label using the lexicographic order. In this case, "cancer" is the positive label, a...
string_labeled_classification_problem
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def test_scorer_set_score_request_raises(name): """Test that set_score_request is only available when feature flag is on.""" # Make sure they expose the routing methods. scorer = get_scorer(name) with pytest.raises(RuntimeError, match="This method is only available"): scorer.set_score_request()
Test that set_score_request is only available when feature flag is on.
test_scorer_set_score_request_raises
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def test_scorer_metadata_request(name): """Testing metadata requests for scorers. This test checks many small things in a large test, to reduce the boilerplate required for each section. """ # Make sure they expose the routing methods. scorer = get_scorer(name) assert hasattr(scorer, "set_s...
Testing metadata requests for scorers. This test checks many small things in a large test, to reduce the boilerplate required for each section.
test_scorer_metadata_request
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def test_metadata_kwarg_conflict(): """This test makes sure the right warning is raised if the user passes some metadata both as a constructor to make_scorer, and during __call__. """ X, y = make_classification( n_classes=3, n_informative=3, n_samples=20, random_state=0 ) lr = LogisticRe...
This test makes sure the right warning is raised if the user passes some metadata both as a constructor to make_scorer, and during __call__.
test_metadata_kwarg_conflict
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def test_PassthroughScorer_set_score_request(): """Test that _PassthroughScorer.set_score_request adds the correct metadata request on itself and doesn't change its estimator's routing.""" est = LogisticRegression().set_score_request(sample_weight="estimator_weights") # make a `_PassthroughScorer` with ...
Test that _PassthroughScorer.set_score_request adds the correct metadata request on itself and doesn't change its estimator's routing.
test_PassthroughScorer_set_score_request
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def test_PassthroughScorer_set_score_request_raises_without_routing_enabled(): """Test that _PassthroughScorer.set_score_request raises if metadata routing is disabled.""" scorer = check_scoring(LogisticRegression(), None) msg = "This method is only available when metadata routing is enabled." with...
Test that _PassthroughScorer.set_score_request raises if metadata routing is disabled.
test_PassthroughScorer_set_score_request_raises_without_routing_enabled
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def test_get_scorer_multilabel_indicator(): """Check that our scorer deal with multi-label indicator matrices. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/26817 """ X, Y = make_multilabel_classification(n_samples=72, n_classes=3, random_state=0) X_train, X_test,...
Check that our scorer deal with multi-label indicator matrices. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/26817
test_get_scorer_multilabel_indicator
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def test_get_scorer_multimetric(pass_estimator): """Check that check_scoring is compatible with multi-metric configurations.""" X, y = make_classification(n_samples=150, n_features=10, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LogisticRegression(rand...
Check that check_scoring is compatible with multi-metric configurations.
test_get_scorer_multimetric
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def test_check_scoring_multimetric_raise_exc(): """Test that check_scoring returns error code for a subset of scorers in multimetric scoring if raise_exc=False and raises otherwise.""" def raising_scorer(estimator, X, y): raise ValueError("That doesn't work.") X, y = make_classification(n_samp...
Test that check_scoring returns error code for a subset of scorers in multimetric scoring if raise_exc=False and raises otherwise.
test_check_scoring_multimetric_raise_exc
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def test_metadata_routing_multimetric_metadata_routing(enable_metadata_routing): """Test multimetric scorer works with and without metadata routing enabled when there is no actual metadata to pass. Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28256 """ X, y = make_cla...
Test multimetric scorer works with and without metadata routing enabled when there is no actual metadata to pass. Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28256
test_metadata_routing_multimetric_metadata_routing
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def test_curve_scorer(): """Check the behaviour of the `_CurveScorer` class.""" X, y = make_classification(random_state=0) estimator = LogisticRegression().fit(X, y) curve_scorer = _CurveScorer( balanced_accuracy_score, sign=1, response_method="predict_proba", thresholds=...
Check the behaviour of the `_CurveScorer` class.
test_curve_scorer
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def test_curve_scorer_pos_label(global_random_seed): """Check that we propagate properly the `pos_label` parameter to the scorer.""" n_samples = 30 X, y = make_classification( n_samples=n_samples, weights=[0.9, 0.1], random_state=global_random_seed ) estimator = LogisticRegression().fit(X, y...
Check that we propagate properly the `pos_label` parameter to the scorer.
test_curve_scorer_pos_label
python
scikit-learn/scikit-learn
sklearn/metrics/tests/test_score_objects.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/tests/test_score_objects.py
BSD-3-Clause
def sqeuclidean_row_norms(X, num_threads): """Compute the squared euclidean norm of the rows of X in parallel. Parameters ---------- X : ndarray or CSR matrix of shape (n_samples, n_features) Input data. Must be c-contiguous. num_threads : int The number of OpenMP threads to use. ...
Compute the squared euclidean norm of the rows of X in parallel. Parameters ---------- X : ndarray or CSR matrix of shape (n_samples, n_features) Input data. Must be c-contiguous. num_threads : int The number of OpenMP threads to use. Returns ------- sqeuclidean_row_norms ...
sqeuclidean_row_norms
python
scikit-learn/scikit-learn
sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
BSD-3-Clause
def is_usable_for(cls, X, Y, metric) -> bool: """Return True if the dispatcher can be used for the given parameters. Parameters ---------- X : {ndarray, sparse matrix} of shape (n_samples_X, n_features) Input data. Y : {ndarray, sparse matrix} of shape (n_sa...
Return True if the dispatcher can be used for the given parameters. Parameters ---------- X : {ndarray, sparse matrix} of shape (n_samples_X, n_features) Input data. Y : {ndarray, sparse matrix} of shape (n_samples_Y, n_features) Input data. met...
is_usable_for
python
scikit-learn/scikit-learn
sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
BSD-3-Clause
def compute( cls, X, Y, **kwargs, ): """Compute the reduction. Parameters ---------- X : ndarray or CSR matrix of shape (n_samples_X, n_features) Input data. Y : ndarray or CSR matrix of shape (n_samples_Y, n_features) ...
Compute the reduction. Parameters ---------- X : ndarray or CSR matrix of shape (n_samples_X, n_features) Input data. Y : ndarray or CSR matrix of shape (n_samples_Y, n_features) Input data. **kwargs : additional parameters for the reduction No...
compute
python
scikit-learn/scikit-learn
sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
BSD-3-Clause
def compute( cls, X, Y, k, metric="euclidean", chunk_size=None, metric_kwargs=None, strategy=None, return_distance=False, ): """Compute the argkmin reduction. Parameters ---------- X : ndarray or CSR matrix of s...
Compute the argkmin reduction. Parameters ---------- X : ndarray or CSR matrix of shape (n_samples_X, n_features) Input data. Y : ndarray or CSR matrix of shape (n_samples_Y, n_features) Input data. k : int The k for the argkmin reduction. ...
compute
python
scikit-learn/scikit-learn
sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
BSD-3-Clause
def compute( cls, X, Y, radius, metric="euclidean", chunk_size=None, metric_kwargs=None, strategy=None, return_distance=False, sort_results=False, ): """Return the results of the reduction for the given arguments. Param...
Return the results of the reduction for the given arguments. Parameters ---------- X : ndarray or CSR matrix of shape (n_samples_X, n_features) Input data. Y : ndarray or CSR matrix of shape (n_samples_Y, n_features) Input data. radius : float ...
compute
python
scikit-learn/scikit-learn
sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
BSD-3-Clause
def compute( cls, X, Y, k, weights, Y_labels, unique_Y_labels, metric="euclidean", chunk_size=None, metric_kwargs=None, strategy=None, ): """Compute the argkmin reduction. Parameters ---------- X...
Compute the argkmin reduction. Parameters ---------- X : ndarray of shape (n_samples_X, n_features) The input array to be labelled. Y : ndarray of shape (n_samples_Y, n_features) The input array whose class membership are provided through the `Y_labe...
compute
python
scikit-learn/scikit-learn
sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
BSD-3-Clause
def compute( cls, X, Y, radius, weights, Y_labels, unique_Y_labels, outlier_label, metric="euclidean", chunk_size=None, metric_kwargs=None, strategy=None, ): """Return the results of the reduction for the given a...
Return the results of the reduction for the given arguments. Parameters ---------- X : ndarray of shape (n_samples_X, n_features) The input array to be labelled. Y : ndarray of shape (n_samples_Y, n_features) The input array whose class membership is provided thro...
compute
python
scikit-learn/scikit-learn
sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py
BSD-3-Clause
def plot( self, *, include_values=True, cmap="viridis", xticks_rotation="horizontal", values_format=None, ax=None, colorbar=True, im_kw=None, text_kw=None, ): """Plot visualization. Parameters ---------- ...
Plot visualization. Parameters ---------- include_values : bool, default=True Includes values in confusion matrix. cmap : str or matplotlib Colormap, default='viridis' Colormap recognized by matplotlib. xticks_rotation : {'vertical', 'horizontal'} or fl...
plot
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/confusion_matrix.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/confusion_matrix.py
BSD-3-Clause
def from_estimator( cls, estimator, X, y, *, labels=None, sample_weight=None, normalize=None, display_labels=None, include_values=True, xticks_rotation="horizontal", values_format=None, cmap="viridis", ax=Non...
Plot Confusion Matrix given an estimator and some data. For general information regarding `scikit-learn` visualization tools, see the :ref:`Visualization Guide <visualizations>`. For guidance on interpreting these plots, refer to the :ref:`Model Evaluation Guide <confusion_matrix>`. ...
from_estimator
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/confusion_matrix.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/confusion_matrix.py
BSD-3-Clause
def from_predictions( cls, y_true, y_pred, *, labels=None, sample_weight=None, normalize=None, display_labels=None, include_values=True, xticks_rotation="horizontal", values_format=None, cmap="viridis", ax=None, ...
Plot Confusion Matrix given true and predicted labels. For general information regarding `scikit-learn` visualization tools, see the :ref:`Visualization Guide <visualizations>`. For guidance on interpreting these plots, refer to the :ref:`Model Evaluation Guide <confusion_matrix>`. ...
from_predictions
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/confusion_matrix.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/confusion_matrix.py
BSD-3-Clause
def from_estimator( cls, estimator, X, y, *, sample_weight=None, drop_intermediate=True, response_method="auto", pos_label=None, name=None, ax=None, **kwargs, ): """Plot DET curve given an estimator and data. ...
Plot DET curve given an estimator and data. For general information regarding `scikit-learn` visualization tools, see the :ref:`Visualization Guide <visualizations>`. For guidance on interpreting these plots, refer to the :ref:`Model Evaluation Guide <det_curve>`. .. versionadd...
from_estimator
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/det_curve.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/det_curve.py
BSD-3-Clause
def from_predictions( cls, y_true, y_pred, *, sample_weight=None, drop_intermediate=True, pos_label=None, name=None, ax=None, **kwargs, ): """Plot the DET curve given the true and predicted labels. For general informati...
Plot the DET curve given the true and predicted labels. For general information regarding `scikit-learn` visualization tools, see the :ref:`Visualization Guide <visualizations>`. For guidance on interpreting these plots, refer to the :ref:`Model Evaluation Guide <det_curve>`. ....
from_predictions
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/det_curve.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/det_curve.py
BSD-3-Clause
def plot(self, ax=None, *, name=None, **kwargs): """Plot visualization. Parameters ---------- ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. name : str, default=None Name of DET curve f...
Plot visualization. Parameters ---------- ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. name : str, default=None Name of DET curve for labeling. If `None`, use `estimator_name` if ...
plot
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/det_curve.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/det_curve.py
BSD-3-Clause
def plot( self, ax=None, *, name=None, plot_chance_level=False, chance_level_kw=None, despine=False, **kwargs, ): """Plot visualization. Extra keyword arguments will be passed to matplotlib's `plot`. Parameters -------...
Plot visualization. Extra keyword arguments will be passed to matplotlib's `plot`. Parameters ---------- ax : Matplotlib Axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. name : str, default=None Name of...
plot
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/precision_recall_curve.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/precision_recall_curve.py
BSD-3-Clause
def from_estimator( cls, estimator, X, y, *, sample_weight=None, drop_intermediate=False, response_method="auto", pos_label=None, name=None, ax=None, plot_chance_level=False, chance_level_kw=None, despine=Fal...
Plot precision-recall curve given an estimator and some data. For general information regarding `scikit-learn` visualization tools, see the :ref:`Visualization Guide <visualizations>`. For guidance on interpreting these plots, refer to the :ref:`Model Evaluation Guide <precision_recall_...
from_estimator
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/precision_recall_curve.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/precision_recall_curve.py
BSD-3-Clause
def from_predictions( cls, y_true, y_pred, *, sample_weight=None, drop_intermediate=False, pos_label=None, name=None, ax=None, plot_chance_level=False, chance_level_kw=None, despine=False, **kwargs, ): ""...
Plot precision-recall curve given binary class predictions. For general information regarding `scikit-learn` visualization tools, see the :ref:`Visualization Guide <visualizations>`. For guidance on interpreting these plots, refer to the :ref:`Model Evaluation Guide <precision_recall_f_...
from_predictions
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/precision_recall_curve.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/precision_recall_curve.py
BSD-3-Clause
def plot( self, ax=None, *, kind="residual_vs_predicted", scatter_kwargs=None, line_kwargs=None, ): """Plot visualization. Extra keyword arguments will be passed to matplotlib's ``plot``. Parameters ---------- ax : matplotlib ...
Plot visualization. Extra keyword arguments will be passed to matplotlib's ``plot``. Parameters ---------- ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. kind : {"actual_vs_predicted", "residual_v...
plot
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/regression.py
BSD-3-Clause
def from_estimator( cls, estimator, X, y, *, kind="residual_vs_predicted", subsample=1_000, random_state=None, ax=None, scatter_kwargs=None, line_kwargs=None, ): """Plot the prediction error given a regressor and some da...
Plot the prediction error given a regressor and some data. For general information regarding `scikit-learn` visualization tools, read more in the :ref:`Visualization Guide <visualizations>`. For details regarding interpreting these plots, refer to the :ref:`Model Evaluation Guide <visua...
from_estimator
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/regression.py
BSD-3-Clause
def from_predictions( cls, y_true, y_pred, *, kind="residual_vs_predicted", subsample=1_000, random_state=None, ax=None, scatter_kwargs=None, line_kwargs=None, ): """Plot the prediction error given the true and predicted targets...
Plot the prediction error given the true and predicted targets. For general information regarding `scikit-learn` visualization tools, read more in the :ref:`Visualization Guide <visualizations>`. For details regarding interpreting these plots, refer to the :ref:`Model Evaluation Guide <...
from_predictions
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/regression.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/regression.py
BSD-3-Clause
def plot( self, ax=None, *, name=None, curve_kwargs=None, plot_chance_level=False, chance_level_kw=None, despine=False, **kwargs, ): """Plot visualization. Parameters ---------- ax : matplotlib axes, default=Non...
Plot visualization. Parameters ---------- ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. name : str or list of str, default=None Name for labeling legend entries. The number of legend entries ...
plot
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/roc_curve.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/roc_curve.py
BSD-3-Clause
def from_estimator( cls, estimator, X, y, *, sample_weight=None, drop_intermediate=True, response_method="auto", pos_label=None, name=None, ax=None, curve_kwargs=None, plot_chance_level=False, chance_level_kw...
Create a ROC Curve display from an estimator. For general information regarding `scikit-learn` visualization tools, see the :ref:`Visualization Guide <visualizations>`. For guidance on interpreting these plots, refer to the :ref:`Model Evaluation Guide <roc_metrics>`. Parameter...
from_estimator
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/roc_curve.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/roc_curve.py
BSD-3-Clause
def from_cv_results( cls, cv_results, X, y, *, sample_weight=None, drop_intermediate=True, response_method="auto", pos_label=None, ax=None, name=None, curve_kwargs=None, plot_chance_level=False, chance_level_...
Create a multi-fold ROC curve display given cross-validation results. .. versionadded:: 1.7 Parameters ---------- cv_results : dict Dictionary as returned by :func:`~sklearn.model_selection.cross_validate` using `return_estimator=True` and `return_indices=True` ...
from_cv_results
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/roc_curve.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/roc_curve.py
BSD-3-Clause
def test_display_curve_error_classifier(pyplot, data, data_binary, Display): """Check that a proper error is raised when only binary classification is supported.""" X, y = data X_binary, y_binary = data_binary clf = DecisionTreeClassifier().fit(X, y) # Case 1: multiclass classifier with multicl...
Check that a proper error is raised when only binary classification is supported.
test_display_curve_error_classifier
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_common_curve_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_common_curve_display.py
BSD-3-Clause
def test_display_curve_error_regression(pyplot, data_binary, Display): """Check that we raise an error with regressor.""" # Case 1: regressor X, y = data_binary regressor = DecisionTreeRegressor().fit(X, y) msg = "Expected 'estimator' to be a binary classifier. Got DecisionTreeRegressor" with ...
Check that we raise an error with regressor.
test_display_curve_error_regression
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_common_curve_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_common_curve_display.py
BSD-3-Clause
def test_display_curve_error_no_response( pyplot, data_binary, response_method, msg, Display, ): """Check that a proper error is raised when the response method requested is not defined for the given trained classifier.""" X, y = data_binary class MyClassifier(ClassifierMixin, BaseE...
Check that a proper error is raised when the response method requested is not defined for the given trained classifier.
test_display_curve_error_no_response
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_common_curve_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_common_curve_display.py
BSD-3-Clause
def test_display_curve_estimator_name_multiple_calls( pyplot, data_binary, Display, constructor_name, ): """Check that passing `name` when calling `plot` will overwrite the original name in the legend.""" X, y = data_binary clf_name = "my hand-crafted name" clf = LogisticRegression()...
Check that passing `name` when calling `plot` will overwrite the original name in the legend.
test_display_curve_estimator_name_multiple_calls
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_common_curve_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_common_curve_display.py
BSD-3-Clause
def test_display_curve_not_fitted_errors_old_name(pyplot, data_binary, clf, Display): """Check that a proper error is raised when the classifier is not fitted.""" X, y = data_binary # clone since we parametrize the test and the classifier will be fitted # when testing the second and subsequent plott...
Check that a proper error is raised when the classifier is not fitted.
test_display_curve_not_fitted_errors_old_name
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_common_curve_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_common_curve_display.py
BSD-3-Clause
def test_display_curve_not_fitted_errors(pyplot, data_binary, clf, Display): """Check that a proper error is raised when the classifier is not fitted.""" X, y = data_binary # clone since we parametrize the test and the classifier will be fitted # when testing the second and subsequent plotting function ...
Check that a proper error is raised when the classifier is not fitted.
test_display_curve_not_fitted_errors
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_common_curve_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_common_curve_display.py
BSD-3-Clause
def test_display_curve_n_samples_consistency(pyplot, data_binary, Display): """Check the error raised when `y_pred` or `sample_weight` have inconsistent length.""" X, y = data_binary classifier = DecisionTreeClassifier().fit(X, y) msg = "Found input variables with inconsistent numbers of samples" ...
Check the error raised when `y_pred` or `sample_weight` have inconsistent length.
test_display_curve_n_samples_consistency
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_common_curve_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_common_curve_display.py
BSD-3-Clause
def test_display_curve_error_pos_label(pyplot, data_binary, Display): """Check consistence of error message when `pos_label` should be specified.""" X, y = data_binary y = y + 10 classifier = DecisionTreeClassifier().fit(X, y) y_pred = classifier.predict_proba(X)[:, -1] msg = r"y_true takes val...
Check consistence of error message when `pos_label` should be specified.
test_display_curve_error_pos_label
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_common_curve_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_common_curve_display.py
BSD-3-Clause
def test_confusion_matrix_display_validation(pyplot): """Check that we raise the proper error when validating parameters.""" X, y = make_classification( n_samples=100, n_informative=5, n_classes=5, random_state=0 ) with pytest.raises(NotFittedError): ConfusionMatrixDisplay.from_estimato...
Check that we raise the proper error when validating parameters.
test_confusion_matrix_display_validation
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
BSD-3-Clause
def test_confusion_matrix_display_custom_labels( pyplot, constructor_name, with_labels, with_display_labels ): """Check the resulting plot when labels are given.""" n_classes = 5 X, y = make_classification( n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 ) classifier ...
Check the resulting plot when labels are given.
test_confusion_matrix_display_custom_labels
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
BSD-3-Clause
def test_confusion_matrix_display(pyplot, constructor_name): """Check the behaviour of the default constructor without using the class methods.""" n_classes = 5 X, y = make_classification( n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 ) classifier = SVC().fit(X, y) ...
Check the behaviour of the default constructor without using the class methods.
test_confusion_matrix_display
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
BSD-3-Clause
def test_confusion_matrix_contrast(pyplot): """Check that the text color is appropriate depending on background.""" cm = np.eye(2) / 2 disp = ConfusionMatrixDisplay(cm, display_labels=[0, 1]) disp.plot(cmap=pyplot.cm.gray) # diagonal text is black assert_allclose(disp.text_[0, 0].get_color(), ...
Check that the text color is appropriate depending on background.
test_confusion_matrix_contrast
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
BSD-3-Clause
def test_confusion_matrix_pipeline(pyplot, clf): """Check the behaviour of the plotting with more complex pipeline.""" n_classes = 5 X, y = make_classification( n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 ) with pytest.raises(NotFittedError): ConfusionMatrixDi...
Check the behaviour of the plotting with more complex pipeline.
test_confusion_matrix_pipeline
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
BSD-3-Clause
def test_confusion_matrix_with_unknown_labels(pyplot, constructor_name): """Check that when labels=None, the unique values in `y_pred` and `y_true` will be used. Non-regression test for: https://github.com/scikit-learn/scikit-learn/pull/18405 """ n_classes = 5 X, y = make_classification( ...
Check that when labels=None, the unique values in `y_pred` and `y_true` will be used. Non-regression test for: https://github.com/scikit-learn/scikit-learn/pull/18405
test_confusion_matrix_with_unknown_labels
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
BSD-3-Clause
def test_colormap_max(pyplot): """Check that the max color is used for the color of the text.""" gray = pyplot.get_cmap("gray", 1024) confusion_matrix = np.array([[1.0, 0.0], [0.0, 1.0]]) disp = ConfusionMatrixDisplay(confusion_matrix) disp.plot(cmap=gray) color = disp.text_[1, 0].get_color() ...
Check that the max color is used for the color of the text.
test_colormap_max
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
BSD-3-Clause
def test_im_kw_adjust_vmin_vmax(pyplot): """Check that im_kw passes kwargs to imshow""" confusion_matrix = np.array([[0.48, 0.04], [0.08, 0.4]]) disp = ConfusionMatrixDisplay(confusion_matrix) disp.plot(im_kw=dict(vmin=0.0, vmax=0.8)) clim = disp.im_.get_clim() assert clim[0] == pytest.approx(...
Check that im_kw passes kwargs to imshow
test_im_kw_adjust_vmin_vmax
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
BSD-3-Clause
def test_confusion_matrix_text_kw(pyplot): """Check that text_kw is passed to the text call.""" font_size = 15.0 X, y = make_classification(random_state=0) classifier = SVC().fit(X, y) # from_estimator passes the font size disp = ConfusionMatrixDisplay.from_estimator( classifier, X, y, ...
Check that text_kw is passed to the text call.
test_confusion_matrix_text_kw
python
scikit-learn/scikit-learn
sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py
BSD-3-Clause