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 func(*args, **kw): """Updates the request for provided parameters This docstring is overwritten below. See REQUESTER_DOC for expected functionality """ if not _routing_enabled(): raise RuntimeError( "This method is only available when metadata routing is enabled." " You can enable it using" " sklearn.set_config(enable_metadata_routing=True)." ) if self.validate_keys and (set(kw) - set(self.keys)): raise TypeError( f"Unexpected args: {set(kw) - set(self.keys)} in {self.name}. " f"Accepted arguments are: {set(self.keys)}" ) # This makes it possible to use the decorated method as an unbound method, # for instance when monkeypatching. # https://github.com/scikit-learn/scikit-learn/issues/28632 if instance is None: _instance = args[0] args = args[1:] else: _instance = instance # Replicating python's behavior when positional args are given other than # `self`, and `self` is only allowed if this method is unbound. if args: raise TypeError( f"set_{self.name}_request() takes 0 positional argument but" f" {len(args)} were given" ) requests = _instance._get_metadata_request() method_metadata_request = getattr(requests, self.name) for prop, alias in kw.items(): if alias is not UNCHANGED: method_metadata_request.add_request(param=prop, alias=alias) _instance._metadata_request = requests return _instance
Updates the request for provided parameters This docstring is overwritten below. See REQUESTER_DOC for expected functionality
func
python
scikit-learn/scikit-learn
sklearn/utils/_metadata_requests.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py
BSD-3-Clause
def __init_subclass__(cls, **kwargs): """Set the ``set_{method}_request`` methods. This uses PEP-487 [1]_ to set the ``set_{method}_request`` methods. It looks for the information available in the set default values which are set using ``__metadata_request__*`` class attributes, or inferred from method signatures. The ``__metadata_request__*`` class attributes are used when a method does not explicitly accept a metadata through its arguments or if the developer would like to specify a request value for those metadata which are different from the default ``None``. References ---------- .. [1] https://www.python.org/dev/peps/pep-0487 """ try: requests = cls._get_default_requests() except Exception: # if there are any issues in the default values, it will be raised # when ``get_metadata_routing`` is called. Here we are going to # ignore all the issues such as bad defaults etc. super().__init_subclass__(**kwargs) return for method in SIMPLE_METHODS: mmr = getattr(requests, method) # set ``set_{method}_request`` methods if not len(mmr.requests): continue setattr( cls, f"set_{method}_request", RequestMethod(method, sorted(mmr.requests.keys())), ) super().__init_subclass__(**kwargs)
Set the ``set_{method}_request`` methods. This uses PEP-487 [1]_ to set the ``set_{method}_request`` methods. It looks for the information available in the set default values which are set using ``__metadata_request__*`` class attributes, or inferred from method signatures. The ``__metadata_request__*`` class attributes are used when a method does not explicitly accept a metadata through its arguments or if the developer would like to specify a request value for those metadata which are different from the default ``None``. References ---------- .. [1] https://www.python.org/dev/peps/pep-0487
__init_subclass__
python
scikit-learn/scikit-learn
sklearn/utils/_metadata_requests.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py
BSD-3-Clause
def _build_request_for_signature(cls, router, method): """Build the `MethodMetadataRequest` for a method using its signature. This method takes all arguments from the method signature and uses ``None`` as their default request value, except ``X``, ``y``, ``Y``, ``Xt``, ``yt``, ``*args``, and ``**kwargs``. Parameters ---------- router : MetadataRequest The parent object for the created `MethodMetadataRequest`. method : str The name of the method. Returns ------- method_request : MethodMetadataRequest The prepared request using the method's signature. """ mmr = MethodMetadataRequest(owner=cls.__name__, method=method) # Here we use `isfunction` instead of `ismethod` because calling `getattr` # on a class instead of an instance returns an unbound function. if not hasattr(cls, method) or not inspect.isfunction(getattr(cls, method)): return mmr # ignore the first parameter of the method, which is usually "self" params = list(inspect.signature(getattr(cls, method)).parameters.items())[1:] for pname, param in params: if pname in {"X", "y", "Y", "Xt", "yt"}: continue if param.kind in {param.VAR_POSITIONAL, param.VAR_KEYWORD}: continue mmr.add_request( param=pname, alias=None, ) return mmr
Build the `MethodMetadataRequest` for a method using its signature. This method takes all arguments from the method signature and uses ``None`` as their default request value, except ``X``, ``y``, ``Y``, ``Xt``, ``yt``, ``*args``, and ``**kwargs``. Parameters ---------- router : MetadataRequest The parent object for the created `MethodMetadataRequest`. method : str The name of the method. Returns ------- method_request : MethodMetadataRequest The prepared request using the method's signature.
_build_request_for_signature
python
scikit-learn/scikit-learn
sklearn/utils/_metadata_requests.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py
BSD-3-Clause
def _get_default_requests(cls): """Collect default request values. This method combines the information present in ``__metadata_request__*`` class attributes, as well as determining request keys from method signatures. """ requests = MetadataRequest(owner=cls.__name__) for method in SIMPLE_METHODS: setattr( requests, method, cls._build_request_for_signature(router=requests, method=method), ) # Then overwrite those defaults with the ones provided in # __metadata_request__* attributes. Defaults set in # __metadata_request__* attributes take precedence over signature # sniffing. # need to go through the MRO since this is a class attribute and # ``vars`` doesn't report the parent class attributes. We go through # the reverse of the MRO so that child classes have precedence over # their parents. substr = "__metadata_request__" for base_class in reversed(inspect.getmro(cls)): for attr, value in vars(base_class).items(): if substr not in attr: continue # we don't check for attr.startswith() since python prefixes attrs # starting with __ with the `_ClassName`. method = attr[attr.index(substr) + len(substr) :] for prop, alias in value.items(): # Here we add request values specified via those class attributes # to the `MetadataRequest` object. Adding a request which already # exists will override the previous one. Since we go through the # MRO in reverse order, the one specified by the lowest most classes # in the inheritance tree are the ones which take effect. getattr(requests, method).add_request(param=prop, alias=alias) return requests
Collect default request values. This method combines the information present in ``__metadata_request__*`` class attributes, as well as determining request keys from method signatures.
_get_default_requests
python
scikit-learn/scikit-learn
sklearn/utils/_metadata_requests.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py
BSD-3-Clause
def _get_metadata_request(self): """Get requested data properties. Please check :ref:`User Guide <metadata_routing>` on how the routing mechanism works. Returns ------- request : MetadataRequest A :class:`~sklearn.utils.metadata_routing.MetadataRequest` instance. """ if hasattr(self, "_metadata_request"): requests = get_routing_for_object(self._metadata_request) else: requests = self._get_default_requests() return requests
Get requested data properties. Please check :ref:`User Guide <metadata_routing>` on how the routing mechanism works. Returns ------- request : MetadataRequest A :class:`~sklearn.utils.metadata_routing.MetadataRequest` instance.
_get_metadata_request
python
scikit-learn/scikit-learn
sklearn/utils/_metadata_requests.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py
BSD-3-Clause
def process_routing(_obj, _method, /, **kwargs): """Validate and route input parameters. This function is used inside a router's method, e.g. :term:`fit`, to validate the metadata and handle the routing. Assuming this signature of a router's fit method: ``fit(self, X, y, sample_weight=None, **fit_params)``, a call to this function would be: ``process_routing(self, "fit", sample_weight=sample_weight, **fit_params)``. Note that if routing is not enabled and ``kwargs`` is empty, then it returns an empty routing where ``process_routing(...).ANYTHING.ANY_METHOD`` is always an empty dictionary. .. versionadded:: 1.3 Parameters ---------- _obj : object An object implementing ``get_metadata_routing``. Typically a meta-estimator. _method : str The name of the router's method in which this function is called. **kwargs : dict Metadata to be routed. Returns ------- routed_params : Bunch A :class:`~utils.Bunch` of the form ``{"object_name": {"method_name": {params: value}}}`` which can be used to pass the required metadata to A :class:`~sklearn.utils.Bunch` of the form ``{"object_name": {"method_name": {params: value}}}`` which can be used to pass the required metadata to corresponding methods or corresponding child objects. The object names are those defined in `obj.get_metadata_routing()`. """ if not kwargs: # If routing is not enabled and kwargs are empty, then we don't have to # try doing any routing, we can simply return a structure which returns # an empty dict on routed_params.ANYTHING.ANY_METHOD. class EmptyRequest: def get(self, name, default=None): return Bunch(**{method: dict() for method in METHODS}) def __getitem__(self, name): return Bunch(**{method: dict() for method in METHODS}) def __getattr__(self, name): return Bunch(**{method: dict() for method in METHODS}) return EmptyRequest() if not (hasattr(_obj, "get_metadata_routing") or isinstance(_obj, MetadataRouter)): raise AttributeError( f"The given object ({_obj.__class__.__name__!r}) needs to either" " implement the routing method `get_metadata_routing` or be a" " `MetadataRouter` instance." ) if _method not in METHODS: raise TypeError( f"Can only route and process input on these methods: {METHODS}, " f"while the passed method is: {_method}." ) request_routing = get_routing_for_object(_obj) request_routing.validate_metadata(params=kwargs, method=_method) routed_params = request_routing.route_params(params=kwargs, caller=_method) return routed_params
Validate and route input parameters. This function is used inside a router's method, e.g. :term:`fit`, to validate the metadata and handle the routing. Assuming this signature of a router's fit method: ``fit(self, X, y, sample_weight=None, **fit_params)``, a call to this function would be: ``process_routing(self, "fit", sample_weight=sample_weight, **fit_params)``. Note that if routing is not enabled and ``kwargs`` is empty, then it returns an empty routing where ``process_routing(...).ANYTHING.ANY_METHOD`` is always an empty dictionary. .. versionadded:: 1.3 Parameters ---------- _obj : object An object implementing ``get_metadata_routing``. Typically a meta-estimator. _method : str The name of the router's method in which this function is called. **kwargs : dict Metadata to be routed. Returns ------- routed_params : Bunch A :class:`~utils.Bunch` of the form ``{"object_name": {"method_name": {params: value}}}`` which can be used to pass the required metadata to A :class:`~sklearn.utils.Bunch` of the form ``{"object_name": {"method_name": {params: value}}}`` which can be used to pass the required metadata to corresponding methods or corresponding child objects. The object names are those defined in `obj.get_metadata_routing()`.
process_routing
python
scikit-learn/scikit-learn
sklearn/utils/_metadata_requests.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_metadata_requests.py
BSD-3-Clause
def is_scalar_nan(x): """Test if x is NaN. This function is meant to overcome the issue that np.isnan does not allow non-numerical types as input, and that np.nan is not float('nan'). Parameters ---------- x : any type Any scalar value. Returns ------- bool Returns true if x is NaN, and false otherwise. Examples -------- >>> import numpy as np >>> from sklearn.utils._missing import is_scalar_nan >>> is_scalar_nan(np.nan) True >>> is_scalar_nan(float("nan")) True >>> is_scalar_nan(None) False >>> is_scalar_nan("") False >>> is_scalar_nan([np.nan]) False """ return ( not isinstance(x, numbers.Integral) and isinstance(x, numbers.Real) and math.isnan(x) )
Test if x is NaN. This function is meant to overcome the issue that np.isnan does not allow non-numerical types as input, and that np.nan is not float('nan'). Parameters ---------- x : any type Any scalar value. Returns ------- bool Returns true if x is NaN, and false otherwise. Examples -------- >>> import numpy as np >>> from sklearn.utils._missing import is_scalar_nan >>> is_scalar_nan(np.nan) True >>> is_scalar_nan(float("nan")) True >>> is_scalar_nan(None) False >>> is_scalar_nan("") False >>> is_scalar_nan([np.nan]) False
is_scalar_nan
python
scikit-learn/scikit-learn
sklearn/utils/_missing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_missing.py
BSD-3-Clause
def is_pandas_na(x): """Test if x is pandas.NA. We intentionally do not use this function to return `True` for `pd.NA` in `is_scalar_nan`, because estimators that support `pd.NA` are the exception rather than the rule at the moment. When `pd.NA` is more universally supported, we may reconsider this decision. Parameters ---------- x : any type Returns ------- boolean """ with suppress(ImportError): from pandas import NA return x is NA return False
Test if x is pandas.NA. We intentionally do not use this function to return `True` for `pd.NA` in `is_scalar_nan`, because estimators that support `pd.NA` are the exception rather than the rule at the moment. When `pd.NA` is more universally supported, we may reconsider this decision. Parameters ---------- x : any type Returns ------- boolean
is_pandas_na
python
scikit-learn/scikit-learn
sklearn/utils/_missing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_missing.py
BSD-3-Clause
def _check_X_y(self, X, y=None, should_be_fitted=True): """Validate X and y and make extra check. Parameters ---------- X : array-like of shape (n_samples, n_features) The data set. `X` is checked only if `check_X` is not `None` (default is None). y : array-like of shape (n_samples), default=None The corresponding target, by default `None`. `y` is checked only if `check_y` is not `None` (default is None). should_be_fitted : bool, default=True Whether or not the classifier should be already fitted. By default True. Returns ------- X, y """ if should_be_fitted: check_is_fitted(self) if self.check_X is not None: params = {} if self.check_X_params is None else self.check_X_params checked_X = self.check_X(X, **params) if isinstance(checked_X, (bool, np.bool_)): assert checked_X else: X = checked_X if y is not None and self.check_y is not None: params = {} if self.check_y_params is None else self.check_y_params checked_y = self.check_y(y, **params) if isinstance(checked_y, (bool, np.bool_)): assert checked_y else: y = checked_y return X, y
Validate X and y and make extra check. Parameters ---------- X : array-like of shape (n_samples, n_features) The data set. `X` is checked only if `check_X` is not `None` (default is None). y : array-like of shape (n_samples), default=None The corresponding target, by default `None`. `y` is checked only if `check_y` is not `None` (default is None). should_be_fitted : bool, default=True Whether or not the classifier should be already fitted. By default True. Returns ------- X, y
_check_X_y
python
scikit-learn/scikit-learn
sklearn/utils/_mocking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py
BSD-3-Clause
def fit(self, X, y, sample_weight=None, **fit_params): """Fit classifier. Parameters ---------- X : array-like 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 shape (n_samples, n_outputs) or (n_samples,), \ default=None Target relative to X for classification or regression; None for unsupervised learning. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. **fit_params : dict of string -> object Parameters passed to the ``fit`` method of the estimator Returns ------- self """ assert _num_samples(X) == _num_samples(y) if self.methods_to_check == "all" or "fit" in self.methods_to_check: X, y = self._check_X_y(X, y, should_be_fitted=False) self.n_features_in_ = np.shape(X)[1] self.classes_ = np.unique(check_array(y, ensure_2d=False, allow_nd=True)) if self.expected_fit_params: missing = set(self.expected_fit_params) - set(fit_params) if missing: raise AssertionError( f"Expected fit parameter(s) {list(missing)} not seen." ) for key, value in fit_params.items(): if _num_samples(value) != _num_samples(X): raise AssertionError( f"Fit parameter {key} has length {_num_samples(value)}" f"; expected {_num_samples(X)}." ) if self.expected_sample_weight: if sample_weight is None: raise AssertionError("Expected sample_weight to be passed") _check_sample_weight(sample_weight, X) return self
Fit classifier. Parameters ---------- X : array-like 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 shape (n_samples, n_outputs) or (n_samples,), default=None Target relative to X for classification or regression; None for unsupervised learning. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. **fit_params : dict of string -> object Parameters passed to the ``fit`` method of the estimator Returns ------- self
fit
python
scikit-learn/scikit-learn
sklearn/utils/_mocking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py
BSD-3-Clause
def predict(self, X): """Predict the first class seen in `classes_`. Parameters ---------- X : array-like of shape (n_samples, n_features) The input data. Returns ------- preds : ndarray of shape (n_samples,) Predictions of the first class seen in `classes_`. """ if self.methods_to_check == "all" or "predict" in self.methods_to_check: X, y = self._check_X_y(X) rng = check_random_state(self.random_state) return rng.choice(self.classes_, size=_num_samples(X))
Predict the first class seen in `classes_`. Parameters ---------- X : array-like of shape (n_samples, n_features) The input data. Returns ------- preds : ndarray of shape (n_samples,) Predictions of the first class seen in `classes_`.
predict
python
scikit-learn/scikit-learn
sklearn/utils/_mocking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py
BSD-3-Clause
def predict_proba(self, X): """Predict probabilities for each class. Here, the dummy classifier will provide a probability of 1 for the first class of `classes_` and 0 otherwise. Parameters ---------- X : array-like of shape (n_samples, n_features) The input data. Returns ------- proba : ndarray of shape (n_samples, n_classes) The probabilities for each sample and class. """ if self.methods_to_check == "all" or "predict_proba" in self.methods_to_check: X, y = self._check_X_y(X) rng = check_random_state(self.random_state) proba = rng.randn(_num_samples(X), len(self.classes_)) proba = np.abs(proba, out=proba) proba /= np.sum(proba, axis=1)[:, np.newaxis] return proba
Predict probabilities for each class. Here, the dummy classifier will provide a probability of 1 for the first class of `classes_` and 0 otherwise. Parameters ---------- X : array-like of shape (n_samples, n_features) The input data. Returns ------- proba : ndarray of shape (n_samples, n_classes) The probabilities for each sample and class.
predict_proba
python
scikit-learn/scikit-learn
sklearn/utils/_mocking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py
BSD-3-Clause
def decision_function(self, X): """Confidence score. Parameters ---------- X : array-like of shape (n_samples, n_features) The input data. Returns ------- decision : ndarray of shape (n_samples,) if n_classes == 2\ else (n_samples, n_classes) Confidence score. """ if ( self.methods_to_check == "all" or "decision_function" in self.methods_to_check ): X, y = self._check_X_y(X) rng = check_random_state(self.random_state) if len(self.classes_) == 2: # for binary classifier, the confidence score is related to # classes_[1] and therefore should be null. return rng.randn(_num_samples(X)) else: return rng.randn(_num_samples(X), len(self.classes_))
Confidence score. Parameters ---------- X : array-like of shape (n_samples, n_features) The input data. Returns ------- decision : ndarray of shape (n_samples,) if n_classes == 2 else (n_samples, n_classes) Confidence score.
decision_function
python
scikit-learn/scikit-learn
sklearn/utils/_mocking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py
BSD-3-Clause
def score(self, X=None, Y=None): """Fake score. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data, where `n_samples` is the number of samples and `n_features` is the number of features. Y : array-like of shape (n_samples, n_output) or (n_samples,) Target relative to X for classification or regression; None for unsupervised learning. Returns ------- score : float Either 0 or 1 depending of `foo_param` (i.e. `foo_param > 1 => score=1` otherwise `score=0`). """ if self.methods_to_check == "all" or "score" in self.methods_to_check: self._check_X_y(X, Y) if self.foo_param > 1: score = 1.0 else: score = 0.0 return score
Fake score. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data, where `n_samples` is the number of samples and `n_features` is the number of features. Y : array-like of shape (n_samples, n_output) or (n_samples,) Target relative to X for classification or regression; None for unsupervised learning. Returns ------- score : float Either 0 or 1 depending of `foo_param` (i.e. `foo_param > 1 => score=1` otherwise `score=0`).
score
python
scikit-learn/scikit-learn
sklearn/utils/_mocking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_mocking.py
BSD-3-Clause
def check_matplotlib_support(caller_name): """Raise ImportError with detailed error message if mpl is not installed. Plot utilities like any of the Display's plotting functions should lazily import matplotlib and call this helper before any computation. Parameters ---------- caller_name : str The name of the caller that requires matplotlib. """ try: import matplotlib # noqa: F401 except ImportError as e: raise ImportError( "{} requires matplotlib. You can install matplotlib with " "`pip install matplotlib`".format(caller_name) ) from e
Raise ImportError with detailed error message if mpl is not installed. Plot utilities like any of the Display's plotting functions should lazily import matplotlib and call this helper before any computation. Parameters ---------- caller_name : str The name of the caller that requires matplotlib.
check_matplotlib_support
python
scikit-learn/scikit-learn
sklearn/utils/_optional_dependencies.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_optional_dependencies.py
BSD-3-Clause
def check_pandas_support(caller_name): """Raise ImportError with detailed error message if pandas is not installed. Plot utilities like :func:`fetch_openml` should lazily import pandas and call this helper before any computation. Parameters ---------- caller_name : str The name of the caller that requires pandas. Returns ------- pandas The pandas package. """ try: import pandas return pandas except ImportError as e: raise ImportError("{} requires pandas.".format(caller_name)) from e
Raise ImportError with detailed error message if pandas is not installed. Plot utilities like :func:`fetch_openml` should lazily import pandas and call this helper before any computation. Parameters ---------- caller_name : str The name of the caller that requires pandas. Returns ------- pandas The pandas package.
check_pandas_support
python
scikit-learn/scikit-learn
sklearn/utils/_optional_dependencies.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_optional_dependencies.py
BSD-3-Clause
def validate_parameter_constraints(parameter_constraints, params, caller_name): """Validate types and values of given parameters. Parameters ---------- parameter_constraints : dict or {"no_validation"} If "no_validation", validation is skipped for this parameter. If a dict, it must be a dictionary `param_name: list of constraints`. A parameter is valid if it satisfies one of the constraints from the list. Constraints can be: - an Interval object, representing a continuous or discrete range of numbers - the string "array-like" - the string "sparse matrix" - the string "random_state" - callable - None, meaning that None is a valid value for the parameter - any type, meaning that any instance of this type is valid - an Options object, representing a set of elements of a given type - a StrOptions object, representing a set of strings - the string "boolean" - the string "verbose" - the string "cv_object" - the string "nan" - a MissingValues object representing markers for missing values - a HasMethods object, representing method(s) an object must have - a Hidden object, representing a constraint not meant to be exposed to the user params : dict A dictionary `param_name: param_value`. The parameters to validate against the constraints. caller_name : str The name of the estimator or function or method that called this function. """ for param_name, param_val in params.items(): # We allow parameters to not have a constraint so that third party estimators # can inherit from sklearn estimators without having to necessarily use the # validation tools. if param_name not in parameter_constraints: continue constraints = parameter_constraints[param_name] if constraints == "no_validation": continue constraints = [make_constraint(constraint) for constraint in constraints] for constraint in constraints: if constraint.is_satisfied_by(param_val): # this constraint is satisfied, no need to check further. break else: # No constraint is satisfied, raise with an informative message. # Ignore constraints that we don't want to expose in the error message, # i.e. options that are for internal purpose or not officially supported. constraints = [ constraint for constraint in constraints if not constraint.hidden ] if len(constraints) == 1: constraints_str = f"{constraints[0]}" else: constraints_str = ( f"{', '.join([str(c) for c in constraints[:-1]])} or" f" {constraints[-1]}" ) raise InvalidParameterError( f"The {param_name!r} parameter of {caller_name} must be" f" {constraints_str}. Got {param_val!r} instead." )
Validate types and values of given parameters. Parameters ---------- parameter_constraints : dict or {"no_validation"} If "no_validation", validation is skipped for this parameter. If a dict, it must be a dictionary `param_name: list of constraints`. A parameter is valid if it satisfies one of the constraints from the list. Constraints can be: - an Interval object, representing a continuous or discrete range of numbers - the string "array-like" - the string "sparse matrix" - the string "random_state" - callable - None, meaning that None is a valid value for the parameter - any type, meaning that any instance of this type is valid - an Options object, representing a set of elements of a given type - a StrOptions object, representing a set of strings - the string "boolean" - the string "verbose" - the string "cv_object" - the string "nan" - a MissingValues object representing markers for missing values - a HasMethods object, representing method(s) an object must have - a Hidden object, representing a constraint not meant to be exposed to the user params : dict A dictionary `param_name: param_value`. The parameters to validate against the constraints. caller_name : str The name of the estimator or function or method that called this function.
validate_parameter_constraints
python
scikit-learn/scikit-learn
sklearn/utils/_param_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py
BSD-3-Clause
def make_constraint(constraint): """Convert the constraint into the appropriate Constraint object. Parameters ---------- constraint : object The constraint to convert. Returns ------- constraint : instance of _Constraint The converted constraint. """ if isinstance(constraint, str) and constraint == "array-like": return _ArrayLikes() if isinstance(constraint, str) and constraint == "sparse matrix": return _SparseMatrices() if isinstance(constraint, str) and constraint == "random_state": return _RandomStates() if constraint is callable: return _Callables() if constraint is None: return _NoneConstraint() if isinstance(constraint, type): return _InstancesOf(constraint) if isinstance( constraint, (Interval, StrOptions, Options, HasMethods, MissingValues) ): return constraint if isinstance(constraint, str) and constraint == "boolean": return _Booleans() if isinstance(constraint, str) and constraint == "verbose": return _VerboseHelper() if isinstance(constraint, str) and constraint == "cv_object": return _CVObjects() if isinstance(constraint, Hidden): constraint = make_constraint(constraint.constraint) constraint.hidden = True return constraint if (isinstance(constraint, str) and constraint == "nan") or ( isinstance(constraint, float) and np.isnan(constraint) ): return _NanConstraint() raise ValueError(f"Unknown constraint type: {constraint}")
Convert the constraint into the appropriate Constraint object. Parameters ---------- constraint : object The constraint to convert. Returns ------- constraint : instance of _Constraint The converted constraint.
make_constraint
python
scikit-learn/scikit-learn
sklearn/utils/_param_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py
BSD-3-Clause
def validate_params(parameter_constraints, *, prefer_skip_nested_validation): """Decorator to validate types and values of functions and methods. Parameters ---------- parameter_constraints : dict A dictionary `param_name: list of constraints`. See the docstring of `validate_parameter_constraints` for a description of the accepted constraints. Note that the *args and **kwargs parameters are not validated and must not be present in the parameter_constraints dictionary. prefer_skip_nested_validation : bool If True, the validation of parameters of inner estimators or functions called by the decorated function will be skipped. This is useful to avoid validating many times the parameters passed by the user from the public facing API. It's also useful to avoid validating parameters that we pass internally to inner functions that are guaranteed to be valid by the test suite. It should be set to True for most functions, except for those that receive non-validated objects as parameters or that are just wrappers around classes because they only perform a partial validation. Returns ------- decorated_function : function or method The decorated function. """ def decorator(func): # The dict of parameter constraints is set as an attribute of the function # to make it possible to dynamically introspect the constraints for # automatic testing. setattr(func, "_skl_parameter_constraints", parameter_constraints) @functools.wraps(func) def wrapper(*args, **kwargs): global_skip_validation = get_config()["skip_parameter_validation"] if global_skip_validation: return func(*args, **kwargs) func_sig = signature(func) # Map *args/**kwargs to the function signature params = func_sig.bind(*args, **kwargs) params.apply_defaults() # ignore self/cls and positional/keyword markers to_ignore = [ p.name for p in func_sig.parameters.values() if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD) ] to_ignore += ["self", "cls"] params = {k: v for k, v in params.arguments.items() if k not in to_ignore} validate_parameter_constraints( parameter_constraints, params, caller_name=func.__qualname__ ) try: with config_context( skip_parameter_validation=( prefer_skip_nested_validation or global_skip_validation ) ): return func(*args, **kwargs) except InvalidParameterError as e: # When the function is just a wrapper around an estimator, we allow # the function to delegate validation to the estimator, but we replace # the name of the estimator by the name of the function in the error # message to avoid confusion. msg = re.sub( r"parameter of \w+ must be", f"parameter of {func.__qualname__} must be", str(e), ) raise InvalidParameterError(msg) from e return wrapper return decorator
Decorator to validate types and values of functions and methods. Parameters ---------- parameter_constraints : dict A dictionary `param_name: list of constraints`. See the docstring of `validate_parameter_constraints` for a description of the accepted constraints. Note that the *args and **kwargs parameters are not validated and must not be present in the parameter_constraints dictionary. prefer_skip_nested_validation : bool If True, the validation of parameters of inner estimators or functions called by the decorated function will be skipped. This is useful to avoid validating many times the parameters passed by the user from the public facing API. It's also useful to avoid validating parameters that we pass internally to inner functions that are guaranteed to be valid by the test suite. It should be set to True for most functions, except for those that receive non-validated objects as parameters or that are just wrappers around classes because they only perform a partial validation. Returns ------- decorated_function : function or method The decorated function.
validate_params
python
scikit-learn/scikit-learn
sklearn/utils/_param_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py
BSD-3-Clause
def _type_name(t): """Convert type into human readable string.""" module = t.__module__ qualname = t.__qualname__ if module == "builtins": return qualname elif t == Real: return "float" elif t == Integral: return "int" return f"{module}.{qualname}"
Convert type into human readable string.
_type_name
python
scikit-learn/scikit-learn
sklearn/utils/_param_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py
BSD-3-Clause
def is_satisfied_by(self, val): """Whether or not a value satisfies the constraint. Parameters ---------- val : object The value to check. Returns ------- is_satisfied : bool Whether or not the constraint is satisfied by this value. """
Whether or not a value satisfies the constraint. Parameters ---------- val : object The value to check. Returns ------- is_satisfied : bool Whether or not the constraint is satisfied by this value.
is_satisfied_by
python
scikit-learn/scikit-learn
sklearn/utils/_param_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py
BSD-3-Clause
def _mark_if_deprecated(self, option): """Add a deprecated mark to an option if needed.""" option_str = f"{option!r}" if option in self.deprecated: option_str = f"{option_str} (deprecated)" return option_str
Add a deprecated mark to an option if needed.
_mark_if_deprecated
python
scikit-learn/scikit-learn
sklearn/utils/_param_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py
BSD-3-Clause
def generate_invalid_param_val(constraint): """Return a value that does not satisfy the constraint. Raises a NotImplementedError if there exists no invalid value for this constraint. This is only useful for testing purpose. Parameters ---------- constraint : _Constraint instance The constraint to generate a value for. Returns ------- val : object A value that does not satisfy the constraint. """ if isinstance(constraint, StrOptions): return f"not {' or '.join(constraint.options)}" if isinstance(constraint, MissingValues): return np.array([1, 2, 3]) if isinstance(constraint, _VerboseHelper): return -1 if isinstance(constraint, HasMethods): return type("HasNotMethods", (), {})() if isinstance(constraint, _IterablesNotString): return "a string" if isinstance(constraint, _CVObjects): return "not a cv object" if isinstance(constraint, Interval) and constraint.type is Integral: if constraint.left is not None: return constraint.left - 1 if constraint.right is not None: return constraint.right + 1 # There's no integer outside (-inf, +inf) raise NotImplementedError if isinstance(constraint, Interval) and constraint.type in (Real, RealNotInt): if constraint.left is not None: return constraint.left - 1e-6 if constraint.right is not None: return constraint.right + 1e-6 # bounds are -inf, +inf if constraint.closed in ("right", "neither"): return -np.inf if constraint.closed in ("left", "neither"): return np.inf # interval is [-inf, +inf] return np.nan raise NotImplementedError
Return a value that does not satisfy the constraint. Raises a NotImplementedError if there exists no invalid value for this constraint. This is only useful for testing purpose. Parameters ---------- constraint : _Constraint instance The constraint to generate a value for. Returns ------- val : object A value that does not satisfy the constraint.
generate_invalid_param_val
python
scikit-learn/scikit-learn
sklearn/utils/_param_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py
BSD-3-Clause
def generate_valid_param(constraint): """Return a value that does satisfy a constraint. This is only useful for testing purpose. Parameters ---------- constraint : Constraint instance The constraint to generate a value for. Returns ------- val : object A value that does satisfy the constraint. """ if isinstance(constraint, _ArrayLikes): return np.array([1, 2, 3]) if isinstance(constraint, _SparseMatrices): return csr_matrix([[0, 1], [1, 0]]) if isinstance(constraint, _RandomStates): return np.random.RandomState(42) if isinstance(constraint, _Callables): return lambda x: x if isinstance(constraint, _NoneConstraint): return None if isinstance(constraint, _InstancesOf): if constraint.type is np.ndarray: # special case for ndarray since it can't be instantiated without arguments return np.array([1, 2, 3]) if constraint.type in (Integral, Real): # special case for Integral and Real since they are abstract classes return 1 return constraint.type() if isinstance(constraint, _Booleans): return True if isinstance(constraint, _VerboseHelper): return 1 if isinstance(constraint, MissingValues) and constraint.numeric_only: return np.nan if isinstance(constraint, MissingValues) and not constraint.numeric_only: return "missing" if isinstance(constraint, HasMethods): return type( "ValidHasMethods", (), {m: lambda self: None for m in constraint.methods} )() if isinstance(constraint, _IterablesNotString): return [1, 2, 3] if isinstance(constraint, _CVObjects): return 5 if isinstance(constraint, Options): # includes StrOptions for option in constraint.options: return option if isinstance(constraint, Interval): interval = constraint if interval.left is None and interval.right is None: return 0 elif interval.left is None: return interval.right - 1 elif interval.right is None: return interval.left + 1 else: if interval.type is Real: return (interval.left + interval.right) / 2 else: return interval.left + 1 raise ValueError(f"Unknown constraint type: {constraint}")
Return a value that does satisfy a constraint. This is only useful for testing purpose. Parameters ---------- constraint : Constraint instance The constraint to generate a value for. Returns ------- val : object A value that does satisfy the constraint.
generate_valid_param
python
scikit-learn/scikit-learn
sklearn/utils/_param_validation.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_param_validation.py
BSD-3-Clause
def _get_legend_label(curve_legend_metric, curve_name, legend_metric_name): """Helper to get legend label using `name` and `legend_metric`""" if curve_legend_metric is not None and curve_name is not None: label = f"{curve_name} ({legend_metric_name} = {curve_legend_metric:0.2f})" elif curve_legend_metric is not None: label = f"{legend_metric_name} = {curve_legend_metric:0.2f}" elif curve_name is not None: label = curve_name else: label = None return label
Helper to get legend label using `name` and `legend_metric`
_get_legend_label
python
scikit-learn/scikit-learn
sklearn/utils/_plotting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py
BSD-3-Clause
def _validate_curve_kwargs( n_curves, name, legend_metric, legend_metric_name, curve_kwargs, **kwargs, ): """Get validated line kwargs for each curve. Parameters ---------- n_curves : int Number of curves. name : list of str or None Name for labeling legend entries. legend_metric : dict Dictionary with "mean" and "std" keys, or "metric" key of metric values for each curve. If None, "label" will not contain metric values. legend_metric_name : str Name of the summary value provided in `legend_metrics`. curve_kwargs : dict or list of dict or None Dictionary with keywords passed to the matplotlib's `plot` function to draw the individual curves. If a list is provided, the parameters are applied to the curves sequentially. If a single dictionary is provided, the same parameters are applied to all curves. **kwargs : dict Deprecated. Keyword arguments to be passed to matplotlib's `plot`. """ # TODO(1.9): Remove deprecated **kwargs if curve_kwargs and kwargs: raise ValueError( "Cannot provide both `curve_kwargs` and `kwargs`. `**kwargs` is " "deprecated in 1.7 and will be removed in 1.9. Pass all matplotlib " "arguments to `curve_kwargs` as a dictionary." ) if kwargs: warnings.warn( "`**kwargs` is deprecated and will be removed in 1.9. Pass all " "matplotlib arguments to `curve_kwargs` as a dictionary instead.", FutureWarning, ) curve_kwargs = kwargs if isinstance(curve_kwargs, list) and len(curve_kwargs) != n_curves: raise ValueError( f"`curve_kwargs` must be None, a dictionary or a list of length " f"{n_curves}. Got: {curve_kwargs}." ) # Ensure valid `name` and `curve_kwargs` combination. if ( isinstance(name, list) and len(name) != 1 and not isinstance(curve_kwargs, list) ): raise ValueError( "To avoid labeling individual curves that have the same appearance, " f"`curve_kwargs` should be a list of {n_curves} dictionaries. " "Alternatively, set `name` to `None` or a single string to label " "a single legend entry with mean ROC AUC score of all curves." ) # Ensure `name` is of the correct length if isinstance(name, str): name = [name] if isinstance(name, list) and len(name) == 1: name = name * n_curves name = [None] * n_curves if name is None else name # Ensure `curve_kwargs` is of correct length if isinstance(curve_kwargs, Mapping): curve_kwargs = [curve_kwargs] * n_curves default_multi_curve_kwargs = {"alpha": 0.5, "linestyle": "--", "color": "blue"} if curve_kwargs is None: if n_curves > 1: curve_kwargs = [default_multi_curve_kwargs] * n_curves else: curve_kwargs = [{}] labels = [] if "mean" in legend_metric: label_aggregate = _BinaryClassifierCurveDisplayMixin._get_legend_label( legend_metric["mean"], name[0], legend_metric_name ) # Note: "std" always `None` when "mean" is `None` - no metric value added # to label in this case if legend_metric["std"] is not None: # Add the "+/- std" to the end (in brackets if name provided) if name[0] is not None: label_aggregate = ( label_aggregate[:-1] + f" +/- {legend_metric['std']:0.2f})" ) else: label_aggregate = ( label_aggregate + f" +/- {legend_metric['std']:0.2f}" ) # Add `label` for first curve only, set to `None` for remaining curves labels.extend([label_aggregate] + [None] * (n_curves - 1)) else: for curve_legend_metric, curve_name in zip(legend_metric["metric"], name): labels.append( _BinaryClassifierCurveDisplayMixin._get_legend_label( curve_legend_metric, curve_name, legend_metric_name ) ) curve_kwargs_ = [ _validate_style_kwargs({"label": label}, curve_kwargs[fold_idx]) for fold_idx, label in enumerate(labels) ] return curve_kwargs_
Get validated line kwargs for each curve. Parameters ---------- n_curves : int Number of curves. name : list of str or None Name for labeling legend entries. legend_metric : dict Dictionary with "mean" and "std" keys, or "metric" key of metric values for each curve. If None, "label" will not contain metric values. legend_metric_name : str Name of the summary value provided in `legend_metrics`. curve_kwargs : dict or list of dict or None Dictionary with keywords passed to the matplotlib's `plot` function to draw the individual curves. If a list is provided, the parameters are applied to the curves sequentially. If a single dictionary is provided, the same parameters are applied to all curves. **kwargs : dict Deprecated. Keyword arguments to be passed to matplotlib's `plot`.
_validate_curve_kwargs
python
scikit-learn/scikit-learn
sklearn/utils/_plotting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py
BSD-3-Clause
def _validate_score_name(score_name, scoring, negate_score): """Validate the `score_name` parameter. If `score_name` is provided, we just return it as-is. If `score_name` is `None`, we use `Score` if `negate_score` is `False` and `Negative score` otherwise. If `score_name` is a string or a callable, we infer the name. We replace `_` by spaces and capitalize the first letter. We remove `neg_` and replace it by `"Negative"` if `negate_score` is `False` or just remove it otherwise. """ if score_name is not None: return score_name elif scoring is None: return "Negative score" if negate_score else "Score" else: score_name = scoring.__name__ if callable(scoring) else scoring if negate_score: if score_name.startswith("neg_"): score_name = score_name[4:] else: score_name = f"Negative {score_name}" elif score_name.startswith("neg_"): score_name = f"Negative {score_name[4:]}" score_name = score_name.replace("_", " ") return score_name.capitalize()
Validate the `score_name` parameter. If `score_name` is provided, we just return it as-is. If `score_name` is `None`, we use `Score` if `negate_score` is `False` and `Negative score` otherwise. If `score_name` is a string or a callable, we infer the name. We replace `_` by spaces and capitalize the first letter. We remove `neg_` and replace it by `"Negative"` if `negate_score` is `False` or just remove it otherwise.
_validate_score_name
python
scikit-learn/scikit-learn
sklearn/utils/_plotting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py
BSD-3-Clause
def _interval_max_min_ratio(data): """Compute the ratio between the largest and smallest inter-point distances. A value larger than 5 typically indicates that the parameter range would better be displayed with a log scale while a linear scale would be more suitable otherwise. """ diff = np.diff(np.sort(data)) return diff.max() / diff.min()
Compute the ratio between the largest and smallest inter-point distances. A value larger than 5 typically indicates that the parameter range would better be displayed with a log scale while a linear scale would be more suitable otherwise.
_interval_max_min_ratio
python
scikit-learn/scikit-learn
sklearn/utils/_plotting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py
BSD-3-Clause
def _validate_style_kwargs(default_style_kwargs, user_style_kwargs): """Create valid style kwargs by avoiding Matplotlib alias errors. Matplotlib raises an error when, for example, 'color' and 'c', or 'linestyle' and 'ls', are specified together. To avoid this, we automatically keep only the one specified by the user and raise an error if the user specifies both. Parameters ---------- default_style_kwargs : dict The Matplotlib style kwargs used by default in the scikit-learn display. user_style_kwargs : dict The user-defined Matplotlib style kwargs. Returns ------- valid_style_kwargs : dict The validated style kwargs taking into account both default and user-defined Matplotlib style kwargs. """ invalid_to_valid_kw = { "ls": "linestyle", "c": "color", "ec": "edgecolor", "fc": "facecolor", "lw": "linewidth", "mec": "markeredgecolor", "mfcalt": "markerfacecoloralt", "ms": "markersize", "mew": "markeredgewidth", "mfc": "markerfacecolor", "aa": "antialiased", "ds": "drawstyle", "font": "fontproperties", "family": "fontfamily", "name": "fontname", "size": "fontsize", "stretch": "fontstretch", "style": "fontstyle", "variant": "fontvariant", "weight": "fontweight", "ha": "horizontalalignment", "va": "verticalalignment", "ma": "multialignment", } for invalid_key, valid_key in invalid_to_valid_kw.items(): if invalid_key in user_style_kwargs and valid_key in user_style_kwargs: raise TypeError( f"Got both {invalid_key} and {valid_key}, which are aliases of one " "another" ) valid_style_kwargs = default_style_kwargs.copy() for key in user_style_kwargs.keys(): if key in invalid_to_valid_kw: valid_style_kwargs[invalid_to_valid_kw[key]] = user_style_kwargs[key] else: valid_style_kwargs[key] = user_style_kwargs[key] return valid_style_kwargs
Create valid style kwargs by avoiding Matplotlib alias errors. Matplotlib raises an error when, for example, 'color' and 'c', or 'linestyle' and 'ls', are specified together. To avoid this, we automatically keep only the one specified by the user and raise an error if the user specifies both. Parameters ---------- default_style_kwargs : dict The Matplotlib style kwargs used by default in the scikit-learn display. user_style_kwargs : dict The user-defined Matplotlib style kwargs. Returns ------- valid_style_kwargs : dict The validated style kwargs taking into account both default and user-defined Matplotlib style kwargs.
_validate_style_kwargs
python
scikit-learn/scikit-learn
sklearn/utils/_plotting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py
BSD-3-Clause
def _despine(ax): """Remove the top and right spines of the plot. Parameters ---------- ax : matplotlib.axes.Axes The axes of the plot to despine. """ for s in ["top", "right"]: ax.spines[s].set_visible(False) for s in ["bottom", "left"]: ax.spines[s].set_bounds(0, 1)
Remove the top and right spines of the plot. Parameters ---------- ax : matplotlib.axes.Axes The axes of the plot to despine.
_despine
python
scikit-learn/scikit-learn
sklearn/utils/_plotting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py
BSD-3-Clause
def _convert_to_list_leaving_none(param): """Convert parameters to a list, leaving `None` as is.""" if param is None: return None if isinstance(param, list): return param return [param]
Convert parameters to a list, leaving `None` as is.
_convert_to_list_leaving_none
python
scikit-learn/scikit-learn
sklearn/utils/_plotting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py
BSD-3-Clause
def _check_param_lengths(required, optional, class_name): """Check required and optional parameters are of the same length.""" optional_provided = {} for name, param in optional.items(): if isinstance(param, list): optional_provided[name] = param all_params = {**required, **optional_provided} if len({len(param) for param in all_params.values()}) > 1: param_keys = [key for key in all_params.keys()] # Note: below code requires `len(param_keys) >= 2`, which is the case for all # display classes params_formatted = " and ".join([", ".join(param_keys[:-1]), param_keys[-1]]) or_plot = "" if "'name' (or self.name)" in param_keys: or_plot = " (or `plot`)" lengths_formatted = ", ".join( f"{key}: {len(value)}" for key, value in all_params.items() ) raise ValueError( f"{params_formatted} from `{class_name}` initialization{or_plot}, " f"should all be lists of the same length. Got: {lengths_formatted}" )
Check required and optional parameters are of the same length.
_check_param_lengths
python
scikit-learn/scikit-learn
sklearn/utils/_plotting.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_plotting.py
BSD-3-Clause
def _changed_params(estimator): """Return dict (param_name: value) of parameters that were given to estimator with non-default values.""" params = estimator.get_params(deep=False) init_func = getattr(estimator.__init__, "deprecated_original", estimator.__init__) init_params = inspect.signature(init_func).parameters init_params = {name: param.default for name, param in init_params.items()} def has_changed(k, v): if k not in init_params: # happens if k is part of a **kwargs return True if init_params[k] == inspect._empty: # k has no default value return True # try to avoid calling repr on nested estimators if isinstance(v, BaseEstimator) and v.__class__ != init_params[k].__class__: return True # Use repr as a last resort. It may be expensive. if repr(v) != repr(init_params[k]) and not ( is_scalar_nan(init_params[k]) and is_scalar_nan(v) ): return True return False return {k: v for k, v in params.items() if has_changed(k, v)}
Return dict (param_name: value) of parameters that were given to estimator with non-default values.
_changed_params
python
scikit-learn/scikit-learn
sklearn/utils/_pprint.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_pprint.py
BSD-3-Clause
def _format_params_or_dict_items( self, object, stream, indent, allowance, context, level, is_dict ): """Format dict items or parameters respecting the compact=True parameter. For some reason, the builtin rendering of dict items doesn't respect compact=True and will use one line per key-value if all cannot fit in a single line. Dict items will be rendered as <'key': value> while params will be rendered as <key=value>. The implementation is mostly copy/pasting from the builtin _format_items(). This also adds ellipsis if the number of items is greater than self.n_max_elements_to_show. """ write = stream.write indent += self._indent_per_level delimnl = ",\n" + " " * indent delim = "" width = max_width = self._width - indent + 1 it = iter(object) try: next_ent = next(it) except StopIteration: return last = False n_items = 0 while not last: if n_items == self.n_max_elements_to_show: write(", ...") break n_items += 1 ent = next_ent try: next_ent = next(it) except StopIteration: last = True max_width -= allowance width -= allowance if self._compact: k, v = ent krepr = self._repr(k, context, level) vrepr = self._repr(v, context, level) if not is_dict: krepr = krepr.strip("'") middle = ": " if is_dict else "=" rep = krepr + middle + vrepr w = len(rep) + 2 if width < w: width = max_width if delim: delim = delimnl if width >= w: width -= w write(delim) delim = ", " write(rep) continue write(delim) delim = delimnl class_ = KeyValTuple if is_dict else KeyValTupleParam self._format( class_(ent), stream, indent, allowance if last else 1, context, level )
Format dict items or parameters respecting the compact=True parameter. For some reason, the builtin rendering of dict items doesn't respect compact=True and will use one line per key-value if all cannot fit in a single line. Dict items will be rendered as <'key': value> while params will be rendered as <key=value>. The implementation is mostly copy/pasting from the builtin _format_items(). This also adds ellipsis if the number of items is greater than self.n_max_elements_to_show.
_format_params_or_dict_items
python
scikit-learn/scikit-learn
sklearn/utils/_pprint.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_pprint.py
BSD-3-Clause
def _format_items(self, items, stream, indent, allowance, context, level): """Format the items of an iterable (list, tuple...). Same as the built-in _format_items, with support for ellipsis if the number of elements is greater than self.n_max_elements_to_show. """ write = stream.write indent += self._indent_per_level if self._indent_per_level > 1: write((self._indent_per_level - 1) * " ") delimnl = ",\n" + " " * indent delim = "" width = max_width = self._width - indent + 1 it = iter(items) try: next_ent = next(it) except StopIteration: return last = False n_items = 0 while not last: if n_items == self.n_max_elements_to_show: write(", ...") break n_items += 1 ent = next_ent try: next_ent = next(it) except StopIteration: last = True max_width -= allowance width -= allowance if self._compact: rep = self._repr(ent, context, level) w = len(rep) + 2 if width < w: width = max_width if delim: delim = delimnl if width >= w: width -= w write(delim) delim = ", " write(rep) continue write(delim) delim = delimnl self._format(ent, stream, indent, allowance if last else 1, context, level)
Format the items of an iterable (list, tuple...). Same as the built-in _format_items, with support for ellipsis if the number of elements is greater than self.n_max_elements_to_show.
_format_items
python
scikit-learn/scikit-learn
sklearn/utils/_pprint.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_pprint.py
BSD-3-Clause
def _pprint_key_val_tuple(self, object, stream, indent, allowance, context, level): """Pretty printing for key-value tuples from dict or parameters.""" k, v = object rep = self._repr(k, context, level) if isinstance(object, KeyValTupleParam): rep = rep.strip("'") middle = "=" else: middle = ": " stream.write(rep) stream.write(middle) self._format( v, stream, indent + len(rep) + len(middle), allowance, context, level )
Pretty printing for key-value tuples from dict or parameters.
_pprint_key_val_tuple
python
scikit-learn/scikit-learn
sklearn/utils/_pprint.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_pprint.py
BSD-3-Clause
def _safe_repr(object, context, maxlevels, level, changed_only=False): """Same as the builtin _safe_repr, with added support for Estimator objects.""" typ = type(object) if typ in pprint._builtin_scalars: return repr(object), True, False r = getattr(typ, "__repr__", None) if issubclass(typ, dict) and r is dict.__repr__: if not object: return "{}", True, False objid = id(object) if maxlevels and level >= maxlevels: return "{...}", False, objid in context if objid in context: return pprint._recursion(object), False, True context[objid] = 1 readable = True recursive = False components = [] append = components.append level += 1 saferepr = _safe_repr items = sorted(object.items(), key=pprint._safe_tuple) for k, v in items: krepr, kreadable, krecur = saferepr( k, context, maxlevels, level, changed_only=changed_only ) vrepr, vreadable, vrecur = saferepr( v, context, maxlevels, level, changed_only=changed_only ) append("%s: %s" % (krepr, vrepr)) readable = readable and kreadable and vreadable if krecur or vrecur: recursive = True del context[objid] return "{%s}" % ", ".join(components), readable, recursive if (issubclass(typ, list) and r is list.__repr__) or ( issubclass(typ, tuple) and r is tuple.__repr__ ): if issubclass(typ, list): if not object: return "[]", True, False format = "[%s]" elif len(object) == 1: format = "(%s,)" else: if not object: return "()", True, False format = "(%s)" objid = id(object) if maxlevels and level >= maxlevels: return format % "...", False, objid in context if objid in context: return pprint._recursion(object), False, True context[objid] = 1 readable = True recursive = False components = [] append = components.append level += 1 for o in object: orepr, oreadable, orecur = _safe_repr( o, context, maxlevels, level, changed_only=changed_only ) append(orepr) if not oreadable: readable = False if orecur: recursive = True del context[objid] return format % ", ".join(components), readable, recursive if issubclass(typ, BaseEstimator): objid = id(object) if maxlevels and level >= maxlevels: return f"{typ.__name__}(...)", False, objid in context if objid in context: return pprint._recursion(object), False, True context[objid] = 1 readable = True recursive = False if changed_only: params = _changed_params(object) else: params = object.get_params(deep=False) components = [] append = components.append level += 1 saferepr = _safe_repr items = sorted(params.items(), key=pprint._safe_tuple) for k, v in items: krepr, kreadable, krecur = saferepr( k, context, maxlevels, level, changed_only=changed_only ) vrepr, vreadable, vrecur = saferepr( v, context, maxlevels, level, changed_only=changed_only ) append("%s=%s" % (krepr.strip("'"), vrepr)) readable = readable and kreadable and vreadable if krecur or vrecur: recursive = True del context[objid] return ("%s(%s)" % (typ.__name__, ", ".join(components)), readable, recursive) rep = repr(object) return rep, (rep and not rep.startswith("<")), False
Same as the builtin _safe_repr, with added support for Estimator objects.
_safe_repr
python
scikit-learn/scikit-learn
sklearn/utils/_pprint.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_pprint.py
BSD-3-Clause
def _process_predict_proba(*, y_pred, target_type, classes, pos_label): """Get the response values when the response method is `predict_proba`. This function process the `y_pred` array in the binary and multi-label cases. In the binary case, it selects the column corresponding to the positive class. In the multi-label case, it stacks the predictions if they are not in the "compressed" format `(n_samples, n_outputs)`. Parameters ---------- y_pred : ndarray Output of `estimator.predict_proba`. The shape depends on the target type: - for binary classification, it is a 2d array of shape `(n_samples, 2)`; - for multiclass classification, it is a 2d array of shape `(n_samples, n_classes)`; - for multilabel classification, it is either a list of 2d arrays of shape `(n_samples, 2)` (e.g. `RandomForestClassifier` or `KNeighborsClassifier`) or an array of shape `(n_samples, n_outputs)` (e.g. `MLPClassifier` or `RidgeClassifier`). target_type : {"binary", "multiclass", "multilabel-indicator"} Type of the target. classes : ndarray of shape (n_classes,) or list of such arrays Class labels as reported by `estimator.classes_`. pos_label : int, float, bool or str Only used with binary and multiclass targets. Returns ------- y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or \ (n_samples, n_output) Compressed predictions format as requested by the metrics. """ if target_type == "binary" and y_pred.shape[1] < 2: # We don't handle classifiers trained on a single class. raise ValueError( f"Got predict_proba of shape {y_pred.shape}, but need " "classifier with two classes." ) if target_type == "binary": col_idx = np.flatnonzero(classes == pos_label)[0] return y_pred[:, col_idx] elif target_type == "multilabel-indicator": # Use a compress format of shape `(n_samples, n_output)`. # Only `MLPClassifier` and `RidgeClassifier` return an array of shape # `(n_samples, n_outputs)`. if isinstance(y_pred, list): # list of arrays of shape `(n_samples, 2)` return np.vstack([p[:, -1] for p in y_pred]).T else: # array of shape `(n_samples, n_outputs)` return y_pred return y_pred
Get the response values when the response method is `predict_proba`. This function process the `y_pred` array in the binary and multi-label cases. In the binary case, it selects the column corresponding to the positive class. In the multi-label case, it stacks the predictions if they are not in the "compressed" format `(n_samples, n_outputs)`. Parameters ---------- y_pred : ndarray Output of `estimator.predict_proba`. The shape depends on the target type: - for binary classification, it is a 2d array of shape `(n_samples, 2)`; - for multiclass classification, it is a 2d array of shape `(n_samples, n_classes)`; - for multilabel classification, it is either a list of 2d arrays of shape `(n_samples, 2)` (e.g. `RandomForestClassifier` or `KNeighborsClassifier`) or an array of shape `(n_samples, n_outputs)` (e.g. `MLPClassifier` or `RidgeClassifier`). target_type : {"binary", "multiclass", "multilabel-indicator"} Type of the target. classes : ndarray of shape (n_classes,) or list of such arrays Class labels as reported by `estimator.classes_`. pos_label : int, float, bool or str Only used with binary and multiclass targets. Returns ------- y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or (n_samples, n_output) Compressed predictions format as requested by the metrics.
_process_predict_proba
python
scikit-learn/scikit-learn
sklearn/utils/_response.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_response.py
BSD-3-Clause
def _process_decision_function(*, y_pred, target_type, classes, pos_label): """Get the response values when the response method is `decision_function`. This function process the `y_pred` array in the binary and multi-label cases. In the binary case, it inverts the sign of the score if the positive label is not `classes[1]`. In the multi-label case, it stacks the predictions if they are not in the "compressed" format `(n_samples, n_outputs)`. Parameters ---------- y_pred : ndarray Output of `estimator.decision_function`. The shape depends on the target type: - for binary classification, it is a 1d array of shape `(n_samples,)` where the sign is assuming that `classes[1]` is the positive class; - for multiclass classification, it is a 2d array of shape `(n_samples, n_classes)`; - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`. target_type : {"binary", "multiclass", "multilabel-indicator"} Type of the target. classes : ndarray of shape (n_classes,) or list of such arrays Class labels as reported by `estimator.classes_`. pos_label : int, float, bool or str Only used with binary and multiclass targets. Returns ------- y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or \ (n_samples, n_output) Compressed predictions format as requested by the metrics. """ if target_type == "binary" and pos_label == classes[0]: return -1 * y_pred return y_pred
Get the response values when the response method is `decision_function`. This function process the `y_pred` array in the binary and multi-label cases. In the binary case, it inverts the sign of the score if the positive label is not `classes[1]`. In the multi-label case, it stacks the predictions if they are not in the "compressed" format `(n_samples, n_outputs)`. Parameters ---------- y_pred : ndarray Output of `estimator.decision_function`. The shape depends on the target type: - for binary classification, it is a 1d array of shape `(n_samples,)` where the sign is assuming that `classes[1]` is the positive class; - for multiclass classification, it is a 2d array of shape `(n_samples, n_classes)`; - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`. target_type : {"binary", "multiclass", "multilabel-indicator"} Type of the target. classes : ndarray of shape (n_classes,) or list of such arrays Class labels as reported by `estimator.classes_`. pos_label : int, float, bool or str Only used with binary and multiclass targets. Returns ------- y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or (n_samples, n_output) Compressed predictions format as requested by the metrics.
_process_decision_function
python
scikit-learn/scikit-learn
sklearn/utils/_response.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_response.py
BSD-3-Clause
def _get_response_values( estimator, X, response_method, pos_label=None, return_response_method_used=False, ): """Compute the response values of a classifier, an outlier detector, or a regressor. The response values are predictions such that it follows the following shape: - for binary classification, it is a 1d array of shape `(n_samples,)`; - for multiclass classification, it is a 2d array of shape `(n_samples, n_classes)`; - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`; - for outlier detection, it is a 1d array of shape `(n_samples,)`; - for regression, it is a 1d array of shape `(n_samples,)`. If `estimator` is a binary classifier, also return the label for the effective positive class. This utility is used primarily in the displays and the scikit-learn scorers. .. versionadded:: 1.3 Parameters ---------- estimator : estimator instance Fitted classifier, outlier detector, or regressor or a fitted :class:`~sklearn.pipeline.Pipeline` in which the last estimator is a classifier, an outlier detector, or a regressor. X : {array-like, sparse matrix} of shape (n_samples, n_features) Input values. response_method : {"predict_proba", "predict_log_proba", "decision_function", \ "predict"} or list of such str Specifies the response method to use get prediction from an estimator (i.e. :term:`predict_proba`, :term:`predict_log_proba`, :term:`decision_function` or :term:`predict`). Possible choices are: - if `str`, it corresponds to the name to the method to return; - if a list of `str`, it provides the method names in order of preference. The method returned corresponds to the first method in the list and which is implemented by `estimator`. pos_label : int, float, bool or str, default=None The class considered as the positive class when computing the metrics. If `None` and target is 'binary', `estimators.classes_[1]` is considered as the positive class. return_response_method_used : bool, default=False Whether to return the response method used to compute the response values. .. versionadded:: 1.4 Returns ------- y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or \ (n_samples, n_outputs) Target scores calculated from the provided `response_method` and `pos_label`. pos_label : int, float, bool, str or None The class considered as the positive class when computing the metrics. Returns `None` if `estimator` is a regressor or an outlier detector. response_method_used : str The response method used to compute the response values. Only returned if `return_response_method_used` is `True`. .. versionadded:: 1.4 Raises ------ ValueError If `pos_label` is not a valid label. If the shape of `y_pred` is not consistent for binary classifier. If the response method can be applied to a classifier only and `estimator` is a regressor. """ from sklearn.base import is_classifier, is_outlier_detector if is_classifier(estimator): prediction_method = _check_response_method(estimator, response_method) classes = estimator.classes_ target_type = type_of_target(classes) if target_type in ("binary", "multiclass"): if pos_label is not None and pos_label not in classes.tolist(): raise ValueError( f"pos_label={pos_label} is not a valid label: It should be " f"one of {classes}" ) elif pos_label is None and target_type == "binary": pos_label = classes[-1] y_pred = prediction_method(X) if prediction_method.__name__ in ("predict_proba", "predict_log_proba"): y_pred = _process_predict_proba( y_pred=y_pred, target_type=target_type, classes=classes, pos_label=pos_label, ) elif prediction_method.__name__ == "decision_function": y_pred = _process_decision_function( y_pred=y_pred, target_type=target_type, classes=classes, pos_label=pos_label, ) elif is_outlier_detector(estimator): prediction_method = _check_response_method(estimator, response_method) y_pred, pos_label = prediction_method(X), None else: # estimator is a regressor if response_method != "predict": raise ValueError( f"{estimator.__class__.__name__} should either be a classifier to be " f"used with response_method={response_method} or the response_method " "should be 'predict'. Got a regressor with response_method=" f"{response_method} instead." ) prediction_method = estimator.predict y_pred, pos_label = prediction_method(X), None if return_response_method_used: return y_pred, pos_label, prediction_method.__name__ return y_pred, pos_label
Compute the response values of a classifier, an outlier detector, or a regressor. The response values are predictions such that it follows the following shape: - for binary classification, it is a 1d array of shape `(n_samples,)`; - for multiclass classification, it is a 2d array of shape `(n_samples, n_classes)`; - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`; - for outlier detection, it is a 1d array of shape `(n_samples,)`; - for regression, it is a 1d array of shape `(n_samples,)`. If `estimator` is a binary classifier, also return the label for the effective positive class. This utility is used primarily in the displays and the scikit-learn scorers. .. versionadded:: 1.3 Parameters ---------- estimator : estimator instance Fitted classifier, outlier detector, or regressor or a fitted :class:`~sklearn.pipeline.Pipeline` in which the last estimator is a classifier, an outlier detector, or a regressor. X : {array-like, sparse matrix} of shape (n_samples, n_features) Input values. response_method : {"predict_proba", "predict_log_proba", "decision_function", "predict"} or list of such str Specifies the response method to use get prediction from an estimator (i.e. :term:`predict_proba`, :term:`predict_log_proba`, :term:`decision_function` or :term:`predict`). Possible choices are: - if `str`, it corresponds to the name to the method to return; - if a list of `str`, it provides the method names in order of preference. The method returned corresponds to the first method in the list and which is implemented by `estimator`. pos_label : int, float, bool or str, default=None The class considered as the positive class when computing the metrics. If `None` and target is 'binary', `estimators.classes_[1]` is considered as the positive class. return_response_method_used : bool, default=False Whether to return the response method used to compute the response values. .. versionadded:: 1.4 Returns ------- y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or (n_samples, n_outputs) Target scores calculated from the provided `response_method` and `pos_label`. pos_label : int, float, bool, str or None The class considered as the positive class when computing the metrics. Returns `None` if `estimator` is a regressor or an outlier detector. response_method_used : str The response method used to compute the response values. Only returned if `return_response_method_used` is `True`. .. versionadded:: 1.4 Raises ------ ValueError If `pos_label` is not a valid label. If the shape of `y_pred` is not consistent for binary classifier. If the response method can be applied to a classifier only and `estimator` is a regressor.
_get_response_values
python
scikit-learn/scikit-learn
sklearn/utils/_response.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_response.py
BSD-3-Clause
def _get_response_values_binary( estimator, X, response_method, pos_label=None, return_response_method_used=False ): """Compute the response values of a binary classifier. Parameters ---------- estimator : estimator instance Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` in which the last estimator is a binary classifier. X : {array-like, sparse matrix} of shape (n_samples, n_features) Input values. response_method : {'auto', 'predict_proba', 'decision_function'} Specifies whether to use :term:`predict_proba` or :term:`decision_function` as the target response. If set to 'auto', :term:`predict_proba` is tried first and if it does not exist :term:`decision_function` is tried next. pos_label : int, float, bool or str, default=None The class considered as the positive class when computing the metrics. By default, `estimators.classes_[1]` is considered as the positive class. return_response_method_used : bool, default=False Whether to return the response method used to compute the response values. .. versionadded:: 1.5 Returns ------- y_pred : ndarray of shape (n_samples,) Target scores calculated from the provided response_method and pos_label. pos_label : int, float, bool or str The class considered as the positive class when computing the metrics. response_method_used : str The response method used to compute the response values. Only returned if `return_response_method_used` is `True`. .. versionadded:: 1.5 """ classification_error = "Expected 'estimator' to be a binary classifier." check_is_fitted(estimator) if not is_classifier(estimator): raise ValueError( classification_error + f" Got {estimator.__class__.__name__} instead." ) elif len(estimator.classes_) != 2: raise ValueError( classification_error + f" Got {len(estimator.classes_)} classes instead." ) if response_method == "auto": response_method = ["predict_proba", "decision_function"] return _get_response_values( estimator, X, response_method, pos_label=pos_label, return_response_method_used=return_response_method_used, )
Compute the response values of a binary classifier. Parameters ---------- estimator : estimator instance Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` in which the last estimator is a binary classifier. X : {array-like, sparse matrix} of shape (n_samples, n_features) Input values. response_method : {'auto', 'predict_proba', 'decision_function'} Specifies whether to use :term:`predict_proba` or :term:`decision_function` as the target response. If set to 'auto', :term:`predict_proba` is tried first and if it does not exist :term:`decision_function` is tried next. pos_label : int, float, bool or str, default=None The class considered as the positive class when computing the metrics. By default, `estimators.classes_[1]` is considered as the positive class. return_response_method_used : bool, default=False Whether to return the response method used to compute the response values. .. versionadded:: 1.5 Returns ------- y_pred : ndarray of shape (n_samples,) Target scores calculated from the provided response_method and pos_label. pos_label : int, float, bool or str The class considered as the positive class when computing the metrics. response_method_used : str The response method used to compute the response values. Only returned if `return_response_method_used` is `True`. .. versionadded:: 1.5
_get_response_values_binary
python
scikit-learn/scikit-learn
sklearn/utils/_response.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_response.py
BSD-3-Clause
def create_container(self, X_output, X_original, columns, inplace=False): """Create container from `X_output` with additional metadata. Parameters ---------- X_output : {ndarray, dataframe} Data to wrap. X_original : {ndarray, dataframe} Original input dataframe. This is used to extract the metadata that should be passed to `X_output`, e.g. pandas row index. columns : callable, ndarray, or None The column names or a callable that returns the column names. The callable is useful if the column names require some computation. If `None`, then no columns are passed to the container's constructor. inplace : bool, default=False Whether or not we intend to modify `X_output` in-place. However, it does not guarantee that we return the same object if the in-place operation is not possible. Returns ------- wrapped_output : container_type `X_output` wrapped into the container type. """
Create container from `X_output` with additional metadata. Parameters ---------- X_output : {ndarray, dataframe} Data to wrap. X_original : {ndarray, dataframe} Original input dataframe. This is used to extract the metadata that should be passed to `X_output`, e.g. pandas row index. columns : callable, ndarray, or None The column names or a callable that returns the column names. The callable is useful if the column names require some computation. If `None`, then no columns are passed to the container's constructor. inplace : bool, default=False Whether or not we intend to modify `X_output` in-place. However, it does not guarantee that we return the same object if the in-place operation is not possible. Returns ------- wrapped_output : container_type `X_output` wrapped into the container type.
create_container
python
scikit-learn/scikit-learn
sklearn/utils/_set_output.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py
BSD-3-Clause
def is_supported_container(self, X): """Return True if X is a supported container. Parameters ---------- Xs: container Containers to be checked. Returns ------- is_supported_container : bool True if X is a supported container. """
Return True if X is a supported container. Parameters ---------- Xs: container Containers to be checked. Returns ------- is_supported_container : bool True if X is a supported container.
is_supported_container
python
scikit-learn/scikit-learn
sklearn/utils/_set_output.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py
BSD-3-Clause
def rename_columns(self, X, columns): """Rename columns in `X`. Parameters ---------- X : container Container which columns is updated. columns : ndarray of str Columns to update the `X`'s columns with. Returns ------- updated_container : container Container with new names. """
Rename columns in `X`. Parameters ---------- X : container Container which columns is updated. columns : ndarray of str Columns to update the `X`'s columns with. Returns ------- updated_container : container Container with new names.
rename_columns
python
scikit-learn/scikit-learn
sklearn/utils/_set_output.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py
BSD-3-Clause
def hstack(self, Xs): """Stack containers horizontally (column-wise). Parameters ---------- Xs : list of containers List of containers to stack. Returns ------- stacked_Xs : container Stacked containers. """
Stack containers horizontally (column-wise). Parameters ---------- Xs : list of containers List of containers to stack. Returns ------- stacked_Xs : container Stacked containers.
hstack
python
scikit-learn/scikit-learn
sklearn/utils/_set_output.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py
BSD-3-Clause
def _get_adapter_from_container(container): """Get the adapter that knows how to handle such container. See :class:`sklearn.utils._set_output.ContainerAdapterProtocol` for more details. """ module_name = container.__class__.__module__.split(".")[0] try: return ADAPTERS_MANAGER.adapters[module_name] except KeyError as exc: available_adapters = list(ADAPTERS_MANAGER.adapters.keys()) raise ValueError( "The container does not have a registered adapter in scikit-learn. " f"Available adapters are: {available_adapters} while the container " f"provided is: {container!r}." ) from exc
Get the adapter that knows how to handle such container. See :class:`sklearn.utils._set_output.ContainerAdapterProtocol` for more details.
_get_adapter_from_container
python
scikit-learn/scikit-learn
sklearn/utils/_set_output.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py
BSD-3-Clause
def _get_output_config(method, estimator=None): """Get output config based on estimator and global configuration. Parameters ---------- method : {"transform"} Estimator's method for which the output container is looked up. estimator : estimator instance or None Estimator to get the output configuration from. If `None`, check global configuration is used. Returns ------- config : dict Dictionary with keys: - "dense": specifies the dense container for `method`. This can be `"default"` or `"pandas"`. """ est_sklearn_output_config = getattr(estimator, "_sklearn_output_config", {}) if method in est_sklearn_output_config: dense_config = est_sklearn_output_config[method] else: dense_config = get_config()[f"{method}_output"] supported_outputs = ADAPTERS_MANAGER.supported_outputs if dense_config not in supported_outputs: raise ValueError( f"output config must be in {sorted(supported_outputs)}, got {dense_config}" ) return {"dense": dense_config}
Get output config based on estimator and global configuration. Parameters ---------- method : {"transform"} Estimator's method for which the output container is looked up. estimator : estimator instance or None Estimator to get the output configuration from. If `None`, check global configuration is used. Returns ------- config : dict Dictionary with keys: - "dense": specifies the dense container for `method`. This can be `"default"` or `"pandas"`.
_get_output_config
python
scikit-learn/scikit-learn
sklearn/utils/_set_output.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py
BSD-3-Clause
def _wrap_data_with_container(method, data_to_wrap, original_input, estimator): """Wrap output with container based on an estimator's or global config. Parameters ---------- method : {"transform"} Estimator's method to get container output for. data_to_wrap : {ndarray, dataframe} Data to wrap with container. original_input : {ndarray, dataframe} Original input of function. estimator : estimator instance Estimator with to get the output configuration from. Returns ------- output : {ndarray, dataframe} If the output config is "default" or the estimator is not configured for wrapping return `data_to_wrap` unchanged. If the output config is "pandas", return `data_to_wrap` as a pandas DataFrame. """ output_config = _get_output_config(method, estimator) if output_config["dense"] == "default" or not _auto_wrap_is_configured(estimator): return data_to_wrap dense_config = output_config["dense"] if issparse(data_to_wrap): raise ValueError( "The transformer outputs a scipy sparse matrix. " "Try to set the transformer output to a dense array or disable " f"{dense_config.capitalize()} output with set_output(transform='default')." ) adapter = ADAPTERS_MANAGER.adapters[dense_config] return adapter.create_container( data_to_wrap, original_input, columns=estimator.get_feature_names_out, )
Wrap output with container based on an estimator's or global config. Parameters ---------- method : {"transform"} Estimator's method to get container output for. data_to_wrap : {ndarray, dataframe} Data to wrap with container. original_input : {ndarray, dataframe} Original input of function. estimator : estimator instance Estimator with to get the output configuration from. Returns ------- output : {ndarray, dataframe} If the output config is "default" or the estimator is not configured for wrapping return `data_to_wrap` unchanged. If the output config is "pandas", return `data_to_wrap` as a pandas DataFrame.
_wrap_data_with_container
python
scikit-learn/scikit-learn
sklearn/utils/_set_output.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py
BSD-3-Clause
def _wrap_method_output(f, method): """Wrapper used by `_SetOutputMixin` to automatically wrap methods.""" @wraps(f) def wrapped(self, X, *args, **kwargs): data_to_wrap = f(self, X, *args, **kwargs) if isinstance(data_to_wrap, tuple): # only wrap the first output for cross decomposition return_tuple = ( _wrap_data_with_container(method, data_to_wrap[0], X, self), *data_to_wrap[1:], ) # Support for namedtuples `_make` is a documented API for namedtuples: # https://docs.python.org/3/library/collections.html#collections.somenamedtuple._make if hasattr(type(data_to_wrap), "_make"): return type(data_to_wrap)._make(return_tuple) return return_tuple return _wrap_data_with_container(method, data_to_wrap, X, self) return wrapped
Wrapper used by `_SetOutputMixin` to automatically wrap methods.
_wrap_method_output
python
scikit-learn/scikit-learn
sklearn/utils/_set_output.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py
BSD-3-Clause
def _auto_wrap_is_configured(estimator): """Return True if estimator is configured for auto-wrapping the transform method. `_SetOutputMixin` sets `_sklearn_auto_wrap_output_keys` to `set()` if auto wrapping is manually disabled. """ auto_wrap_output_keys = getattr(estimator, "_sklearn_auto_wrap_output_keys", set()) return ( hasattr(estimator, "get_feature_names_out") and "transform" in auto_wrap_output_keys )
Return True if estimator is configured for auto-wrapping the transform method. `_SetOutputMixin` sets `_sklearn_auto_wrap_output_keys` to `set()` if auto wrapping is manually disabled.
_auto_wrap_is_configured
python
scikit-learn/scikit-learn
sklearn/utils/_set_output.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py
BSD-3-Clause
def set_output(self, *, transform=None): """Set output container. See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py` for an example on how to use the API. Parameters ---------- transform : {"default", "pandas", "polars"}, default=None Configure output of `transform` and `fit_transform`. - `"default"`: Default output format of a transformer - `"pandas"`: DataFrame output - `"polars"`: Polars output - `None`: Transform configuration is unchanged .. versionadded:: 1.4 `"polars"` option was added. Returns ------- self : estimator instance Estimator instance. """ if transform is None: return self if not hasattr(self, "_sklearn_output_config"): self._sklearn_output_config = {} self._sklearn_output_config["transform"] = transform return self
Set output container. See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py` for an example on how to use the API. Parameters ---------- transform : {"default", "pandas", "polars"}, default=None Configure output of `transform` and `fit_transform`. - `"default"`: Default output format of a transformer - `"pandas"`: DataFrame output - `"polars"`: Polars output - `None`: Transform configuration is unchanged .. versionadded:: 1.4 `"polars"` option was added. Returns ------- self : estimator instance Estimator instance.
set_output
python
scikit-learn/scikit-learn
sklearn/utils/_set_output.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py
BSD-3-Clause
def _safe_set_output(estimator, *, transform=None): """Safely call estimator.set_output and error if it not available. This is used by meta-estimators to set the output for child estimators. Parameters ---------- estimator : estimator instance Estimator instance. transform : {"default", "pandas", "polars"}, default=None Configure output of the following estimator's methods: - `"transform"` - `"fit_transform"` If `None`, this operation is a no-op. Returns ------- estimator : estimator instance Estimator instance. """ set_output_for_transform = hasattr(estimator, "transform") or ( hasattr(estimator, "fit_transform") and transform is not None ) if not set_output_for_transform: # If estimator can not transform, then `set_output` does not need to be # called. return if not hasattr(estimator, "set_output"): raise ValueError( f"Unable to configure output for {estimator} because `set_output` " "is not available." ) return estimator.set_output(transform=transform)
Safely call estimator.set_output and error if it not available. This is used by meta-estimators to set the output for child estimators. Parameters ---------- estimator : estimator instance Estimator instance. transform : {"default", "pandas", "polars"}, default=None Configure output of the following estimator's methods: - `"transform"` - `"fit_transform"` If `None`, this operation is a no-op. Returns ------- estimator : estimator instance Estimator instance.
_safe_set_output
python
scikit-learn/scikit-learn
sklearn/utils/_set_output.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_set_output.py
BSD-3-Clause
def _get_sys_info(): """System information Returns ------- sys_info : dict system and Python version information """ python = sys.version.replace("\n", " ") blob = [ ("python", python), ("executable", sys.executable), ("machine", platform.platform()), ] return dict(blob)
System information Returns ------- sys_info : dict system and Python version information
_get_sys_info
python
scikit-learn/scikit-learn
sklearn/utils/_show_versions.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_show_versions.py
BSD-3-Clause
def _get_deps_info(): """Overview of the installed version of main dependencies This function does not import the modules to collect the version numbers but instead relies on standard Python package metadata. Returns ------- deps_info: dict version information on relevant Python libraries """ deps = [ "pip", "setuptools", "numpy", "scipy", "Cython", "pandas", "matplotlib", "joblib", "threadpoolctl", ] deps_info = { "sklearn": __version__, } from importlib.metadata import PackageNotFoundError, version for modname in deps: try: deps_info[modname] = version(modname) except PackageNotFoundError: deps_info[modname] = None return deps_info
Overview of the installed version of main dependencies This function does not import the modules to collect the version numbers but instead relies on standard Python package metadata. Returns ------- deps_info: dict version information on relevant Python libraries
_get_deps_info
python
scikit-learn/scikit-learn
sklearn/utils/_show_versions.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_show_versions.py
BSD-3-Clause
def show_versions(): """Print useful debugging information" .. versionadded:: 0.20 Examples -------- >>> from sklearn import show_versions >>> show_versions() # doctest: +SKIP """ sys_info = _get_sys_info() deps_info = _get_deps_info() print("\nSystem:") for k, stat in sys_info.items(): print("{k:>10}: {stat}".format(k=k, stat=stat)) print("\nPython dependencies:") for k, stat in deps_info.items(): print("{k:>13}: {stat}".format(k=k, stat=stat)) print( "\n{k}: {stat}".format( k="Built with OpenMP", stat=_openmp_parallelism_enabled() ) ) # show threadpoolctl results threadpool_results = threadpool_info() if threadpool_results: print() print("threadpoolctl info:") for i, result in enumerate(threadpool_results): for key, val in result.items(): print(f"{key:>15}: {val}") if i != len(threadpool_results) - 1: print()
Print useful debugging information" .. versionadded:: 0.20 Examples -------- >>> from sklearn import show_versions >>> show_versions() # doctest: +SKIP
show_versions
python
scikit-learn/scikit-learn
sklearn/utils/_show_versions.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_show_versions.py
BSD-3-Clause
def default_tags(estimator) -> Tags: """Get the default tags for an estimator. This ignores any ``__sklearn_tags__`` method that the estimator may have. If the estimator is a classifier or a regressor, ``target_tags.required`` will be set to ``True``, otherwise it will be set to ``False``. ``transformer_tags`` will be set to :class:`~.sklearn.utils. TransformerTags` if the estimator has a ``transform`` or ``fit_transform`` method, otherwise it will be set to ``None``. ``classifier_tags`` will be set to :class:`~.sklearn.utils.ClassifierTags` if the estimator is a classifier, otherwise it will be set to ``None``. a classifier, otherwise it will be set to ``None``. ``regressor_tags`` will be set to :class:`~.sklearn.utils.RegressorTags` if the estimator is a regressor, otherwise it will be set to ``None``. Parameters ---------- estimator : estimator object The estimator for which to get the default tags. Returns ------- tags : Tags The default tags for the estimator. """ est_is_classifier = getattr(estimator, "_estimator_type", None) == "classifier" est_is_regressor = getattr(estimator, "_estimator_type", None) == "regressor" target_required = est_is_classifier or est_is_regressor return Tags( estimator_type=getattr(estimator, "_estimator_type", None), target_tags=TargetTags(required=target_required), transformer_tags=( TransformerTags() if hasattr(estimator, "transform") or hasattr(estimator, "fit_transform") else None ), classifier_tags=ClassifierTags() if est_is_classifier else None, regressor_tags=RegressorTags() if est_is_regressor else None, )
Get the default tags for an estimator. This ignores any ``__sklearn_tags__`` method that the estimator may have. If the estimator is a classifier or a regressor, ``target_tags.required`` will be set to ``True``, otherwise it will be set to ``False``. ``transformer_tags`` will be set to :class:`~.sklearn.utils. TransformerTags` if the estimator has a ``transform`` or ``fit_transform`` method, otherwise it will be set to ``None``. ``classifier_tags`` will be set to :class:`~.sklearn.utils.ClassifierTags` if the estimator is a classifier, otherwise it will be set to ``None``. a classifier, otherwise it will be set to ``None``. ``regressor_tags`` will be set to :class:`~.sklearn.utils.RegressorTags` if the estimator is a regressor, otherwise it will be set to ``None``. Parameters ---------- estimator : estimator object The estimator for which to get the default tags. Returns ------- tags : Tags The default tags for the estimator.
default_tags
python
scikit-learn/scikit-learn
sklearn/utils/_tags.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_tags.py
BSD-3-Clause
def get_tags(estimator) -> Tags: """Get estimator tags. :class:`~sklearn.BaseEstimator` provides the estimator tags machinery. However, if an estimator does not inherit from this base class, we should fall-back to the default tags. For scikit-learn built-in estimators, we should still rely on `self.__sklearn_tags__()`. `get_tags(est)` should be used when we are not sure where `est` comes from: typically `get_tags(self.estimator)` where `self` is a meta-estimator, or in the common checks. .. versionadded:: 1.6 Parameters ---------- estimator : estimator object The estimator from which to get the tag. Returns ------- tags : :class:`~.sklearn.utils.Tags` The estimator tags. """ try: tags = estimator.__sklearn_tags__() except AttributeError as exc: # TODO(1.8): turn the warning into an error if "object has no attribute '__sklearn_tags__'" in str(exc): # Fall back to the default tags if the estimator does not # implement __sklearn_tags__. # In particular, workaround the regression reported in # https://github.com/scikit-learn/scikit-learn/issues/30479 # `__sklearn_tags__` is implemented by calling # `super().__sklearn_tags__()` but there is no `__sklearn_tags__` # method in the base class. Typically happens when only inheriting # from Mixins. warnings.warn( f"The following error was raised: {exc}. It seems that " "there are no classes that implement `__sklearn_tags__` " "in the MRO and/or all classes in the MRO call " "`super().__sklearn_tags__()`. Make sure to inherit from " "`BaseEstimator` which implements `__sklearn_tags__` (or " "alternatively define `__sklearn_tags__` but we don't recommend " "this approach). Note that `BaseEstimator` needs to be on the " "right side of other Mixins in the inheritance order. The " "default are now used instead since retrieving tags failed. " "This warning will be replaced by an error in 1.8.", category=DeprecationWarning, ) tags = default_tags(estimator) else: raise return tags
Get estimator tags. :class:`~sklearn.BaseEstimator` provides the estimator tags machinery. However, if an estimator does not inherit from this base class, we should fall-back to the default tags. For scikit-learn built-in estimators, we should still rely on `self.__sklearn_tags__()`. `get_tags(est)` should be used when we are not sure where `est` comes from: typically `get_tags(self.estimator)` where `self` is a meta-estimator, or in the common checks. .. versionadded:: 1.6 Parameters ---------- estimator : estimator object The estimator from which to get the tag. Returns ------- tags : :class:`~.sklearn.utils.Tags` The estimator tags.
get_tags
python
scikit-learn/scikit-learn
sklearn/utils/_tags.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_tags.py
BSD-3-Clause
def ignore_warnings(obj=None, category=Warning): """Context manager and decorator to ignore warnings. Note: Using this (in both variants) will clear all warnings from all python modules loaded. In case you need to test cross-module-warning-logging, this is not your tool of choice. Parameters ---------- obj : callable, default=None callable where you want to ignore the warnings. category : warning class, default=Warning The category to filter. If Warning, all categories will be muted. Examples -------- >>> import warnings >>> from sklearn.utils._testing import ignore_warnings >>> with ignore_warnings(): ... warnings.warn('buhuhuhu') >>> def nasty_warn(): ... warnings.warn('buhuhuhu') ... print(42) >>> ignore_warnings(nasty_warn)() 42 """ if isinstance(obj, type) and issubclass(obj, Warning): # Avoid common pitfall of passing category as the first positional # argument which result in the test not being run warning_name = obj.__name__ raise ValueError( "'obj' should be a callable where you want to ignore warnings. " "You passed a warning class instead: 'obj={warning_name}'. " "If you want to pass a warning class to ignore_warnings, " "you should use 'category={warning_name}'".format(warning_name=warning_name) ) elif callable(obj): return _IgnoreWarnings(category=category)(obj) else: return _IgnoreWarnings(category=category)
Context manager and decorator to ignore warnings. Note: Using this (in both variants) will clear all warnings from all python modules loaded. In case you need to test cross-module-warning-logging, this is not your tool of choice. Parameters ---------- obj : callable, default=None callable where you want to ignore the warnings. category : warning class, default=Warning The category to filter. If Warning, all categories will be muted. Examples -------- >>> import warnings >>> from sklearn.utils._testing import ignore_warnings >>> with ignore_warnings(): ... warnings.warn('buhuhuhu') >>> def nasty_warn(): ... warnings.warn('buhuhuhu') ... print(42) >>> ignore_warnings(nasty_warn)() 42
ignore_warnings
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def __call__(self, fn): """Decorator to catch and hide warnings without visual nesting.""" @wraps(fn) def wrapper(*args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore", self.category) return fn(*args, **kwargs) return wrapper
Decorator to catch and hide warnings without visual nesting.
__call__
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def assert_allclose( actual, desired, rtol=None, atol=0.0, equal_nan=True, err_msg="", verbose=True ): """dtype-aware variant of numpy.testing.assert_allclose This variant introspects the least precise floating point dtype in the input argument and automatically sets the relative tolerance parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64 in scikit-learn). `atol` is always left to 0. by default. It should be adjusted manually to an assertion-specific value in case there are null values expected in `desired`. The aggregate tolerance is `atol + rtol * abs(desired)`. Parameters ---------- actual : array_like Array obtained. desired : array_like Array desired. rtol : float, optional, default=None Relative tolerance. If None, it is set based on the provided arrays' dtypes. atol : float, optional, default=0. Absolute tolerance. equal_nan : bool, optional, default=True If True, NaNs will compare equal. err_msg : str, optional, default='' The error message to be printed in case of failure. verbose : bool, optional, default=True If True, the conflicting values are appended to the error message. Raises ------ AssertionError If actual and desired are not equal up to specified precision. See Also -------- numpy.testing.assert_allclose Examples -------- >>> import numpy as np >>> from sklearn.utils._testing import assert_allclose >>> x = [1e-5, 1e-3, 1e-1] >>> y = np.arccos(np.cos(x)) >>> assert_allclose(x, y, rtol=1e-5, atol=0) >>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32) >>> assert_allclose(a, 1e-5) """ dtypes = [] actual, desired = np.asanyarray(actual), np.asanyarray(desired) dtypes = [actual.dtype, desired.dtype] if rtol is None: rtols = [1e-4 if dtype == np.float32 else 1e-7 for dtype in dtypes] rtol = max(rtols) np_assert_allclose( actual, desired, rtol=rtol, atol=atol, equal_nan=equal_nan, err_msg=err_msg, verbose=verbose, )
dtype-aware variant of numpy.testing.assert_allclose This variant introspects the least precise floating point dtype in the input argument and automatically sets the relative tolerance parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64 in scikit-learn). `atol` is always left to 0. by default. It should be adjusted manually to an assertion-specific value in case there are null values expected in `desired`. The aggregate tolerance is `atol + rtol * abs(desired)`. Parameters ---------- actual : array_like Array obtained. desired : array_like Array desired. rtol : float, optional, default=None Relative tolerance. If None, it is set based on the provided arrays' dtypes. atol : float, optional, default=0. Absolute tolerance. equal_nan : bool, optional, default=True If True, NaNs will compare equal. err_msg : str, optional, default='' The error message to be printed in case of failure. verbose : bool, optional, default=True If True, the conflicting values are appended to the error message. Raises ------ AssertionError If actual and desired are not equal up to specified precision. See Also -------- numpy.testing.assert_allclose Examples -------- >>> import numpy as np >>> from sklearn.utils._testing import assert_allclose >>> x = [1e-5, 1e-3, 1e-1] >>> y = np.arccos(np.cos(x)) >>> assert_allclose(x, y, rtol=1e-5, atol=0) >>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32) >>> assert_allclose(a, 1e-5)
assert_allclose
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def assert_allclose_dense_sparse(x, y, rtol=1e-07, atol=1e-9, err_msg=""): """Assert allclose for sparse and dense data. Both x and y need to be either sparse or dense, they can't be mixed. Parameters ---------- x : {array-like, sparse matrix} First array to compare. y : {array-like, sparse matrix} Second array to compare. rtol : float, default=1e-07 relative tolerance; see numpy.allclose. atol : float, default=1e-9 absolute tolerance; see numpy.allclose. Note that the default here is more tolerant than the default for numpy.testing.assert_allclose, where atol=0. err_msg : str, default='' Error message to raise. """ if sp.sparse.issparse(x) and sp.sparse.issparse(y): x = x.tocsr() y = y.tocsr() x.sum_duplicates() y.sum_duplicates() assert_array_equal(x.indices, y.indices, err_msg=err_msg) assert_array_equal(x.indptr, y.indptr, err_msg=err_msg) assert_allclose(x.data, y.data, rtol=rtol, atol=atol, err_msg=err_msg) elif not sp.sparse.issparse(x) and not sp.sparse.issparse(y): # both dense assert_allclose(x, y, rtol=rtol, atol=atol, err_msg=err_msg) else: raise ValueError( "Can only compare two sparse matrices, not a sparse matrix and an array." )
Assert allclose for sparse and dense data. Both x and y need to be either sparse or dense, they can't be mixed. Parameters ---------- x : {array-like, sparse matrix} First array to compare. y : {array-like, sparse matrix} Second array to compare. rtol : float, default=1e-07 relative tolerance; see numpy.allclose. atol : float, default=1e-9 absolute tolerance; see numpy.allclose. Note that the default here is more tolerant than the default for numpy.testing.assert_allclose, where atol=0. err_msg : str, default='' Error message to raise.
assert_allclose_dense_sparse
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def _delete_folder(folder_path, warn=False): """Utility function to cleanup a temporary folder if still existing. Copy from joblib.pool (for independence). """ try: if os.path.exists(folder_path): # This can fail under windows, # but will succeed when called by atexit shutil.rmtree(folder_path) except OSError: if warn: warnings.warn("Could not delete temporary folder %s" % folder_path)
Utility function to cleanup a temporary folder if still existing. Copy from joblib.pool (for independence).
_delete_folder
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def create_memmap_backed_data(data, mmap_mode="r", return_folder=False): """ Parameters ---------- data mmap_mode : str, default='r' return_folder : bool, default=False """ temp_folder = tempfile.mkdtemp(prefix="sklearn_testing_") atexit.register(functools.partial(_delete_folder, temp_folder, warn=True)) filename = op.join(temp_folder, "data.pkl") joblib.dump(data, filename) memmap_backed_data = joblib.load(filename, mmap_mode=mmap_mode) result = ( memmap_backed_data if not return_folder else (memmap_backed_data, temp_folder) ) return result
Parameters ---------- data mmap_mode : str, default='r' return_folder : bool, default=False
create_memmap_backed_data
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def _get_func_name(func): """Get function full name. Parameters ---------- func : callable The function object. Returns ------- name : str The function name. """ parts = [] module = inspect.getmodule(func) if module: parts.append(module.__name__) qualname = func.__qualname__ if qualname != func.__name__: parts.append(qualname[: qualname.find(".")]) parts.append(func.__name__) return ".".join(parts)
Get function full name. Parameters ---------- func : callable The function object. Returns ------- name : str The function name.
_get_func_name
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def check_docstring_parameters(func, doc=None, ignore=None): """Helper to check docstring. Parameters ---------- func : callable The function object to test. doc : str, default=None Docstring if it is passed manually to the test. ignore : list, default=None Parameters to ignore. Returns ------- incorrect : list A list of string describing the incorrect results. """ from numpydoc import docscrape incorrect = [] ignore = [] if ignore is None else ignore func_name = _get_func_name(func) if not func_name.startswith("sklearn.") or func_name.startswith( "sklearn.externals" ): return incorrect # Don't check docstring for property-functions if inspect.isdatadescriptor(func): return incorrect # Don't check docstring for setup / teardown pytest functions if func_name.split(".")[-1] in ("setup_module", "teardown_module"): return incorrect # Dont check estimator_checks module if func_name.split(".")[2] == "estimator_checks": return incorrect # Get the arguments from the function signature param_signature = list(filter(lambda x: x not in ignore, _get_args(func))) # drop self if len(param_signature) > 0 and param_signature[0] == "self": param_signature.remove("self") # Analyze function's docstring if doc is None: records = [] with warnings.catch_warnings(record=True): warnings.simplefilter("error", UserWarning) try: doc = docscrape.FunctionDoc(func) except UserWarning as exp: if "potentially wrong underline length" in str(exp): # Catch warning raised as of numpydoc 1.2 when # the underline length for a section of a docstring # is not consistent. message = str(exp).split("\n")[:3] incorrect += [f"In function: {func_name}"] + message return incorrect records.append(str(exp)) except Exception as exp: incorrect += [func_name + " parsing error: " + str(exp)] return incorrect if len(records): raise RuntimeError("Error for %s:\n%s" % (func_name, records[0])) param_docs = [] for name, type_definition, param_doc in doc["Parameters"]: # Type hints are empty only if parameter name ended with : if not type_definition.strip(): if ":" in name and name[: name.index(":")][-1:].strip(): incorrect += [ func_name + " There was no space between the param name and colon (%r)" % name ] elif name.rstrip().endswith(":"): incorrect += [ func_name + " Parameter %r has an empty type spec. Remove the colon" % (name.lstrip()) ] # Create a list of parameters to compare with the parameters gotten # from the func signature if "*" not in name: param_docs.append(name.split(":")[0].strip("` ")) # If one of the docstring's parameters had an error then return that # incorrect message if len(incorrect) > 0: return incorrect # Remove the parameters that should be ignored from list param_docs = list(filter(lambda x: x not in ignore, param_docs)) # The following is derived from pytest, Copyright (c) 2004-2017 Holger # Krekel and others, Licensed under MIT License. See # https://github.com/pytest-dev/pytest message = [] for i in range(min(len(param_docs), len(param_signature))): if param_signature[i] != param_docs[i]: message += [ "There's a parameter name mismatch in function" " docstring w.r.t. function signature, at index %s" " diff: %r != %r" % (i, param_signature[i], param_docs[i]) ] break if len(param_signature) > len(param_docs): message += [ "Parameters in function docstring have less items w.r.t." " function signature, first missing item: %s" % param_signature[len(param_docs)] ] elif len(param_signature) < len(param_docs): message += [ "Parameters in function docstring have more items w.r.t." " function signature, first extra item: %s" % param_docs[len(param_signature)] ] # If there wasn't any difference in the parameters themselves between # docstring and signature including having the same length then return # empty list if len(message) == 0: return [] import difflib import pprint param_docs_formatted = pprint.pformat(param_docs).splitlines() param_signature_formatted = pprint.pformat(param_signature).splitlines() message += ["Full diff:"] message.extend( line.strip() for line in difflib.ndiff(param_signature_formatted, param_docs_formatted) ) incorrect.extend(message) # Prepend function name incorrect = ["In function: " + func_name] + incorrect return incorrect
Helper to check docstring. Parameters ---------- func : callable The function object to test. doc : str, default=None Docstring if it is passed manually to the test. ignore : list, default=None Parameters to ignore. Returns ------- incorrect : list A list of string describing the incorrect results.
check_docstring_parameters
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def _check_item_included(item_name, args): """Helper to check if item should be included in checking.""" if args.include is not True and item_name not in args.include: return False if args.exclude is not None and item_name in args.exclude: return False return True
Helper to check if item should be included in checking.
_check_item_included
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def _get_diff_msg(docstrings_grouped): """Get message showing the difference between type/desc docstrings of all objects. `docstrings_grouped` keys should be the type/desc docstrings and values are a list of objects with that docstring. Objects with the same type/desc docstring are thus grouped together. """ msg_diff = "" ref_str = "" ref_group = [] for docstring, group in docstrings_grouped.items(): if not ref_str and not ref_group: ref_str += docstring ref_group.extend(group) diff = list( context_diff( ref_str.split(), docstring.split(), fromfile=str(ref_group), tofile=str(group), n=8, ) ) # Add header msg_diff += "".join((diff[:3])) # Group consecutive 'diff' words to shorten error message for start, group in groupby(diff[3:], key=_diff_key): if start is None: msg_diff += "\n" + "\n".join(group) else: msg_diff += "\n" + start + " ".join(word[2:] for word in group) # Add new lines at end of diff, to separate comparisons msg_diff += "\n\n" return msg_diff
Get message showing the difference between type/desc docstrings of all objects. `docstrings_grouped` keys should be the type/desc docstrings and values are a list of objects with that docstring. Objects with the same type/desc docstring are thus grouped together.
_get_diff_msg
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def _check_consistency_items( items_docs, type_or_desc, section, n_objects, descr_regex_pattern="", ignore_types=tuple(), ): """Helper to check docstring consistency of all `items_docs`. If item is not present in all objects, checking is skipped and warning raised. If `regex` provided, match descriptions to all descriptions. Parameters ---------- items_doc : dict of dict of str Dictionary where the key is the string type or description, value is a dictionary where the key is "type description" or "description" and the value is a list of object names with the same string type or description. type_or_desc : {"type description", "description"} Whether to check type description or description between objects. section : {"Parameters", "Attributes", "Returns"} Name of the section type. n_objects : int Total number of objects. descr_regex_pattern : str, default="" Regex pattern to match for description of all objects. Ignored when `type_or_desc="type description". ignore_types : tuple of str, default=() Tuple of parameter/attribute/return names for which type description matching is ignored. Ignored when `type_or_desc="description". """ skipped = [] for item_name, docstrings_grouped in items_docs.items(): # If item not found in all objects, skip if sum([len(objs) for objs in docstrings_grouped.values()]) < n_objects: skipped.append(item_name) # If regex provided, match to all descriptions elif type_or_desc == "description" and descr_regex_pattern: not_matched = [] for docstring, group in docstrings_grouped.items(): if not re.search(descr_regex_pattern, docstring): not_matched.extend(group) if not_matched: msg = textwrap.fill( f"The description of {section[:-1]} '{item_name}' in {not_matched}" f" does not match 'descr_regex_pattern': {descr_regex_pattern} " ) raise AssertionError(msg) # Skip type checking for items in `ignore_types` elif type_or_desc == "type specification" and item_name in ignore_types: continue # Otherwise, if more than one key, docstrings not consistent between objects elif len(docstrings_grouped.keys()) > 1: msg_diff = _get_diff_msg(docstrings_grouped) obj_groups = " and ".join( str(group) for group in docstrings_grouped.values() ) msg = textwrap.fill( f"The {type_or_desc} of {section[:-1]} '{item_name}' is inconsistent " f"between {obj_groups}:" ) msg += msg_diff raise AssertionError(msg) if skipped: warnings.warn( f"Checking was skipped for {section}: {skipped} as they were " "not found in all objects." )
Helper to check docstring consistency of all `items_docs`. If item is not present in all objects, checking is skipped and warning raised. If `regex` provided, match descriptions to all descriptions. Parameters ---------- items_doc : dict of dict of str Dictionary where the key is the string type or description, value is a dictionary where the key is "type description" or "description" and the value is a list of object names with the same string type or description. type_or_desc : {"type description", "description"} Whether to check type description or description between objects. section : {"Parameters", "Attributes", "Returns"} Name of the section type. n_objects : int Total number of objects. descr_regex_pattern : str, default="" Regex pattern to match for description of all objects. Ignored when `type_or_desc="type description". ignore_types : tuple of str, default=() Tuple of parameter/attribute/return names for which type description matching is ignored. Ignored when `type_or_desc="description".
_check_consistency_items
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def assert_docstring_consistency( objects, include_params=False, exclude_params=None, include_attrs=False, exclude_attrs=None, include_returns=False, exclude_returns=None, descr_regex_pattern=None, ignore_types=tuple(), ): r"""Check consistency between docstring parameters/attributes/returns of objects. Checks if parameters/attributes/returns have the same type specification and description (ignoring whitespace) across `objects`. Intended to be used for related classes/functions/data descriptors. Entries that do not appear across all `objects` are ignored. Parameters ---------- objects : list of {classes, functions, data descriptors} Objects to check. Objects may be classes, functions or data descriptors with docstrings that can be parsed by numpydoc. include_params : list of str or bool, default=False List of parameters to be included. If True, all parameters are included, if False, checking is skipped for parameters. Can only be set if `exclude_params` is None. exclude_params : list of str or None, default=None List of parameters to be excluded. If None, no parameters are excluded. Can only be set if `include_params` is True. include_attrs : list of str or bool, default=False List of attributes to be included. If True, all attributes are included, if False, checking is skipped for attributes. Can only be set if `exclude_attrs` is None. exclude_attrs : list of str or None, default=None List of attributes to be excluded. If None, no attributes are excluded. Can only be set if `include_attrs` is True. include_returns : list of str or bool, default=False List of returns to be included. If True, all returns are included, if False, checking is skipped for returns. Can only be set if `exclude_returns` is None. exclude_returns : list of str or None, default=None List of returns to be excluded. If None, no returns are excluded. Can only be set if `include_returns` is True. descr_regex_pattern : str, default=None Regular expression to match to all descriptions of included parameters/attributes/returns. If None, will revert to default behavior of comparing descriptions between objects. ignore_types : tuple of str, default=tuple() Tuple of parameter/attribute/return names to exclude from type description matching between objects. Examples -------- >>> from sklearn.metrics import (accuracy_score, classification_report, ... mean_absolute_error, mean_squared_error, median_absolute_error) >>> from sklearn.utils._testing import assert_docstring_consistency ... # doctest: +SKIP >>> assert_docstring_consistency([mean_absolute_error, mean_squared_error], ... include_params=['y_true', 'y_pred', 'sample_weight']) # doctest: +SKIP >>> assert_docstring_consistency([median_absolute_error, mean_squared_error], ... include_params=True) # doctest: +SKIP >>> assert_docstring_consistency([accuracy_score, classification_report], ... include_params=["y_true"], ... descr_regex_pattern=r"Ground truth \(correct\) (labels|target values)") ... # doctest: +SKIP """ from numpydoc.docscrape import NumpyDocString Args = namedtuple("args", ["include", "exclude", "arg_name"]) def _create_args(include, exclude, arg_name, section_name): if exclude and include is not True: raise TypeError( f"The 'exclude_{arg_name}' argument can be set only when the " f"'include_{arg_name}' argument is True." ) if include is False: return {} return {section_name: Args(include, exclude, arg_name)} section_args = { **_create_args(include_params, exclude_params, "params", "Parameters"), **_create_args(include_attrs, exclude_attrs, "attrs", "Attributes"), **_create_args(include_returns, exclude_returns, "returns", "Returns"), } objects_doc = dict() for obj in objects: if ( inspect.isdatadescriptor(obj) or inspect.isfunction(obj) or inspect.isclass(obj) ): objects_doc[obj.__name__] = NumpyDocString(inspect.getdoc(obj)) else: raise TypeError( "All 'objects' must be one of: function, class or descriptor, " f"got a: {type(obj)}." ) n_objects = len(objects) for section, args in section_args.items(): type_items = defaultdict(lambda: defaultdict(list)) desc_items = defaultdict(lambda: defaultdict(list)) for obj_name, obj_doc in objects_doc.items(): for item_name, type_def, desc in obj_doc[section]: if _check_item_included(item_name, args): # Normalize white space type_def = " ".join(type_def.strip().split()) desc = " ".join(chain.from_iterable(line.split() for line in desc)) # Use string type/desc as key, to group consistent objs together type_items[item_name][type_def].append(obj_name) desc_items[item_name][desc].append(obj_name) _check_consistency_items( type_items, "type specification", section, n_objects, ignore_types=ignore_types, ) _check_consistency_items( desc_items, "description", section, n_objects, descr_regex_pattern=descr_regex_pattern, )
Check consistency between docstring parameters/attributes/returns of objects. Checks if parameters/attributes/returns have the same type specification and description (ignoring whitespace) across `objects`. Intended to be used for related classes/functions/data descriptors. Entries that do not appear across all `objects` are ignored. Parameters ---------- objects : list of {classes, functions, data descriptors} Objects to check. Objects may be classes, functions or data descriptors with docstrings that can be parsed by numpydoc. include_params : list of str or bool, default=False List of parameters to be included. If True, all parameters are included, if False, checking is skipped for parameters. Can only be set if `exclude_params` is None. exclude_params : list of str or None, default=None List of parameters to be excluded. If None, no parameters are excluded. Can only be set if `include_params` is True. include_attrs : list of str or bool, default=False List of attributes to be included. If True, all attributes are included, if False, checking is skipped for attributes. Can only be set if `exclude_attrs` is None. exclude_attrs : list of str or None, default=None List of attributes to be excluded. If None, no attributes are excluded. Can only be set if `include_attrs` is True. include_returns : list of str or bool, default=False List of returns to be included. If True, all returns are included, if False, checking is skipped for returns. Can only be set if `exclude_returns` is None. exclude_returns : list of str or None, default=None List of returns to be excluded. If None, no returns are excluded. Can only be set if `include_returns` is True. descr_regex_pattern : str, default=None Regular expression to match to all descriptions of included parameters/attributes/returns. If None, will revert to default behavior of comparing descriptions between objects. ignore_types : tuple of str, default=tuple() Tuple of parameter/attribute/return names to exclude from type description matching between objects. Examples -------- >>> from sklearn.metrics import (accuracy_score, classification_report, ... mean_absolute_error, mean_squared_error, median_absolute_error) >>> from sklearn.utils._testing import assert_docstring_consistency ... # doctest: +SKIP >>> assert_docstring_consistency([mean_absolute_error, mean_squared_error], ... include_params=['y_true', 'y_pred', 'sample_weight']) # doctest: +SKIP >>> assert_docstring_consistency([median_absolute_error, mean_squared_error], ... include_params=True) # doctest: +SKIP >>> assert_docstring_consistency([accuracy_score, classification_report], ... include_params=["y_true"], ... descr_regex_pattern=r"Ground truth \(correct\) (labels|target values)") ... # doctest: +SKIP
assert_docstring_consistency
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def assert_run_python_script_without_output(source_code, pattern=".+", timeout=60): """Utility to check assertions in an independent Python subprocess. The script provided in the source code should return 0 and the stdtout + stderr should not match the pattern `pattern`. This is a port from cloudpickle https://github.com/cloudpipe/cloudpickle Parameters ---------- source_code : str The Python source code to execute. pattern : str Pattern that the stdout + stderr should not match. By default, unless stdout + stderr are both empty, an error will be raised. timeout : int, default=60 Time in seconds before timeout. """ fd, source_file = tempfile.mkstemp(suffix="_src_test_sklearn.py") os.close(fd) try: with open(source_file, "wb") as f: f.write(source_code.encode("utf-8")) cmd = [sys.executable, source_file] cwd = op.normpath(op.join(op.dirname(sklearn.__file__), "..")) env = os.environ.copy() try: env["PYTHONPATH"] = os.pathsep.join([cwd, env["PYTHONPATH"]]) except KeyError: env["PYTHONPATH"] = cwd kwargs = {"cwd": cwd, "stderr": STDOUT, "env": env} # If coverage is running, pass the config file to the subprocess coverage_rc = os.environ.get("COVERAGE_PROCESS_START") if coverage_rc: kwargs["env"]["COVERAGE_PROCESS_START"] = coverage_rc kwargs["timeout"] = timeout try: try: out = check_output(cmd, **kwargs) except CalledProcessError as e: raise RuntimeError( "script errored with output:\n%s" % e.output.decode("utf-8") ) out = out.decode("utf-8") if re.search(pattern, out): if pattern == ".+": expectation = "Expected no output" else: expectation = f"The output was not supposed to match {pattern!r}" message = f"{expectation}, got the following output instead: {out!r}" raise AssertionError(message) except TimeoutExpired as e: raise RuntimeError( "script timeout, output so far:\n%s" % e.output.decode("utf-8") ) finally: os.unlink(source_file)
Utility to check assertions in an independent Python subprocess. The script provided in the source code should return 0 and the stdtout + stderr should not match the pattern `pattern`. This is a port from cloudpickle https://github.com/cloudpipe/cloudpickle Parameters ---------- source_code : str The Python source code to execute. pattern : str Pattern that the stdout + stderr should not match. By default, unless stdout + stderr are both empty, an error will be raised. timeout : int, default=60 Time in seconds before timeout.
assert_run_python_script_without_output
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def _convert_container( container, constructor_name, columns_name=None, dtype=None, minversion=None, categorical_feature_names=None, ): """Convert a given container to a specific array-like with a dtype. Parameters ---------- container : array-like The container to convert. constructor_name : {"list", "tuple", "array", "sparse", "dataframe", \ "series", "index", "slice", "sparse_csr", "sparse_csc", \ "sparse_csr_array", "sparse_csc_array", "pyarrow", "polars", \ "polars_series"} The type of the returned container. columns_name : index or array-like, default=None For pandas container supporting `columns_names`, it will affect specific names. dtype : dtype, default=None Force the dtype of the container. Does not apply to `"slice"` container. minversion : str, default=None Minimum version for package to install. categorical_feature_names : list of str, default=None List of column names to cast to categorical dtype. Returns ------- converted_container """ if constructor_name == "list": if dtype is None: return list(container) else: return np.asarray(container, dtype=dtype).tolist() elif constructor_name == "tuple": if dtype is None: return tuple(container) else: return tuple(np.asarray(container, dtype=dtype).tolist()) elif constructor_name == "array": return np.asarray(container, dtype=dtype) elif constructor_name in ("pandas", "dataframe"): pd = pytest.importorskip("pandas", minversion=minversion) result = pd.DataFrame(container, columns=columns_name, dtype=dtype, copy=False) if categorical_feature_names is not None: for col_name in categorical_feature_names: result[col_name] = result[col_name].astype("category") return result elif constructor_name == "pyarrow": pa = pytest.importorskip("pyarrow", minversion=minversion) array = np.asarray(container) array = array[:, None] if array.ndim == 1 else array if columns_name is None: columns_name = [f"col{i}" for i in range(array.shape[1])] data = {name: array[:, i] for i, name in enumerate(columns_name)} result = pa.Table.from_pydict(data) if categorical_feature_names is not None: for col_idx, col_name in enumerate(result.column_names): if col_name in categorical_feature_names: result = result.set_column( col_idx, col_name, result.column(col_name).dictionary_encode() ) return result elif constructor_name == "polars": pl = pytest.importorskip("polars", minversion=minversion) result = pl.DataFrame(container, schema=columns_name, orient="row") if categorical_feature_names is not None: for col_name in categorical_feature_names: result = result.with_columns(pl.col(col_name).cast(pl.Categorical)) return result elif constructor_name == "series": pd = pytest.importorskip("pandas", minversion=minversion) return pd.Series(container, dtype=dtype) elif constructor_name == "pyarrow_array": pa = pytest.importorskip("pyarrow", minversion=minversion) return pa.array(container) elif constructor_name == "polars_series": pl = pytest.importorskip("polars", minversion=minversion) return pl.Series(values=container) elif constructor_name == "index": pd = pytest.importorskip("pandas", minversion=minversion) return pd.Index(container, dtype=dtype) elif constructor_name == "slice": return slice(container[0], container[1]) elif "sparse" in constructor_name: if not sp.sparse.issparse(container): # For scipy >= 1.13, sparse array constructed from 1d array may be # 1d or raise an exception. To avoid this, we make sure that the # input container is 2d. For more details, see # https://github.com/scipy/scipy/pull/18530#issuecomment-1878005149 container = np.atleast_2d(container) if constructor_name in ("sparse", "sparse_csr"): # sparse and sparse_csr are equivalent for legacy reasons return sp.sparse.csr_matrix(container, dtype=dtype) elif constructor_name == "sparse_csr_array": return sp.sparse.csr_array(container, dtype=dtype) elif constructor_name == "sparse_csc": return sp.sparse.csc_matrix(container, dtype=dtype) elif constructor_name == "sparse_csc_array": return sp.sparse.csc_array(container, dtype=dtype)
Convert a given container to a specific array-like with a dtype. Parameters ---------- container : array-like The container to convert. constructor_name : {"list", "tuple", "array", "sparse", "dataframe", "series", "index", "slice", "sparse_csr", "sparse_csc", "sparse_csr_array", "sparse_csc_array", "pyarrow", "polars", "polars_series"} The type of the returned container. columns_name : index or array-like, default=None For pandas container supporting `columns_names`, it will affect specific names. dtype : dtype, default=None Force the dtype of the container. Does not apply to `"slice"` container. minversion : str, default=None Minimum version for package to install. categorical_feature_names : list of str, default=None List of column names to cast to categorical dtype. Returns ------- converted_container
_convert_container
python
scikit-learn/scikit-learn
sklearn/utils/_testing.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_testing.py
BSD-3-Clause
def _attach_unique(y): """Attach unique values of y to y and return the result. The result is a view of y, and the metadata (unique) is not attached to y. """ if not isinstance(y, np.ndarray): return y try: # avoid recalculating unique in nested calls. if "unique" in y.dtype.metadata: return y except (AttributeError, TypeError): pass unique = np.unique(y) unique_dtype = np.dtype(y.dtype, metadata={"unique": unique}) return y.view(dtype=unique_dtype)
Attach unique values of y to y and return the result. The result is a view of y, and the metadata (unique) is not attached to y.
_attach_unique
python
scikit-learn/scikit-learn
sklearn/utils/_unique.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_unique.py
BSD-3-Clause
def attach_unique(*ys, return_tuple=False): """Attach unique values of ys to ys and return the results. The result is a view of y, and the metadata (unique) is not attached to y. IMPORTANT: The output of this function should NEVER be returned in functions. This is to avoid this pattern: .. code:: python y = np.array([1, 2, 3]) y = attach_unique(y) y[1] = -1 # now np.unique(y) will be different from cached_unique(y) Parameters ---------- *ys : sequence of array-like Input data arrays. return_tuple : bool, default=False If True, always return a tuple even if there is only one array. Returns ------- ys : tuple of array-like or array-like Input data with unique values attached. """ res = tuple(_attach_unique(y) for y in ys) if len(res) == 1 and not return_tuple: return res[0] return res
Attach unique values of ys to ys and return the results. The result is a view of y, and the metadata (unique) is not attached to y. IMPORTANT: The output of this function should NEVER be returned in functions. This is to avoid this pattern: .. code:: python y = np.array([1, 2, 3]) y = attach_unique(y) y[1] = -1 # now np.unique(y) will be different from cached_unique(y) Parameters ---------- *ys : sequence of array-like Input data arrays. return_tuple : bool, default=False If True, always return a tuple even if there is only one array. Returns ------- ys : tuple of array-like or array-like Input data with unique values attached.
attach_unique
python
scikit-learn/scikit-learn
sklearn/utils/_unique.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_unique.py
BSD-3-Clause
def _cached_unique(y, xp=None): """Return the unique values of y. Use the cached values from dtype.metadata if present. This function does NOT cache the values in y, i.e. it doesn't change y. Call `attach_unique` to attach the unique values to y. """ try: if y.dtype.metadata is not None and "unique" in y.dtype.metadata: return y.dtype.metadata["unique"] except AttributeError: # in case y is not a numpy array pass xp, _ = get_namespace(y, xp=xp) return xp.unique_values(y)
Return the unique values of y. Use the cached values from dtype.metadata if present. This function does NOT cache the values in y, i.e. it doesn't change y. Call `attach_unique` to attach the unique values to y.
_cached_unique
python
scikit-learn/scikit-learn
sklearn/utils/_unique.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_unique.py
BSD-3-Clause
def cached_unique(*ys, xp=None): """Return the unique values of ys. Use the cached values from dtype.metadata if present. This function does NOT cache the values in y, i.e. it doesn't change y. Call `attach_unique` to attach the unique values to y. Parameters ---------- *ys : sequence of array-like Input data arrays. xp : module, default=None Precomputed array namespace module. When passed, typically from a caller that has already performed inspection of its own inputs, skips array namespace inspection. Returns ------- res : tuple of array-like or array-like Unique values of ys. """ res = tuple(_cached_unique(y, xp=xp) for y in ys) if len(res) == 1: return res[0] return res
Return the unique values of ys. Use the cached values from dtype.metadata if present. This function does NOT cache the values in y, i.e. it doesn't change y. Call `attach_unique` to attach the unique values to y. Parameters ---------- *ys : sequence of array-like Input data arrays. xp : module, default=None Precomputed array namespace module. When passed, typically from a caller that has already performed inspection of its own inputs, skips array namespace inspection. Returns ------- res : tuple of array-like or array-like Unique values of ys.
cached_unique
python
scikit-learn/scikit-learn
sklearn/utils/_unique.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_unique.py
BSD-3-Clause
def _message_with_time(source, message, time): """Create one line message for logging purposes. Parameters ---------- source : str String indicating the source or the reference of the message. message : str Short message. time : int Time in seconds. """ start_message = "[%s] " % source # adapted from joblib.logger.short_format_time without the Windows -.1s # adjustment if time > 60: time_str = "%4.1fmin" % (time / 60) else: time_str = " %5.1fs" % time end_message = " %s, total=%s" % (message, time_str) dots_len = 70 - len(start_message) - len(end_message) return "%s%s%s" % (start_message, dots_len * ".", end_message)
Create one line message for logging purposes. Parameters ---------- source : str String indicating the source or the reference of the message. message : str Short message. time : int Time in seconds.
_message_with_time
python
scikit-learn/scikit-learn
sklearn/utils/_user_interface.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_user_interface.py
BSD-3-Clause
def _print_elapsed_time(source, message=None): """Log elapsed time to stdout when the context is exited. Parameters ---------- source : str String indicating the source or the reference of the message. message : str, default=None Short message. If None, nothing will be printed. Returns ------- context_manager Prints elapsed time upon exit if verbose. """ if message is None: yield else: start = timeit.default_timer() yield print(_message_with_time(source, message, timeit.default_timer() - start))
Log elapsed time to stdout when the context is exited. Parameters ---------- source : str String indicating the source or the reference of the message. message : str, default=None Short message. If None, nothing will be printed. Returns ------- context_manager Prints elapsed time upon exit if verbose.
_print_elapsed_time
python
scikit-learn/scikit-learn
sklearn/utils/_user_interface.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/_user_interface.py
BSD-3-Clause
def test_get_namespace_ndarray_creation_device(): """Check expected behavior with device and creation functions.""" X = numpy.asarray([1, 2, 3]) xp_out, _ = get_namespace(X) full_array = xp_out.full(10, fill_value=2.0, device="cpu") assert_allclose(full_array, [2.0] * 10) with pytest.raises(ValueError, match="Unsupported device"): xp_out.zeros(10, device="cuda")
Check expected behavior with device and creation functions.
test_get_namespace_ndarray_creation_device
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_array_api.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_array_api.py
BSD-3-Clause
def test_asarray_with_order(array_api): """Test _asarray_with_order passes along order for NumPy arrays.""" xp = pytest.importorskip(array_api) X = xp.asarray([1.2, 3.4, 5.1]) X_new = _asarray_with_order(X, order="F", xp=xp) X_new_np = numpy.asarray(X_new) assert X_new_np.flags["F_CONTIGUOUS"]
Test _asarray_with_order passes along order for NumPy arrays.
test_asarray_with_order
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_array_api.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_array_api.py
BSD-3-Clause
def test_convert_estimator_to_array_api(): """Convert estimator attributes to ArrayAPI arrays.""" xp = pytest.importorskip("array_api_strict") X_np = numpy.asarray([[1.3, 4.5]]) est = SimpleEstimator().fit(X_np) new_est = _estimator_with_converted_arrays(est, lambda array: xp.asarray(array)) assert hasattr(new_est.X_, "__array_namespace__")
Convert estimator attributes to ArrayAPI arrays.
test_convert_estimator_to_array_api
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_array_api.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_array_api.py
BSD-3-Clause
def test_bunch_attribute_deprecation(): """Check that bunch raises deprecation message with `__getattr__`.""" bunch = Bunch() values = np.asarray([1, 2, 3]) msg = ( "Key: 'values', is deprecated in 1.3 and will be " "removed in 1.5. Please use 'grid_values' instead" ) bunch._set_deprecated( values, new_key="grid_values", deprecated_key="values", warning_message=msg ) with warnings.catch_warnings(): # Does not warn for "grid_values" warnings.simplefilter("error") v = bunch["grid_values"] assert v is values with pytest.warns(FutureWarning, match=msg): # Warns for "values" v = bunch["values"] assert v is values
Check that bunch raises deprecation message with `__getattr__`.
test_bunch_attribute_deprecation
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_bunch.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_bunch.py
BSD-3-Clause
def test_get_chunk_n_rows_warns(): """Check that warning is raised when working_memory is too low.""" row_bytes = 1024 * 1024 + 1 max_n_rows = None working_memory = 1 expected = 1 warn_msg = ( "Could not adhere to working_memory config. Currently 1MiB, 2MiB required." ) with pytest.warns(UserWarning, match=warn_msg): actual = get_chunk_n_rows( row_bytes=row_bytes, max_n_rows=max_n_rows, working_memory=working_memory, ) assert actual == expected assert type(actual) is type(expected) with config_context(working_memory=working_memory): with pytest.warns(UserWarning, match=warn_msg): actual = get_chunk_n_rows(row_bytes=row_bytes, max_n_rows=max_n_rows) assert actual == expected assert type(actual) is type(expected)
Check that warning is raised when working_memory is too low.
test_get_chunk_n_rows_warns
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_chunking.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_chunking.py
BSD-3-Clause
def test_class_weight_does_not_contains_more_classes(): """Check that class_weight can contain more labels than in y. Non-regression test for #22413 """ tree = DecisionTreeClassifier(class_weight={0: 1, 1: 10, 2: 20}) # Does not raise tree.fit([[0, 0, 1], [1, 0, 1], [1, 2, 0]], [0, 0, 1])
Check that class_weight can contain more labels than in y. Non-regression test for #22413
test_class_weight_does_not_contains_more_classes
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_class_weight.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_class_weight.py
BSD-3-Clause
def test_compute_sample_weight_sparse(csc_container): """Check that we can compute weight for sparse `y`.""" y = csc_container(np.asarray([[0], [1], [1]])) sample_weight = compute_sample_weight("balanced", y) assert_allclose(sample_weight, [1.5, 0.75, 0.75])
Check that we can compute weight for sparse `y`.
test_compute_sample_weight_sparse
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_class_weight.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_class_weight.py
BSD-3-Clause
def test_check_estimator_with_class_removed(): """Test that passing a class instead of an instance fails.""" msg = "Passing a class was deprecated" with raises(TypeError, match=msg): check_estimator(LogisticRegression)
Test that passing a class instead of an instance fails.
test_check_estimator_with_class_removed
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_mutable_default_params(): """Test that constructor cannot have mutable default parameters.""" msg = ( "Parameter 'p' of estimator 'HasMutableParameters' is of type " "object which is not allowed" ) # check that the "default_constructible" test checks for mutable parameters check_parameters_default_constructible( "Immutable", HasImmutableParameters() ) # should pass with raises(AssertionError, match=msg): check_parameters_default_constructible("Mutable", HasMutableParameters())
Test that constructor cannot have mutable default parameters.
test_mutable_default_params
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_check_set_params(): """Check set_params doesn't fail and sets the right values.""" # check that values returned by get_params match set_params msg = "get_params result does not match what was passed to set_params" with raises(AssertionError, match=msg): check_set_params("test", ModifiesValueInsteadOfRaisingError()) with warnings.catch_warnings(record=True) as records: check_set_params("test", RaisesErrorInSetParams()) assert UserWarning in [rec.category for rec in records] with raises(AssertionError, match=msg): check_set_params("test", ModifiesAnotherValue())
Check set_params doesn't fail and sets the right values.
test_check_set_params
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_check_estimator_not_fail_fast(): """Check the contents of the results returned with on_fail!="raise". This results should contain details about the observed failures, expected or not. """ check_results = check_estimator(BaseEstimator(), on_fail=None) assert isinstance(check_results, list) assert len(check_results) > 0 assert all( isinstance(item, dict) and set(item.keys()) == { "estimator", "check_name", "exception", "status", "expected_to_fail", "expected_to_fail_reason", } for item in check_results ) # Some tests are expected to fail, some are expected to pass. assert any(item["status"] == "failed" for item in check_results) assert any(item["status"] == "passed" for item in check_results)
Check the contents of the results returned with on_fail!="raise". This results should contain details about the observed failures, expected or not.
test_check_estimator_not_fail_fast
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_check_estimator_sparse_tag(): """Test that check_estimator_sparse_tag raises error when sparse tag is misaligned.""" class EstimatorWithSparseConfig(BaseEstimator): def __init__(self, tag_sparse, accept_sparse, fit_error=None): self.tag_sparse = tag_sparse self.accept_sparse = accept_sparse self.fit_error = fit_error def fit(self, X, y=None): if self.fit_error: raise self.fit_error validate_data(self, X, y, accept_sparse=self.accept_sparse) return self def __sklearn_tags__(self): tags = super().__sklearn_tags__() tags.input_tags.sparse = self.tag_sparse return tags test_cases = [ {"tag_sparse": True, "accept_sparse": True, "error_type": None}, {"tag_sparse": False, "accept_sparse": False, "error_type": None}, {"tag_sparse": False, "accept_sparse": True, "error_type": AssertionError}, {"tag_sparse": True, "accept_sparse": False, "error_type": AssertionError}, ] for test_case in test_cases: estimator = EstimatorWithSparseConfig( test_case["tag_sparse"], test_case["accept_sparse"], ) if test_case["error_type"] is None: check_estimator_sparse_tag(estimator.__class__.__name__, estimator) else: with raises(test_case["error_type"]): check_estimator_sparse_tag(estimator.__class__.__name__, estimator) # estimator `tag_sparse=accept_sparse=False` fails on sparse data # but does not raise the appropriate error for fit_error in [TypeError("unexpected error"), KeyError("other error")]: estimator = EstimatorWithSparseConfig(False, False, fit_error) with raises(AssertionError): check_estimator_sparse_tag(estimator.__class__.__name__, estimator)
Test that check_estimator_sparse_tag raises error when sparse tag is misaligned.
test_check_estimator_sparse_tag
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def run_tests_without_pytest(): """Runs the tests in this file without using pytest.""" main_module = sys.modules["__main__"] test_functions = [ getattr(main_module, name) for name in dir(main_module) if name.startswith("test_") ] test_cases = [unittest.FunctionTestCase(fn) for fn in test_functions] suite = unittest.TestSuite() suite.addTests(test_cases) runner = unittest.TextTestRunner() runner.run(suite)
Runs the tests in this file without using pytest.
run_tests_without_pytest
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_xfail_count_with_no_fast_fail(): """Test that the right number of xfail warnings are raised when on_fail is "warn". It also checks the number of raised EstimatorCheckFailedWarning, and checks the output of check_estimator. """ est = NuSVC() expected_failed_checks = _get_expected_failed_checks(est) # This is to make sure we test a class that has some expected failures assert len(expected_failed_checks) > 0 with warnings.catch_warnings(record=True) as records: logs = check_estimator( est, expected_failed_checks=expected_failed_checks, on_fail="warn", ) xfail_warns = [w for w in records if w.category != SkipTestWarning] assert all([rec.category == EstimatorCheckFailedWarning for rec in xfail_warns]) assert len(xfail_warns) == len(expected_failed_checks) xfailed = [log for log in logs if log["status"] == "xfail"] assert len(xfailed) == len(expected_failed_checks)
Test that the right number of xfail warnings are raised when on_fail is "warn". It also checks the number of raised EstimatorCheckFailedWarning, and checks the output of check_estimator.
test_xfail_count_with_no_fast_fail
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_check_estimator_callback(): """Test that the callback is called with the right arguments.""" call_count = {"xfail": 0, "skipped": 0, "passed": 0, "failed": 0} def callback( *, estimator, check_name, exception, status, expected_to_fail, expected_to_fail_reason, ): assert status in ("xfail", "skipped", "passed", "failed") nonlocal call_count call_count[status] += 1 est = NuSVC() expected_failed_checks = _get_expected_failed_checks(est) # This is to make sure we test a class that has some expected failures assert len(expected_failed_checks) > 0 with warnings.catch_warnings(record=True): check_estimator( est, expected_failed_checks=expected_failed_checks, on_fail=None, callback=callback, ) all_checks_count = len(list(estimator_checks_generator(est, legacy=True))) assert call_count["xfail"] == len(expected_failed_checks) assert call_count["passed"] > 0 assert call_count["failed"] == 0 assert call_count["skipped"] == ( all_checks_count - call_count["xfail"] - call_count["passed"] )
Test that the callback is called with the right arguments.
test_check_estimator_callback
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_check_outlier_contamination(): """Check the test for the contamination parameter in the outlier detectors.""" # Without any parameter constraints, the estimator will early exit the test by # returning None. class OutlierDetectorWithoutConstraint(OutlierMixin, BaseEstimator): """Outlier detector without parameter validation.""" def __init__(self, contamination=0.1): self.contamination = contamination def fit(self, X, y=None, sample_weight=None): return self # pragma: no cover def predict(self, X, y=None): return np.ones(X.shape[0]) detector = OutlierDetectorWithoutConstraint() assert check_outlier_contamination(detector.__class__.__name__, detector) is None # Now, we check that with the parameter constraints, the test should only be valid # if an Interval constraint with bound in [0, 1] is provided. class OutlierDetectorWithConstraint(OutlierDetectorWithoutConstraint): _parameter_constraints = {"contamination": [StrOptions({"auto"})]} detector = OutlierDetectorWithConstraint() err_msg = "contamination constraints should contain a Real Interval constraint." with raises(AssertionError, match=err_msg): check_outlier_contamination(detector.__class__.__name__, detector) # Add a correct interval constraint and check that the test passes. OutlierDetectorWithConstraint._parameter_constraints["contamination"] = [ Interval(Real, 0, 0.5, closed="right") ] detector = OutlierDetectorWithConstraint() check_outlier_contamination(detector.__class__.__name__, detector) incorrect_intervals = [ Interval(Integral, 0, 1, closed="right"), # not an integral interval Interval(Real, -1, 1, closed="right"), # lower bound is negative Interval(Real, 0, 2, closed="right"), # upper bound is greater than 1 Interval(Real, 0, 0.5, closed="left"), # lower bound include 0 ] err_msg = r"contamination constraint should be an interval in \(0, 0.5\]" for interval in incorrect_intervals: OutlierDetectorWithConstraint._parameter_constraints["contamination"] = [ interval ] detector = OutlierDetectorWithConstraint() with raises(AssertionError, match=err_msg): check_outlier_contamination(detector.__class__.__name__, detector)
Check the test for the contamination parameter in the outlier detectors.
test_check_outlier_contamination
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_check_estimator_cloneable_error(): """Check that the right error is raised when the estimator is not cloneable.""" class NotCloneable(BaseEstimator): def __sklearn_clone__(self): raise NotImplementedError("This estimator is not cloneable.") estimator = NotCloneable() msg = "Cloning of .* failed with error" with raises(AssertionError, match=msg): check_estimator_cloneable("NotCloneable", estimator)
Check that the right error is raised when the estimator is not cloneable.
test_check_estimator_cloneable_error
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_estimator_repr_error(): """Check that the right error is raised when the estimator does not have a repr.""" class NotRepr(BaseEstimator): def __repr__(self): raise NotImplementedError("This estimator does not have a repr.") estimator = NotRepr() msg = "Repr of .* failed with error" with raises(AssertionError, match=msg): check_estimator_repr("NotRepr", estimator)
Check that the right error is raised when the estimator does not have a repr.
test_estimator_repr_error
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_check_classifier_not_supporting_multiclass(): """Check that when the estimator has the wrong tags.classifier_tags.multi_class set, the test fails.""" class BadEstimator(BaseEstimator): # we don't actually need to define the tag here since we're running the test # manually, and BaseEstimator defaults to multi_output=False. def fit(self, X, y): return self msg = "The estimator tag `tags.classifier_tags.multi_class` is False" with raises(AssertionError, match=msg): check_classifier_not_supporting_multiclass("BadEstimator", BadEstimator())
Check that when the estimator has the wrong tags.classifier_tags.multi_class set, the test fails.
test_check_classifier_not_supporting_multiclass
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_check_estimator_callback_with_fast_fail_error(): """Check that check_estimator fails correctly with on_fail='raise' and callback.""" with raises( ValueError, match="callback cannot be provided together with on_fail='raise'" ): check_estimator(LogisticRegression(), on_fail="raise", callback=lambda: None)
Check that check_estimator fails correctly with on_fail='raise' and callback.
test_check_estimator_callback_with_fast_fail_error
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_check_mixin_order(): """Test that the check raises an error when the mixin order is incorrect.""" class BadEstimator(BaseEstimator, TransformerMixin): def fit(self, X, y=None): return self msg = "TransformerMixin comes before/left side of BaseEstimator" with raises(AssertionError, match=re.escape(msg)): check_mixin_order("BadEstimator", BadEstimator())
Test that the check raises an error when the mixin order is incorrect.
test_check_mixin_order
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_estimator_checks.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_estimator_checks.py
BSD-3-Clause
def test_randomized_eigsh(dtype): """Test that `_randomized_eigsh` returns the appropriate components""" rng = np.random.RandomState(42) X = np.diag(np.array([1.0, -2.0, 0.0, 3.0], dtype=dtype)) # random rotation that preserves the eigenvalues of X rand_rot = np.linalg.qr(rng.normal(size=X.shape))[0] X = rand_rot @ X @ rand_rot.T # with 'module' selection method, the negative eigenvalue shows up eigvals, eigvecs = _randomized_eigsh(X, n_components=2, selection="module") # eigenvalues assert eigvals.shape == (2,) assert_array_almost_equal(eigvals, [3.0, -2.0]) # negative eigenvalue here # eigenvectors assert eigvecs.shape == (4, 2) # with 'value' selection method, the negative eigenvalue does not show up with pytest.raises(NotImplementedError): _randomized_eigsh(X, n_components=2, selection="value")
Test that `_randomized_eigsh` returns the appropriate components
test_randomized_eigsh
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_extmath.py
BSD-3-Clause
def test_randomized_eigsh_compared_to_others(k): """Check that `_randomized_eigsh` is similar to other `eigsh` Tests that for a random PSD matrix, `_randomized_eigsh` provides results comparable to LAPACK (scipy.linalg.eigh) and ARPACK (scipy.sparse.linalg.eigsh). Note: some versions of ARPACK do not support k=n_features. """ # make a random PSD matrix n_features = 200 X = make_sparse_spd_matrix(n_features, random_state=0) # compare two versions of randomized # rough and fast eigvals, eigvecs = _randomized_eigsh( X, n_components=k, selection="module", n_iter=25, random_state=0 ) # more accurate but slow (TODO find realistic settings here) eigvals_qr, eigvecs_qr = _randomized_eigsh( X, n_components=k, n_iter=25, n_oversamples=20, random_state=0, power_iteration_normalizer="QR", selection="module", ) # with LAPACK eigvals_lapack, eigvecs_lapack = eigh( X, subset_by_index=(n_features - k, n_features - 1) ) indices = eigvals_lapack.argsort()[::-1] eigvals_lapack = eigvals_lapack[indices] eigvecs_lapack = eigvecs_lapack[:, indices] # -- eigenvalues comparison assert eigvals_lapack.shape == (k,) # comparison precision assert_array_almost_equal(eigvals, eigvals_lapack, decimal=6) assert_array_almost_equal(eigvals_qr, eigvals_lapack, decimal=6) # -- eigenvectors comparison assert eigvecs_lapack.shape == (n_features, k) # flip eigenvectors' sign to enforce deterministic output dummy_vecs = np.zeros_like(eigvecs).T eigvecs, _ = svd_flip(eigvecs, dummy_vecs) eigvecs_qr, _ = svd_flip(eigvecs_qr, dummy_vecs) eigvecs_lapack, _ = svd_flip(eigvecs_lapack, dummy_vecs) assert_array_almost_equal(eigvecs, eigvecs_lapack, decimal=4) assert_array_almost_equal(eigvecs_qr, eigvecs_lapack, decimal=6) # comparison ARPACK ~ LAPACK (some ARPACK implems do not support k=n) if k < n_features: v0 = _init_arpack_v0(n_features, random_state=0) # "LA" largest algebraic <=> selection="value" in randomized_eigsh eigvals_arpack, eigvecs_arpack = eigsh( X, k, which="LA", tol=0, maxiter=None, v0=v0 ) indices = eigvals_arpack.argsort()[::-1] # eigenvalues eigvals_arpack = eigvals_arpack[indices] assert_array_almost_equal(eigvals_lapack, eigvals_arpack, decimal=10) # eigenvectors eigvecs_arpack = eigvecs_arpack[:, indices] eigvecs_arpack, _ = svd_flip(eigvecs_arpack, dummy_vecs) assert_array_almost_equal(eigvecs_arpack, eigvecs_lapack, decimal=8)
Check that `_randomized_eigsh` is similar to other `eigsh` Tests that for a random PSD matrix, `_randomized_eigsh` provides results comparable to LAPACK (scipy.linalg.eigh) and ARPACK (scipy.sparse.linalg.eigsh). Note: some versions of ARPACK do not support k=n_features.
test_randomized_eigsh_compared_to_others
python
scikit-learn/scikit-learn
sklearn/utils/tests/test_extmath.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/tests/test_extmath.py
BSD-3-Clause