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...
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 infe...
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...
__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``...
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 ---------- ...
_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__) ...
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` inst...
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_...
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: ``p...
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...
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 ...
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...
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 ...
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 : arr...
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 correspo...
_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 : ar...
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,), ...
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 clas...
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...
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 -------...
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_...
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...
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 ...
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 ...
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 matpl...
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 ...
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 ...
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 ...
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 sati...
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(c...
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_c...
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 *ar...
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 c...
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 ...
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 doe...
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})" eli...
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 : l...
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 metr...
_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...
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...
_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...
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 specif...
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. Paramete...
_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...
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...
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 ...
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...
_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....
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("'") ...
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...
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...
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 "co...
_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 ...
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 th...
_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...
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_c...
_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` ...
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...
_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 d...
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 `...
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_co...
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 ne...
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[...
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...
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 ...
_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} D...
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...
_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 decom...
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_out...
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 Configu...
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`. ...
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...
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 outp...
_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()), ]...
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 librar...
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 s...
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``. ``tran...
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:`~.skle...
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 ...
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...
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 -...
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 calla...
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) retu...
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 paramete...
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....
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-li...
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-...
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 ...
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, te...
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__) ...
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...
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 lis...
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 togethe...
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` provid...
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 strin...
_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/attrib...
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 ...
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 cloudpickl...
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 :...
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 conve...
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_cs...
_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...
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::...
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
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 No...
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...
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. ...
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_m...
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. ...
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 Prin...
_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(Va...
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)) a...
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_...
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 pyt...
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 c...
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", Modifies...
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, li...
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.acce...
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) f...
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...
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, expect...
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...
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 =...
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 wi...
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 Base...
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", c...
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(Asserti...
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))[...
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 ...
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