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 predict(self, X): """Perform regression on samples in X. For an one-class model, +1 (inlier) or -1 (outlier) is returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) For kernel="precomputed", the expected shape of X is ...
Perform regression on samples in X. For an one-class model, +1 (inlier) or -1 (outlier) is returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) For kernel="precomputed", the expected shape of X is (n_samples_test, n_sa...
predict
python
scikit-learn/scikit-learn
sklearn/svm/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.py
BSD-3-Clause
def _compute_kernel(self, X): """Return the data transformed by a callable kernel""" if callable(self.kernel): # in the case of precomputed kernel given as a function, we # have to compute explicitly the kernel matrix kernel = self.kernel(X, self.__Xfit) i...
Return the data transformed by a callable kernel
_compute_kernel
python
scikit-learn/scikit-learn
sklearn/svm/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.py
BSD-3-Clause
def _decision_function(self, X): """Evaluates the decision function for the samples in X. Parameters ---------- X : array-like of shape (n_samples, n_features) Returns ------- X : array-like of shape (n_samples, n_class * (n_class-1) / 2) Returns the...
Evaluates the decision function for the samples in X. Parameters ---------- X : array-like of shape (n_samples, n_features) Returns ------- X : array-like of shape (n_samples, n_class * (n_class-1) / 2) Returns the decision function of the sample for each cl...
_decision_function
python
scikit-learn/scikit-learn
sklearn/svm/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.py
BSD-3-Clause
def coef_(self): """Weights assigned to the features when `kernel="linear"`. Returns ------- ndarray of shape (n_features, n_classes) """ if self.kernel != "linear": raise AttributeError("coef_ is only available when using a linear kernel") coef = se...
Weights assigned to the features when `kernel="linear"`. Returns ------- ndarray of shape (n_features, n_classes)
coef_
python
scikit-learn/scikit-learn
sklearn/svm/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.py
BSD-3-Clause
def n_support_(self): """Number of support vectors for each class.""" try: check_is_fitted(self) except NotFittedError: raise AttributeError svm_type = LIBSVM_IMPL.index(self._impl) if svm_type in (0, 1): return self._n_support else: ...
Number of support vectors for each class.
n_support_
python
scikit-learn/scikit-learn
sklearn/svm/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.py
BSD-3-Clause
def decision_function(self, X): """Evaluate the decision function for the samples in X. Parameters ---------- X : array-like of shape (n_samples, n_features) The input samples. Returns ------- X : ndarray of shape (n_samples, n_classes * (n_classes-1...
Evaluate the decision function for the samples in X. Parameters ---------- X : array-like of shape (n_samples, n_features) The input samples. Returns ------- X : ndarray of shape (n_samples, n_classes * (n_classes-1) / 2) Returns the decision fun...
decision_function
python
scikit-learn/scikit-learn
sklearn/svm/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.py
BSD-3-Clause
def predict(self, X): """Perform classification on samples in X. For an one-class model, +1 or -1 is returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ (n_samples_test, n_samples_train) For kernel="p...
Perform classification on samples in X. For an one-class model, +1 or -1 is returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples_test, n_samples_train) For kernel="precomputed", the expected shape of ...
predict
python
scikit-learn/scikit-learn
sklearn/svm/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.py
BSD-3-Clause
def predict_proba(self, X): """Compute probabilities of possible outcomes for samples in X. The model needs to have probability information computed at training time: fit with attribute `probability` set to True. Parameters ---------- X : array-like of shape (n_samples,...
Compute probabilities of possible outcomes for samples in X. The model needs to have probability information computed at training time: fit with attribute `probability` set to True. Parameters ---------- X : array-like of shape (n_samples, n_features) For kernel="pr...
predict_proba
python
scikit-learn/scikit-learn
sklearn/svm/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.py
BSD-3-Clause
def _get_liblinear_solver_type(multi_class, penalty, loss, dual): """Find the liblinear magic number for the solver. This number depends on the values of the following attributes: - multi_class - penalty - loss - dual The same number is also internally used by LibLinear to determin...
Find the liblinear magic number for the solver. This number depends on the values of the following attributes: - multi_class - penalty - loss - dual The same number is also internally used by LibLinear to determine which solver to use.
_get_liblinear_solver_type
python
scikit-learn/scikit-learn
sklearn/svm/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.py
BSD-3-Clause
def _fit_liblinear( X, y, C, fit_intercept, intercept_scaling, class_weight, penalty, dual, verbose, max_iter, tol, random_state=None, multi_class="ovr", loss="logistic_regression", epsilon=0.1, sample_weight=None, ): """Used by Logistic Regression (an...
Used by Logistic Regression (and CV) and LinearSVC/LinearSVR. Preprocessing is done in this function before supplying it to liblinear. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and ...
_fit_liblinear
python
scikit-learn/scikit-learn
sklearn/svm/_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_base.py
BSD-3-Clause
def l1_min_c(X, y, *, loss="squared_hinge", fit_intercept=True, intercept_scaling=1.0): """Return the lowest bound for `C`. The lower bound for `C` is computed such that for `C` in `(l1_min_C, infinity)` the model is guaranteed not to be empty. This applies to l1 penalized classifiers, such as :class:`...
Return the lowest bound for `C`. The lower bound for `C` is computed such that for `C` in `(l1_min_C, infinity)` the model is guaranteed not to be empty. This applies to l1 penalized classifiers, such as :class:`sklearn.svm.LinearSVC` with penalty='l1' and :class:`sklearn.linear_model.LogisticRegressio...
l1_min_c
python
scikit-learn/scikit-learn
sklearn/svm/_bounds.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_bounds.py
BSD-3-Clause
def _validate_dual_parameter(dual, loss, penalty, multi_class, X): """Helper function to assign the value of dual parameter.""" if dual == "auto": if X.shape[0] < X.shape[1]: try: _get_liblinear_solver_type(multi_class, penalty, loss, True) return True ...
Helper function to assign the value of dual parameter.
_validate_dual_parameter
python
scikit-learn/scikit-learn
sklearn/svm/_classes.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_classes.py
BSD-3-Clause
def fit(self, X, y, sample_weight=None): """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 ...
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/svm/_classes.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_classes.py
BSD-3-Clause
def fit(self, X, y, sample_weight=None): """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 ...
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/svm/_classes.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_classes.py
BSD-3-Clause
def fit(self, X, y=None, sample_weight=None): """Detect the soft boundary of the set of samples X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Set of samples, where `n_samples` is the number of samples and `n_features` i...
Detect the soft boundary of the set of samples X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Set of samples, where `n_samples` is the number of samples and `n_features` is the number of features. y : Ignored ...
fit
python
scikit-learn/scikit-learn
sklearn/svm/_classes.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_classes.py
BSD-3-Clause
def predict(self, X): """Perform classification on samples in X. For a one-class model, +1 or -1 is returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ (n_samples_test, n_samples_train) For kernel="pr...
Perform classification on samples in X. For a one-class model, +1 or -1 is returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples_test, n_samples_train) For kernel="precomputed", the expected shape of X...
predict
python
scikit-learn/scikit-learn
sklearn/svm/_classes.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/_classes.py
BSD-3-Clause
def test_newrand_default(): """Test that bounded_rand_int_wrap without seeding respects the range Note this test should pass either if executed alone, or in conjunctions with other tests that call set_seed explicit in any order: it checks invariants on the RNG instead of specific values. """ ge...
Test that bounded_rand_int_wrap without seeding respects the range Note this test should pass either if executed alone, or in conjunctions with other tests that call set_seed explicit in any order: it checks invariants on the RNG instead of specific values.
test_newrand_default
python
scikit-learn/scikit-learn
sklearn/svm/tests/test_bounds.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/tests/test_bounds.py
BSD-3-Clause
def test_svc(X_train, y_train, X_test, kernel, sparse_container): """Check that sparse SVC gives the same result as SVC.""" X_train = sparse_container(X_train) clf = svm.SVC( gamma=1, kernel=kernel, probability=True, random_state=0, decision_function_shape="ovo", ...
Check that sparse SVC gives the same result as SVC.
test_svc
python
scikit-learn/scikit-learn
sklearn/svm/tests/test_sparse.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/tests/test_sparse.py
BSD-3-Clause
def test_svc_ovr_tie_breaking(SVCClass): """Test if predict breaks ties in OVR mode. Related issue: https://github.com/scikit-learn/scikit-learn/issues/8277 """ if SVCClass.__name__ == "NuSVC" and _IS_32BIT: # XXX: known failure to be investigated. Either the code needs to be # fixed or ...
Test if predict breaks ties in OVR mode. Related issue: https://github.com/scikit-learn/scikit-learn/issues/8277
test_svc_ovr_tie_breaking
python
scikit-learn/scikit-learn
sklearn/svm/tests/test_svm.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/tests/test_svm.py
BSD-3-Clause
def test_custom_kernel_not_array_input(Estimator): """Test using a custom kernel that is not fed with array-like for floats""" data = ["A A", "A", "B", "B B", "A B"] X = np.array([[2, 0], [1, 0], [0, 1], [0, 2], [1, 1]]) # count encoding y = np.array([1, 1, 2, 2, 1]) def string_kernel(X1, X2): ...
Test using a custom kernel that is not fed with array-like for floats
test_custom_kernel_not_array_input
python
scikit-learn/scikit-learn
sklearn/svm/tests/test_svm.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/tests/test_svm.py
BSD-3-Clause
def test_svc_raises_error_internal_representation(): """Check that SVC raises error when internal representation is altered. Non-regression test for #18891 and https://nvd.nist.gov/vuln/detail/CVE-2020-28975 """ clf = svm.SVC(kernel="linear").fit(X, Y) clf._n_support[0] = 1000000 msg = "The in...
Check that SVC raises error when internal representation is altered. Non-regression test for #18891 and https://nvd.nist.gov/vuln/detail/CVE-2020-28975
test_svc_raises_error_internal_representation
python
scikit-learn/scikit-learn
sklearn/svm/tests/test_svm.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/tests/test_svm.py
BSD-3-Clause
def test_svm_with_infinite_C(Estimator, make_dataset, C_inf, global_random_seed): """Check that we can pass `C=inf` that is equivalent to a very large C value. Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/29772 """ X, y = make_dataset(random_state=global_random_seed) ...
Check that we can pass `C=inf` that is equivalent to a very large C value. Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/29772
test_svm_with_infinite_C
python
scikit-learn/scikit-learn
sklearn/svm/tests/test_svm.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/svm/tests/test_svm.py
BSD-3-Clause
def record_metadata(obj, record_default=True, **kwargs): """Utility function to store passed metadata to a method of obj. If record_default is False, kwargs whose values are "default" are skipped. This is so that checks on keyword arguments whose default was not changed are skipped. """ stack ...
Utility function to store passed metadata to a method of obj. If record_default is False, kwargs whose values are "default" are skipped. This is so that checks on keyword arguments whose default was not changed are skipped.
record_metadata
python
scikit-learn/scikit-learn
sklearn/tests/metadata_routing_common.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/metadata_routing_common.py
BSD-3-Clause
def check_recorded_metadata(obj, method, parent, split_params=tuple(), **kwargs): """Check whether the expected metadata is passed to the object's method. Parameters ---------- obj : estimator object sub-estimator to check routed params for method : str sub-estimator's method where ...
Check whether the expected metadata is passed to the object's method. Parameters ---------- obj : estimator object sub-estimator to check routed params for method : str sub-estimator's method where metadata is routed to, or otherwise in the context of metadata routing referred t...
check_recorded_metadata
python
scikit-learn/scikit-learn
sklearn/tests/metadata_routing_common.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/metadata_routing_common.py
BSD-3-Clause
def assert_request_is_empty(metadata_request, exclude=None): """Check if a metadata request dict is empty. One can exclude a method or a list of methods from the check using the ``exclude`` parameter. If metadata_request is a MetadataRouter, then ``exclude`` can be of the form ``{"object" : [method, .....
Check if a metadata request dict is empty. One can exclude a method or a list of methods from the check using the ``exclude`` parameter. If metadata_request is a MetadataRouter, then ``exclude`` can be of the form ``{"object" : [method, ...]}``.
assert_request_is_empty
python
scikit-learn/scikit-learn
sklearn/tests/metadata_routing_common.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/metadata_routing_common.py
BSD-3-Clause
def test_clone_protocol(): """Checks that clone works with `__sklearn_clone__` protocol.""" class FrozenEstimator(BaseEstimator): def __init__(self, fitted_estimator): self.fitted_estimator = fitted_estimator def __getattr__(self, name): return getattr(self.fitted_estim...
Checks that clone works with `__sklearn_clone__` protocol.
test_clone_protocol
python
scikit-learn/scikit-learn
sklearn/tests/test_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_base.py
BSD-3-Clause
def test_n_features_in_validation(): """Check that `_check_n_features` validates data when reset=False""" est = MyEstimator() X_train = [[1, 2, 3], [4, 5, 6]] _check_n_features(est, X_train, reset=True) assert est.n_features_in_ == 3 msg = "X does not contain any features, but MyEstimator is e...
Check that `_check_n_features` validates data when reset=False
test_n_features_in_validation
python
scikit-learn/scikit-learn
sklearn/tests/test_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_base.py
BSD-3-Clause
def test_n_features_in_no_validation(): """Check that `_check_n_features` does not validate data when n_features_in_ is not defined.""" est = MyEstimator() _check_n_features(est, "invalid X", reset=True) assert not hasattr(est, "n_features_in_") # does not raise _check_n_features(est, "inv...
Check that `_check_n_features` does not validate data when n_features_in_ is not defined.
test_n_features_in_no_validation
python
scikit-learn/scikit-learn
sklearn/tests/test_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_base.py
BSD-3-Clause
def test_clone_keeps_output_config(): """Check that clone keeps the set_output config.""" ss = StandardScaler().set_output(transform="pandas") config = _get_output_config("transform", ss) ss_clone = clone(ss) config_clone = _get_output_config("transform", ss_clone) assert config == config_clon...
Check that clone keeps the set_output config.
test_clone_keeps_output_config
python
scikit-learn/scikit-learn
sklearn/tests/test_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_base.py
BSD-3-Clause
def test_estimator_empty_instance_dict(estimator): """Check that ``__getstate__`` returns an empty ``dict`` with an empty instance. Python 3.11+ changed behaviour by returning ``None`` instead of raising an ``AttributeError``. Non-regression test for gh-25188. """ state = estimator.__getstate__...
Check that ``__getstate__`` returns an empty ``dict`` with an empty instance. Python 3.11+ changed behaviour by returning ``None`` instead of raising an ``AttributeError``. Non-regression test for gh-25188.
test_estimator_empty_instance_dict
python
scikit-learn/scikit-learn
sklearn/tests/test_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_base.py
BSD-3-Clause
def test_estimator_getstate_using_slots_error_message(): """Using a `BaseEstimator` with `__slots__` is not supported.""" class WithSlots: __slots__ = ("x",) class Estimator(BaseEstimator, WithSlots): pass msg = ( "You cannot use `__slots__` in objects inheriting from " ...
Using a `BaseEstimator` with `__slots__` is not supported.
test_estimator_getstate_using_slots_error_message
python
scikit-learn/scikit-learn
sklearn/tests/test_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_base.py
BSD-3-Clause
def test_dataframe_protocol(constructor_name, minversion): """Uses the dataframe exchange protocol to get feature names.""" data = [[1, 4, 2], [3, 3, 6]] columns = ["col_0", "col_1", "col_2"] df = _convert_container( data, constructor_name, columns_name=columns, minversion=minversion ) ...
Uses the dataframe exchange protocol to get feature names.
test_dataframe_protocol
python
scikit-learn/scikit-learn
sklearn/tests/test_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_base.py
BSD-3-Clause
def test_transformer_fit_transform_with_metadata_in_transform(): """Test that having a transformer with metadata for transform raises a warning when calling fit_transform.""" class CustomTransformer(BaseEstimator, TransformerMixin): def fit(self, X, y=None, prop=None): return self ...
Test that having a transformer with metadata for transform raises a warning when calling fit_transform.
test_transformer_fit_transform_with_metadata_in_transform
python
scikit-learn/scikit-learn
sklearn/tests/test_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_base.py
BSD-3-Clause
def test_outlier_mixin_fit_predict_with_metadata_in_predict(): """Test that having an OutlierMixin with metadata for predict raises a warning when calling fit_predict.""" class CustomOutlierDetector(BaseEstimator, OutlierMixin): def fit(self, X, y=None, prop=None): return self ...
Test that having an OutlierMixin with metadata for predict raises a warning when calling fit_predict.
test_outlier_mixin_fit_predict_with_metadata_in_predict
python
scikit-learn/scikit-learn
sklearn/tests/test_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_base.py
BSD-3-Clause
def test_get_params_html(): """Check the behaviour of the `_get_params_html` method.""" est = MyEstimator(empty="test") assert est._get_params_html() == {"l1": 0, "empty": "test"} assert est._get_params_html().non_default == ("empty",)
Check the behaviour of the `_get_params_html` method.
test_get_params_html
python
scikit-learn/scikit-learn
sklearn/tests/test_base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_base.py
BSD-3-Clause
def test_sigmoid_calibration(): """Test calibration values with Platt sigmoid model""" exF = np.array([5, -4, 1.0]) exY = np.array([1, -1, -1]) # computed from my python port of the C++ code in LibSVM AB_lin_libsvm = np.array([-0.20261354391187855, 0.65236314980010512]) assert_array_almost_equal...
Test calibration values with Platt sigmoid model
test_sigmoid_calibration
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibration_nan_imputer(ensemble): """Test that calibration can accept nan""" X, y = make_classification( n_samples=10, n_features=2, n_informative=2, n_redundant=0, random_state=42 ) X[0, 0] = np.nan clf = Pipeline( [("imputer", SimpleImputer()), ("rf", RandomForestClassifi...
Test that calibration can accept nan
test_calibration_nan_imputer
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibration_accepts_ndarray(X): """Test that calibration accepts n-dimensional arrays as input""" y = [1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0] class MockTensorClassifier(ClassifierMixin, BaseEstimator): """A toy estimator that accepts tensor inputs""" def fit(self, X, y): ...
Test that calibration accepts n-dimensional arrays as input
test_calibration_accepts_ndarray
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibration_dict_pipeline(dict_data, dict_data_pipeline): """Test that calibration works in prefit pipeline with transformer `X` is not array-like, sparse matrix or dataframe at the start. See https://github.com/scikit-learn/scikit-learn/issues/8710 Also test it can predict without running in...
Test that calibration works in prefit pipeline with transformer `X` is not array-like, sparse matrix or dataframe at the start. See https://github.com/scikit-learn/scikit-learn/issues/8710 Also test it can predict without running into validation errors. See https://github.com/scikit-learn/scikit-learn...
test_calibration_dict_pipeline
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibration_curve_pos_label_error_str(dtype_y_str): """Check error message when a `pos_label` is not specified with `str` targets.""" rng = np.random.RandomState(42) y1 = np.array(["spam"] * 3 + ["eggs"] * 2, dtype=dtype_y_str) y2 = rng.randint(0, 2, size=y1.size) err_msg = ( "y_tr...
Check error message when a `pos_label` is not specified with `str` targets.
test_calibration_curve_pos_label_error_str
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibration_curve_pos_label(dtype_y_str): """Check the behaviour when passing explicitly `pos_label`.""" y_true = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1]) classes = np.array(["spam", "egg"], dtype=dtype_y_str) y_true_str = classes[y_true] y_pred = np.array([0.1, 0.2, 0.3, 0.4, 0.65, 0.7, 0.8, ...
Check the behaviour when passing explicitly `pos_label`.
test_calibration_curve_pos_label
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibration_display_kwargs(pyplot, iris_data_binary, kwargs): """Check that matplotlib aliases are handled.""" X, y = iris_data_binary lr = LogisticRegression().fit(X, y) viz = CalibrationDisplay.from_estimator(lr, X, y, **kwargs) assert viz.line_.get_color() == "red" assert viz.line_...
Check that matplotlib aliases are handled.
test_calibration_display_kwargs
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibration_display_pos_label( pyplot, iris_data_binary, pos_label, expected_pos_label ): """Check the behaviour of `pos_label` in the `CalibrationDisplay`.""" X, y = iris_data_binary lr = LogisticRegression().fit(X, y) viz = CalibrationDisplay.from_estimator(lr, X, y, pos_label=pos_label)...
Check the behaviour of `pos_label` in the `CalibrationDisplay`.
test_calibration_display_pos_label
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibrated_classifier_cv_double_sample_weights_equivalence(method, ensemble): """Check that passing repeating twice the dataset `X` is equivalent to passing a `sample_weight` with a factor 2.""" X, y = load_iris(return_X_y=True) # Scale the data to avoid any convergence issue X = StandardSc...
Check that passing repeating twice the dataset `X` is equivalent to passing a `sample_weight` with a factor 2.
test_calibrated_classifier_cv_double_sample_weights_equivalence
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibration_with_fit_params(fit_params_type, data): """Tests that fit_params are passed to the underlying base estimator. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/12384 """ X, y = data fit_params = { "a": _convert_container(y, fit_params_type...
Tests that fit_params are passed to the underlying base estimator. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/12384
test_calibration_with_fit_params
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibration_with_sample_weight_estimator(sample_weight, data): """Tests that sample_weight is passed to the underlying base estimator. """ X, y = data clf = CheckingClassifier(expected_sample_weight=True) pc_clf = CalibratedClassifierCV(clf) pc_clf.fit(X, y, sample_weight=sample_we...
Tests that sample_weight is passed to the underlying base estimator.
test_calibration_with_sample_weight_estimator
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibration_without_sample_weight_estimator(data): """Check that even if the estimator doesn't support sample_weight, fitting with sample_weight still works. There should be a warning, since the sample_weight is not passed on to the estimator. """ X, y = data sample_weight = np.one...
Check that even if the estimator doesn't support sample_weight, fitting with sample_weight still works. There should be a warning, since the sample_weight is not passed on to the estimator.
test_calibration_without_sample_weight_estimator
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibration_with_non_sample_aligned_fit_param(data): """Check that CalibratedClassifierCV does not enforce sample alignment for fit parameters.""" class TestClassifier(LogisticRegression): def fit(self, X, y, sample_weight=None, fit_param=None): assert fit_param is not None ...
Check that CalibratedClassifierCV does not enforce sample alignment for fit parameters.
test_calibration_with_non_sample_aligned_fit_param
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_calibrated_classifier_cv_works_with_large_confidence_scores( global_random_seed, ): """Test that :class:`CalibratedClassifierCV` works with large confidence scores when using the `sigmoid` method, particularly with the :class:`SGDClassifier`. Non-regression test for issue #26766. """ ...
Test that :class:`CalibratedClassifierCV` works with large confidence scores when using the `sigmoid` method, particularly with the :class:`SGDClassifier`. Non-regression test for issue #26766.
test_calibrated_classifier_cv_works_with_large_confidence_scores
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_float32_predict_proba(data, use_sample_weight, method): """Check that CalibratedClassifierCV works with float32 predict proba. Non-regression test for gh-28245 and gh-28247. """ if use_sample_weight: # Use dtype=np.float64 to check that this does not trigger an # unintentional ...
Check that CalibratedClassifierCV works with float32 predict proba. Non-regression test for gh-28245 and gh-28247.
test_float32_predict_proba
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_error_less_class_samples_than_folds(): """Check that CalibratedClassifierCV works with string targets. non-regression test for issue #28841. """ X = np.random.normal(size=(20, 3)) y = ["a"] * 10 + ["b"] * 10 CalibratedClassifierCV(cv=3).fit(X, y)
Check that CalibratedClassifierCV works with string targets. non-regression test for issue #28841.
test_error_less_class_samples_than_folds
python
scikit-learn/scikit-learn
sklearn/tests/test_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_calibration.py
BSD-3-Clause
def test_check_estimator_generate_only_deprecation(): """Check that check_estimator with generate_only=True raises a deprecation warning.""" with pytest.warns(FutureWarning, match="`generate_only` is deprecated in 1.6"): all_instance_gen_checks = check_estimator( LogisticRegression(), ge...
Check that check_estimator with generate_only=True raises a deprecation warning.
test_check_estimator_generate_only_deprecation
python
scikit-learn/scikit-learn
sklearn/tests/test_common.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_common.py
BSD-3-Clause
def set_assume_finite(assume_finite, sleep_duration): """Return the value of assume_finite after waiting `sleep_duration`.""" with config_context(assume_finite=assume_finite): time.sleep(sleep_duration) return get_config()["assume_finite"]
Return the value of assume_finite after waiting `sleep_duration`.
set_assume_finite
python
scikit-learn/scikit-learn
sklearn/tests/test_config.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_config.py
BSD-3-Clause
def test_config_threadsafe_joblib(backend): """Test that the global config is threadsafe with all joblib backends. Two jobs are spawned and sets assume_finite to two different values. When the job with a duration 0.1s completes, the assume_finite value should be the same as the value passed to the funct...
Test that the global config is threadsafe with all joblib backends. Two jobs are spawned and sets assume_finite to two different values. When the job with a duration 0.1s completes, the assume_finite value should be the same as the value passed to the function. In other words, it is not influenced by th...
test_config_threadsafe_joblib
python
scikit-learn/scikit-learn
sklearn/tests/test_config.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_config.py
BSD-3-Clause
def test_config_threadsafe(): """Uses threads directly to test that the global config does not change between threads. Same test as `test_config_threadsafe_joblib` but with `ThreadPoolExecutor`.""" assume_finites = [False, True, False, True] sleep_durations = [0.1, 0.2, 0.1, 0.2] with ThreadPo...
Uses threads directly to test that the global config does not change between threads. Same test as `test_config_threadsafe_joblib` but with `ThreadPoolExecutor`.
test_config_threadsafe
python
scikit-learn/scikit-learn
sklearn/tests/test_config.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_config.py
BSD-3-Clause
def test_config_array_api_dispatch_error_scipy(monkeypatch): """Check error when SciPy is too old""" monkeypatch.setattr(sklearn.utils._array_api.scipy, "__version__", "1.13.0") with pytest.raises(ImportError, match="SciPy must be 1.14.0 or newer"): with config_context(array_api_dispatch=True): ...
Check error when SciPy is too old
test_config_array_api_dispatch_error_scipy
python
scikit-learn/scikit-learn
sklearn/tests/test_config.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_config.py
BSD-3-Clause
def generate_dataset(n_samples, centers, covariances, random_state=None): """Generate a multivariate normal data given some centers and covariances""" rng = check_random_state(random_state) X = np.vstack( [ rng.multivariate_normal(mean, cov, size=n_samples // ...
Generate a multivariate normal data given some centers and covariances
generate_dataset
python
scikit-learn/scikit-learn
sklearn/tests/test_discriminant_analysis.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_discriminant_analysis.py
BSD-3-Clause
def test_qda_prior_type(priors_type): """Check that priors accept array-like.""" priors = [0.5, 0.5] clf = QuadraticDiscriminantAnalysis( priors=_convert_container([0.5, 0.5], priors_type) ).fit(X6, y6) assert isinstance(clf.priors_, np.ndarray) assert_array_equal(clf.priors_, priors)
Check that priors accept array-like.
test_qda_prior_type
python
scikit-learn/scikit-learn
sklearn/tests/test_discriminant_analysis.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_discriminant_analysis.py
BSD-3-Clause
def test_qda_prior_copy(): """Check that altering `priors` without `fit` doesn't change `priors_`""" priors = np.array([0.5, 0.5]) qda = QuadraticDiscriminantAnalysis(priors=priors).fit(X, y) # we expect the following assert_array_equal(qda.priors_, qda.priors) # altering `priors` without `fit...
Check that altering `priors` without `fit` doesn't change `priors_`
test_qda_prior_copy
python
scikit-learn/scikit-learn
sklearn/tests/test_discriminant_analysis.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_discriminant_analysis.py
BSD-3-Clause
def test_raises_value_error_on_same_number_of_classes_and_samples(solver): """ Tests that if the number of samples equals the number of classes, a ValueError is raised. """ X = np.array([[0.5, 0.6], [0.6, 0.5]]) y = np.array(["a", "b"]) clf = LinearDiscriminantAnalysis(solver=solver) wit...
Tests that if the number of samples equals the number of classes, a ValueError is raised.
test_raises_value_error_on_same_number_of_classes_and_samples
python
scikit-learn/scikit-learn
sklearn/tests/test_discriminant_analysis.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_discriminant_analysis.py
BSD-3-Clause
def test_get_feature_names_out(): """Check get_feature_names_out uses class name as prefix.""" est = LinearDiscriminantAnalysis().fit(X, y) names_out = est.get_feature_names_out() class_name_lower = "LinearDiscriminantAnalysis".lower() expected_names_out = np.array( [ f"{class_...
Check get_feature_names_out uses class name as prefix.
test_get_feature_names_out
python
scikit-learn/scikit-learn
sklearn/tests/test_discriminant_analysis.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_discriminant_analysis.py
BSD-3-Clause
def filter_errors(errors, method, Klass=None): """ Ignore some errors based on the method type. These rules are specific for scikit-learn.""" for code, message in errors: # We ignore following error code, # - RT02: The first line of the Returns section # should contain only ...
Ignore some errors based on the method type. These rules are specific for scikit-learn.
filter_errors
python
scikit-learn/scikit-learn
sklearn/tests/test_docstrings.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_docstrings.py
BSD-3-Clause
def repr_errors(res, Klass=None, method: Optional[str] = None) -> str: """Pretty print original docstring and the obtained errors Parameters ---------- res : dict result of numpydoc.validate.validate Klass : {Estimator, Display, None} estimator object or None method : str ...
Pretty print original docstring and the obtained errors Parameters ---------- res : dict result of numpydoc.validate.validate Klass : {Estimator, Display, None} estimator object or None method : str if estimator is not None, either the method name or None. Returns -...
repr_errors
python
scikit-learn/scikit-learn
sklearn/tests/test_docstrings.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_docstrings.py
BSD-3-Clause
def _get_all_fitted_attributes(estimator): "Get all the fitted attributes of an estimator including properties" # attributes fit_attr = list(estimator.__dict__.keys()) # properties with warnings.catch_warnings(): warnings.filterwarnings("error", category=FutureWarning) for name in ...
Get all the fitted attributes of an estimator including properties
_get_all_fitted_attributes
python
scikit-learn/scikit-learn
sklearn/tests/test_docstring_parameters.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_docstring_parameters.py
BSD-3-Clause
def test_isotonic_regression_ties_secondary_(): """ Test isotonic regression fit, transform and fit_transform against the "secondary" ties method and "pituitary" data from R "isotone" package, as detailed in: J. d. Leeuw, K. Hornik, P. Mair, Isotone Optimization in R: Pool-Adjacent-Violators Algo...
Test isotonic regression fit, transform and fit_transform against the "secondary" ties method and "pituitary" data from R "isotone" package, as detailed in: J. d. Leeuw, K. Hornik, P. Mair, Isotone Optimization in R: Pool-Adjacent-Violators Algorithm (PAVA) and Active Set Methods Set values...
test_isotonic_regression_ties_secondary_
python
scikit-learn/scikit-learn
sklearn/tests/test_isotonic.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_isotonic.py
BSD-3-Clause
def test_isotonic_regression_with_ties_in_differently_sized_groups(): """ Non-regression test to handle issue 9432: https://github.com/scikit-learn/scikit-learn/issues/9432 Compare against output in R: > library("isotone") > x <- c(0, 1, 1, 2, 3, 4) > y <- c(0, 0, 1, 0, 0, 1) > res1 <- ...
Non-regression test to handle issue 9432: https://github.com/scikit-learn/scikit-learn/issues/9432 Compare against output in R: > library("isotone") > x <- c(0, 1, 1, 2, 3, 4) > y <- c(0, 0, 1, 0, 0, 1) > res1 <- gpava(x, y, ties="secondary") > res1$x `isotone` version: 1.1-0, 201...
test_isotonic_regression_with_ties_in_differently_sized_groups
python
scikit-learn/scikit-learn
sklearn/tests/test_isotonic.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_isotonic.py
BSD-3-Clause
def test_isotonic_regression_sample_weight_not_overwritten(): """Check that calling fitting function of isotonic regression will not overwrite `sample_weight`. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/20508 """ X, y = make_regression(n_samples=10, n_features=1...
Check that calling fitting function of isotonic regression will not overwrite `sample_weight`. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/20508
test_isotonic_regression_sample_weight_not_overwritten
python
scikit-learn/scikit-learn
sklearn/tests/test_isotonic.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_isotonic.py
BSD-3-Clause
def test_isotonic_regression_output_predict(): """Check that `predict` does return the expected output type. We need to check that `transform` will output a DataFrame and a NumPy array when we set `transform_output` to `pandas`. Non-regression test for: https://github.com/scikit-learn/scikit-learn...
Check that `predict` does return the expected output type. We need to check that `transform` will output a DataFrame and a NumPy array when we set `transform_output` to `pandas`. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/25499
test_isotonic_regression_output_predict
python
scikit-learn/scikit-learn
sklearn/tests/test_isotonic.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_isotonic.py
BSD-3-Clause
def test_polynomial_count_sketch_dense_sparse(gamma, degree, coef0, csr_container): """Check that PolynomialCountSketch results are the same for dense and sparse input. """ ps_dense = PolynomialCountSketch( n_components=500, gamma=gamma, degree=degree, coef0=coef0, random_state=42 ) Xt_d...
Check that PolynomialCountSketch results are the same for dense and sparse input.
test_polynomial_count_sketch_dense_sparse
python
scikit-learn/scikit-learn
sklearn/tests/test_kernel_approximation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py
BSD-3-Clause
def test_additive_chi2_sampler_sample_steps(method, sample_steps): """Check that the input sample step doesn't raise an error and that sample interval doesn't change after fit. """ transformer = AdditiveChi2Sampler(sample_steps=sample_steps) getattr(transformer, method)(X) sample_interval = 0.5...
Check that the input sample step doesn't raise an error and that sample interval doesn't change after fit.
test_additive_chi2_sampler_sample_steps
python
scikit-learn/scikit-learn
sklearn/tests/test_kernel_approximation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py
BSD-3-Clause
def test_additive_chi2_sampler_wrong_sample_steps(method): """Check that we raise a ValueError on invalid sample_steps""" transformer = AdditiveChi2Sampler(sample_steps=4) msg = re.escape( "If sample_steps is not in [1, 2, 3], you need to provide sample_interval" ) with pytest.raises(ValueEr...
Check that we raise a ValueError on invalid sample_steps
test_additive_chi2_sampler_wrong_sample_steps
python
scikit-learn/scikit-learn
sklearn/tests/test_kernel_approximation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py
BSD-3-Clause
def test_rbf_sampler_fitted_attributes_dtype(global_dtype): """Check that the fitted attributes are stored accordingly to the data type of X.""" rbf = RBFSampler() X = np.array([[1, 2], [3, 4], [5, 6]], dtype=global_dtype) rbf.fit(X) assert rbf.random_offset_.dtype == global_dtype assert ...
Check that the fitted attributes are stored accordingly to the data type of X.
test_rbf_sampler_fitted_attributes_dtype
python
scikit-learn/scikit-learn
sklearn/tests/test_kernel_approximation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py
BSD-3-Clause
def test_rbf_sampler_dtype_equivalence(): """Check the equivalence of the results with 32 and 64 bits input.""" rbf32 = RBFSampler(random_state=42) X32 = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32) rbf32.fit(X32) rbf64 = RBFSampler(random_state=42) X64 = np.array([[1, 2], [3, 4], [5, 6...
Check the equivalence of the results with 32 and 64 bits input.
test_rbf_sampler_dtype_equivalence
python
scikit-learn/scikit-learn
sklearn/tests/test_kernel_approximation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py
BSD-3-Clause
def test_rbf_sampler_gamma_scale(): """Check the inner value computed when `gamma='scale'`.""" X, y = [[0.0], [1.0]], [0, 1] rbf = RBFSampler(gamma="scale") rbf.fit(X, y) assert rbf._gamma == pytest.approx(4)
Check the inner value computed when `gamma='scale'`.
test_rbf_sampler_gamma_scale
python
scikit-learn/scikit-learn
sklearn/tests/test_kernel_approximation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py
BSD-3-Clause
def test_skewed_chi2_sampler_fitted_attributes_dtype(global_dtype): """Check that the fitted attributes are stored accordingly to the data type of X.""" skewed_chi2_sampler = SkewedChi2Sampler() X = np.array([[1, 2], [3, 4], [5, 6]], dtype=global_dtype) skewed_chi2_sampler.fit(X) assert skewe...
Check that the fitted attributes are stored accordingly to the data type of X.
test_skewed_chi2_sampler_fitted_attributes_dtype
python
scikit-learn/scikit-learn
sklearn/tests/test_kernel_approximation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py
BSD-3-Clause
def test_skewed_chi2_sampler_dtype_equivalence(): """Check the equivalence of the results with 32 and 64 bits input.""" skewed_chi2_sampler_32 = SkewedChi2Sampler(random_state=42) X_32 = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32) skewed_chi2_sampler_32.fit(X_32) skewed_chi2_sampler_64 = S...
Check the equivalence of the results with 32 and 64 bits input.
test_skewed_chi2_sampler_dtype_equivalence
python
scikit-learn/scikit-learn
sklearn/tests/test_kernel_approximation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py
BSD-3-Clause
def logging_histogram_kernel(x, y, log): """Histogram kernel that writes to a log.""" log.append(1) return np.minimum(x, y).sum()
Histogram kernel that writes to a log.
logging_histogram_kernel
python
scikit-learn/scikit-learn
sklearn/tests/test_kernel_approximation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py
BSD-3-Clause
def test_nystroem_component_indices(): """Check that `component_indices_` corresponds to the subset of training points used to construct the feature map. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/20474 """ X, _ = make_classification(n_samples=100, n_features=20...
Check that `component_indices_` corresponds to the subset of training points used to construct the feature map. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/20474
test_nystroem_component_indices
python
scikit-learn/scikit-learn
sklearn/tests/test_kernel_approximation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_kernel_approximation.py
BSD-3-Clause
def test_estimator_puts_self_in_registry(estimator): """Check that an estimator puts itself in the registry upon fit.""" estimator.fit(X, y) assert estimator in estimator.registry
Check that an estimator puts itself in the registry upon fit.
test_estimator_puts_self_in_registry
python
scikit-learn/scikit-learn
sklearn/tests/test_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py
BSD-3-Clause
def test_default_request_override(): """Test that default requests are correctly overridden regardless of the ASCII order of the class names, hence testing small and capital letter class name starts. Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28430 """ class Base(Ba...
Test that default requests are correctly overridden regardless of the ASCII order of the class names, hence testing small and capital letter class name starts. Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28430
test_default_request_override
python
scikit-learn/scikit-learn
sklearn/tests/test_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py
BSD-3-Clause
def test_removing_non_existing_param_raises(): """Test that removing a metadata using UNUSED which doesn't exist raises.""" class InvalidRequestRemoval(BaseEstimator): # `fit` (in this class or a parent) requests `prop`, but we don't want # it requested at all. __metadata_request__fit =...
Test that removing a metadata using UNUSED which doesn't exist raises.
test_removing_non_existing_param_raises
python
scikit-learn/scikit-learn
sklearn/tests/test_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py
BSD-3-Clause
def test_metadata_request_consumes_method(): """Test that MetadataRequest().consumes() method works as expected.""" request = MetadataRouter(owner="test") assert request.consumes(method="fit", params={"foo"}) == set() request = MetadataRequest(owner="test") request.fit.add_request(param="foo", alia...
Test that MetadataRequest().consumes() method works as expected.
test_metadata_request_consumes_method
python
scikit-learn/scikit-learn
sklearn/tests/test_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py
BSD-3-Clause
def test_metadata_router_consumes_method(): """Test that MetadataRouter().consumes method works as expected.""" # having it here instead of parametrizing the test since `set_fit_request` # is not available while collecting the tests. cases = [ ( WeightedMetaRegressor( ...
Test that MetadataRouter().consumes method works as expected.
test_metadata_router_consumes_method
python
scikit-learn/scikit-learn
sklearn/tests/test_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py
BSD-3-Clause
def test_no_feature_flag_raises_error(): """Test that when feature flag disabled, set_{method}_requests raises.""" with config_context(enable_metadata_routing=False): with pytest.raises(RuntimeError, match="This method is only available"): ConsumingClassifier().set_fit_request(sample_weight=...
Test that when feature flag disabled, set_{method}_requests raises.
test_no_feature_flag_raises_error
python
scikit-learn/scikit-learn
sklearn/tests/test_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py
BSD-3-Clause
def test_no_metadata_always_works(): """Test that when no metadata is passed, having a meta-estimator which does not yet support metadata routing works. Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28246 """ class Estimator(_RoutingNotSupportedMixin, BaseEstimator): ...
Test that when no metadata is passed, having a meta-estimator which does not yet support metadata routing works. Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28246
test_no_metadata_always_works
python
scikit-learn/scikit-learn
sklearn/tests/test_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py
BSD-3-Clause
def test_unsetmetadatapassederror_correct(): """Test that UnsetMetadataPassedError raises the correct error message when set_{method}_request is not set in nested cases.""" weighted_meta = WeightedMetaClassifier(estimator=ConsumingClassifier()) pipe = SimplePipeline([weighted_meta]) msg = re.escape(...
Test that UnsetMetadataPassedError raises the correct error message when set_{method}_request is not set in nested cases.
test_unsetmetadatapassederror_correct
python
scikit-learn/scikit-learn
sklearn/tests/test_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py
BSD-3-Clause
def test_unsetmetadatapassederror_correct_for_composite_methods(): """Test that UnsetMetadataPassedError raises the correct error message when composite metadata request methods are not set in nested cases.""" consuming_transformer = ConsumingTransformer() pipe = Pipeline([("consuming_transformer", cons...
Test that UnsetMetadataPassedError raises the correct error message when composite metadata request methods are not set in nested cases.
test_unsetmetadatapassederror_correct_for_composite_methods
python
scikit-learn/scikit-learn
sklearn/tests/test_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py
BSD-3-Clause
def test_unbound_set_methods_work(): """Tests that if the set_{method}_request is unbound, it still works. Also test that passing positional arguments to the set_{method}_request fails with the right TypeError message. Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28632 ...
Tests that if the set_{method}_request is unbound, it still works. Also test that passing positional arguments to the set_{method}_request fails with the right TypeError message. Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28632
test_unbound_set_methods_work
python
scikit-learn/scikit-learn
sklearn/tests/test_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metadata_routing.py
BSD-3-Clause
def _get_instance_with_pipeline(meta_estimator, init_params): """Given a single meta-estimator instance, generate an instance with a pipeline""" if {"estimator", "base_estimator", "regressor"} & init_params: if is_regressor(meta_estimator): estimator = make_pipeline(TfidfVectorizer(), Ridge(...
Given a single meta-estimator instance, generate an instance with a pipeline
_get_instance_with_pipeline
python
scikit-learn/scikit-learn
sklearn/tests/test_metaestimators.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators.py
BSD-3-Clause
def _generate_meta_estimator_instances_with_pipeline(): """Generate instances of meta-estimators fed with a pipeline Are considered meta-estimators all estimators accepting one of "estimator", "base_estimator" or "estimators". """ print("estimators: ", len(all_estimators())) for _, Estimator in...
Generate instances of meta-estimators fed with a pipeline Are considered meta-estimators all estimators accepting one of "estimator", "base_estimator" or "estimators".
_generate_meta_estimator_instances_with_pipeline
python
scikit-learn/scikit-learn
sklearn/tests/test_metaestimators.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators.py
BSD-3-Clause
def get_init_args(metaestimator_info, sub_estimator_consumes): """Get the init args for a metaestimator This is a helper function to get the init args for a metaestimator from the METAESTIMATORS list. It returns an empty dict if no init args are required. Parameters ---------- metaestimato...
Get the init args for a metaestimator This is a helper function to get the init args for a metaestimator from the METAESTIMATORS list. It returns an empty dict if no init args are required. Parameters ---------- metaestimator_info : dict The metaestimator info from METAESTIMATORS ...
get_init_args
python
scikit-learn/scikit-learn
sklearn/tests/test_metaestimators_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py
BSD-3-Clause
def set_requests(obj, *, method_mapping, methods, metadata_name, value=True): """Call `set_{method}_request` on a list of methods from the sub-estimator. Parameters ---------- obj : BaseEstimator The object for which `set_{method}_request` methods are called. method_mapping : dict ...
Call `set_{method}_request` on a list of methods from the sub-estimator. Parameters ---------- obj : BaseEstimator The object for which `set_{method}_request` methods are called. method_mapping : dict The method mapping in the form of `{caller: [callee, ...]}`. If a "caller" is...
set_requests
python
scikit-learn/scikit-learn
sklearn/tests/test_metaestimators_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py
BSD-3-Clause
def test_unsupported_estimators_fit_with_metadata(estimator): """Test that fit raises NotImplementedError when metadata routing is enabled and a metadata is passed on meta-estimators for which we haven't implemented routing yet.""" with pytest.raises(NotImplementedError): try: estima...
Test that fit raises NotImplementedError when metadata routing is enabled and a metadata is passed on meta-estimators for which we haven't implemented routing yet.
test_unsupported_estimators_fit_with_metadata
python
scikit-learn/scikit-learn
sklearn/tests/test_metaestimators_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py
BSD-3-Clause
def test_metadata_is_routed_correctly_to_scorer(metaestimator): """Test that any requested metadata is correctly routed to the underlying scorers in CV estimators. """ if "scorer_name" not in metaestimator: # This test only makes sense for CV estimators return metaestimator_class = ...
Test that any requested metadata is correctly routed to the underlying scorers in CV estimators.
test_metadata_is_routed_correctly_to_scorer
python
scikit-learn/scikit-learn
sklearn/tests/test_metaestimators_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py
BSD-3-Clause
def test_metadata_is_routed_correctly_to_splitter(metaestimator): """Test that any requested metadata is correctly routed to the underlying splitters in CV estimators. """ if "cv_routing_methods" not in metaestimator: # This test is only for metaestimators accepting a CV splitter return ...
Test that any requested metadata is correctly routed to the underlying splitters in CV estimators.
test_metadata_is_routed_correctly_to_splitter
python
scikit-learn/scikit-learn
sklearn/tests/test_metaestimators_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py
BSD-3-Clause
def test_metadata_routed_to_group_splitter(metaestimator): """Test that groups are routed correctly if group splitter of CV estimator is used within cross_validate. Regression test for issue described in PR #29634 to test that `ValueError: The 'groups' parameter should not be None.` is not raised.""" i...
Test that groups are routed correctly if group splitter of CV estimator is used within cross_validate. Regression test for issue described in PR #29634 to test that `ValueError: The 'groups' parameter should not be None.` is not raised.
test_metadata_routed_to_group_splitter
python
scikit-learn/scikit-learn
sklearn/tests/test_metaestimators_metadata_routing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_metaestimators_metadata_routing.py
BSD-3-Clause
def test_min_dependencies_pyproject_toml(pyproject_section, min_dependencies_tag): """Check versions in pyproject.toml is consistent with _min_dependencies.""" # NumPy is more complex because build-time (>=1.25) and run-time (>=1.19.5) # requirement currently don't match skip_version_check_for = ["numpy...
Check versions in pyproject.toml is consistent with _min_dependencies.
test_min_dependencies_pyproject_toml
python
scikit-learn/scikit-learn
sklearn/tests/test_min_dependencies_readme.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_min_dependencies_readme.py
BSD-3-Clause
def test_ovr_single_label_predict_proba_zero(): """Check that predic_proba returns all zeros when the base estimator never predicts the positive class. """ class NaiveBinaryClassifier(BaseEstimator, ClassifierMixin): def fit(self, X, y): self.classes_ = np.unique(y) retu...
Check that predic_proba returns all zeros when the base estimator never predicts the positive class.
test_ovr_single_label_predict_proba_zero
python
scikit-learn/scikit-learn
sklearn/tests/test_multiclass.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multiclass.py
BSD-3-Clause
def test_pairwise_n_features_in(): """Check the n_features_in_ attributes of the meta and base estimators When the training data is a regular design matrix, everything is intuitive. However, when the training data is a precomputed kernel matrix, the multiclass strategy can resample the kernel matrix of...
Check the n_features_in_ attributes of the meta and base estimators When the training data is a regular design matrix, everything is intuitive. However, when the training data is a precomputed kernel matrix, the multiclass strategy can resample the kernel matrix of the underlying base estimator both ro...
test_pairwise_n_features_in
python
scikit-learn/scikit-learn
sklearn/tests/test_multiclass.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multiclass.py
BSD-3-Clause
def test_constant_int_target(make_y): """Check that constant y target does not raise. Non-regression test for #21869 """ X = np.ones((10, 2)) y = make_y((10, 1), dtype=np.int32) ovr = OneVsRestClassifier(LogisticRegression()) ovr.fit(X, y) y_pred = ovr.predict_proba(X) expected = n...
Check that constant y target does not raise. Non-regression test for #21869
test_constant_int_target
python
scikit-learn/scikit-learn
sklearn/tests/test_multiclass.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tests/test_multiclass.py
BSD-3-Clause