diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/__init__.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c730a71260808e76df302bda674232f06b53499e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/__init__.py @@ -0,0 +1,63 @@ +""" +The :mod:`sklearn.preprocessing` module includes scaling, centering, +normalization, binarization methods. +""" + +from ._data import ( + Binarizer, + KernelCenterer, + MaxAbsScaler, + MinMaxScaler, + Normalizer, + PowerTransformer, + QuantileTransformer, + RobustScaler, + StandardScaler, + add_dummy_feature, + binarize, + maxabs_scale, + minmax_scale, + normalize, + power_transform, + quantile_transform, + robust_scale, + scale, +) +from ._discretization import KBinsDiscretizer +from ._encoders import OneHotEncoder, OrdinalEncoder +from ._function_transformer import FunctionTransformer +from ._label import LabelBinarizer, LabelEncoder, MultiLabelBinarizer, label_binarize +from ._polynomial import PolynomialFeatures, SplineTransformer +from ._target_encoder import TargetEncoder + +__all__ = [ + "Binarizer", + "FunctionTransformer", + "KBinsDiscretizer", + "KernelCenterer", + "LabelBinarizer", + "LabelEncoder", + "MultiLabelBinarizer", + "MinMaxScaler", + "MaxAbsScaler", + "QuantileTransformer", + "Normalizer", + "OneHotEncoder", + "OrdinalEncoder", + "PowerTransformer", + "RobustScaler", + "SplineTransformer", + "StandardScaler", + "TargetEncoder", + "add_dummy_feature", + "PolynomialFeatures", + "binarize", + "normalize", + "scale", + "robust_scale", + "maxabs_scale", + "minmax_scale", + "label_binarize", + "quantile_transform", + "power_transform", +] diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_csr_polynomial_expansion.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_csr_polynomial_expansion.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e780835f806e98022563be901427d7f75c3bdb00 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_csr_polynomial_expansion.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_data.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec8a840298f074f2556d375aba87e374906ddc9 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_data.py @@ -0,0 +1,3618 @@ +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Olivier Grisel +# Andreas Mueller +# Eric Martin +# Giorgio Patrini +# Eric Chang +# License: BSD 3 clause + + +import warnings +from numbers import Integral, Real + +import numpy as np +from scipy import optimize, sparse, stats +from scipy.special import boxcox + +from ..base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + OneToOneFeatureMixin, + TransformerMixin, + _fit_context, +) +from ..utils import _array_api, check_array +from ..utils._array_api import get_namespace +from ..utils._param_validation import Interval, Options, StrOptions, validate_params +from ..utils.extmath import _incremental_mean_and_var, row_norms +from ..utils.sparsefuncs import ( + incr_mean_variance_axis, + inplace_column_scale, + mean_variance_axis, + min_max_axis, +) +from ..utils.sparsefuncs_fast import ( + inplace_csr_row_normalize_l1, + inplace_csr_row_normalize_l2, +) +from ..utils.validation import ( + FLOAT_DTYPES, + _check_sample_weight, + check_is_fitted, + check_random_state, +) +from ._encoders import OneHotEncoder + +BOUNDS_THRESHOLD = 1e-7 + +__all__ = [ + "Binarizer", + "KernelCenterer", + "MinMaxScaler", + "MaxAbsScaler", + "Normalizer", + "OneHotEncoder", + "RobustScaler", + "StandardScaler", + "QuantileTransformer", + "PowerTransformer", + "add_dummy_feature", + "binarize", + "normalize", + "scale", + "robust_scale", + "maxabs_scale", + "minmax_scale", + "quantile_transform", + "power_transform", +] + + +def _is_constant_feature(var, mean, n_samples): + """Detect if a feature is indistinguishable from a constant feature. + + The detection is based on its computed variance and on the theoretical + error bounds of the '2 pass algorithm' for variance computation. + + See "Algorithms for computing the sample variance: analysis and + recommendations", by Chan, Golub, and LeVeque. + """ + # In scikit-learn, variance is always computed using float64 accumulators. + eps = np.finfo(np.float64).eps + + upper_bound = n_samples * eps * var + (n_samples * mean * eps) ** 2 + return var <= upper_bound + + +def _handle_zeros_in_scale(scale, copy=True, constant_mask=None): + """Set scales of near constant features to 1. + + The goal is to avoid division by very small or zero values. + + Near constant features are detected automatically by identifying + scales close to machine precision unless they are precomputed by + the caller and passed with the `constant_mask` kwarg. + + Typically for standard scaling, the scales are the standard + deviation while near constant features are better detected on the + computed variances which are closer to machine precision by + construction. + """ + # if we are fitting on 1D arrays, scale might be a scalar + if np.isscalar(scale): + if scale == 0.0: + scale = 1.0 + return scale + # scale is an array + else: + xp, _ = get_namespace(scale) + if constant_mask is None: + # Detect near constant values to avoid dividing by a very small + # value that could lead to surprising results and numerical + # stability issues. + constant_mask = scale < 10 * xp.finfo(scale.dtype).eps + + if copy: + # New array to avoid side-effects + scale = xp.asarray(scale, copy=True) + scale[constant_mask] = 1.0 + return scale + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "axis": [Options(Integral, {0, 1})], + "with_mean": ["boolean"], + "with_std": ["boolean"], + "copy": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def scale(X, *, axis=0, with_mean=True, with_std=True, copy=True): + """Standardize a dataset along any axis. + + Center to the mean and component wise scale to unit variance. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to center and scale. + + axis : {0, 1}, default=0 + Axis used to compute the means and standard deviations along. If 0, + independently standardize each feature, otherwise (if 1) standardize + each sample. + + with_mean : bool, default=True + If True, center the data before scaling. + + with_std : bool, default=True + If True, scale the data to unit variance (or equivalently, + unit standard deviation). + + copy : bool, default=True + If False, try to avoid a copy and scale in place. + This is not guaranteed to always work in place; e.g. if the data is + a numpy array with an int dtype, a copy will be returned even with + copy=False. + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + The transformed data. + + See Also + -------- + StandardScaler : Performs scaling to unit variance using the Transformer + API (e.g. as part of a preprocessing + :class:`~sklearn.pipeline.Pipeline`). + + Notes + ----- + This implementation will refuse to center scipy.sparse matrices + since it would make them non-sparse and would potentially crash the + program with memory exhaustion problems. + + Instead the caller is expected to either set explicitly + `with_mean=False` (in that case, only variance scaling will be + performed on the features of the CSC matrix) or to call `X.toarray()` + if he/she expects the materialized dense array to fit in memory. + + To avoid memory copy the caller should pass a CSC matrix. + + NaNs are treated as missing values: disregarded to compute the statistics, + and maintained during the data transformation. + + We use a biased estimator for the standard deviation, equivalent to + `numpy.std(x, ddof=0)`. Note that the choice of `ddof` is unlikely to + affect model performance. + + For a comparison of the different scalers, transformers, and normalizers, + see: :ref:`sphx_glr_auto_examples_preprocessing_plot_all_scaling.py`. + + .. warning:: Risk of data leak + + Do not use :func:`~sklearn.preprocessing.scale` unless you know + what you are doing. A common mistake is to apply it to the entire data + *before* splitting into training and test sets. This will bias the + model evaluation because information would have leaked from the test + set to the training set. + In general, we recommend using + :class:`~sklearn.preprocessing.StandardScaler` within a + :ref:`Pipeline ` in order to prevent most risks of data + leaking: `pipe = make_pipeline(StandardScaler(), LogisticRegression())`. + + Examples + -------- + >>> from sklearn.preprocessing import scale + >>> X = [[-2, 1, 2], [-1, 0, 1]] + >>> scale(X, axis=0) # scaling each column independently + array([[-1., 1., 1.], + [ 1., -1., -1.]]) + >>> scale(X, axis=1) # scaling each row independently + array([[-1.37..., 0.39..., 0.98...], + [-1.22..., 0. , 1.22...]]) + """ + X = check_array( + X, + accept_sparse="csc", + copy=copy, + ensure_2d=False, + estimator="the scale function", + dtype=FLOAT_DTYPES, + force_all_finite="allow-nan", + ) + if sparse.issparse(X): + if with_mean: + raise ValueError( + "Cannot center sparse matrices: pass `with_mean=False` instead" + " See docstring for motivation and alternatives." + ) + if axis != 0: + raise ValueError( + "Can only scale sparse matrix on axis=0, got axis=%d" % axis + ) + if with_std: + _, var = mean_variance_axis(X, axis=0) + var = _handle_zeros_in_scale(var, copy=False) + inplace_column_scale(X, 1 / np.sqrt(var)) + else: + X = np.asarray(X) + if with_mean: + mean_ = np.nanmean(X, axis) + if with_std: + scale_ = np.nanstd(X, axis) + # Xr is a view on the original array that enables easy use of + # broadcasting on the axis in which we are interested in + Xr = np.rollaxis(X, axis) + if with_mean: + Xr -= mean_ + mean_1 = np.nanmean(Xr, axis=0) + # Verify that mean_1 is 'close to zero'. If X contains very + # large values, mean_1 can also be very large, due to a lack of + # precision of mean_. In this case, a pre-scaling of the + # concerned feature is efficient, for instance by its mean or + # maximum. + if not np.allclose(mean_1, 0): + warnings.warn( + "Numerical issues were encountered " + "when centering the data " + "and might not be solved. Dataset may " + "contain too large values. You may need " + "to prescale your features." + ) + Xr -= mean_1 + if with_std: + scale_ = _handle_zeros_in_scale(scale_, copy=False) + Xr /= scale_ + if with_mean: + mean_2 = np.nanmean(Xr, axis=0) + # If mean_2 is not 'close to zero', it comes from the fact that + # scale_ is very small so that mean_2 = mean_1/scale_ > 0, even + # if mean_1 was close to zero. The problem is thus essentially + # due to the lack of precision of mean_. A solution is then to + # subtract the mean again: + if not np.allclose(mean_2, 0): + warnings.warn( + "Numerical issues were encountered " + "when scaling the data " + "and might not be solved. The standard " + "deviation of the data is probably " + "very close to 0. " + ) + Xr -= mean_2 + return X + + +class MinMaxScaler(OneToOneFeatureMixin, TransformerMixin, BaseEstimator): + """Transform features by scaling each feature to a given range. + + This estimator scales and translates each feature individually such + that it is in the given range on the training set, e.g. between + zero and one. + + The transformation is given by:: + + X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) + X_scaled = X_std * (max - min) + min + + where min, max = feature_range. + + This transformation is often used as an alternative to zero mean, + unit variance scaling. + + `MinMaxScaler` doesn't reduce the effect of outliers, but it linearly + scales them down into a fixed range, where the largest occurring data point + corresponds to the maximum value and the smallest one corresponds to the + minimum value. For an example visualization, refer to :ref:`Compare + MinMaxScaler with other scalers `. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + feature_range : tuple (min, max), default=(0, 1) + Desired range of transformed data. + + copy : bool, default=True + Set to False to perform inplace row normalization and avoid a + copy (if the input is already a numpy array). + + clip : bool, default=False + Set to True to clip transformed values of held-out data to + provided `feature range`. + + .. versionadded:: 0.24 + + Attributes + ---------- + min_ : ndarray of shape (n_features,) + Per feature adjustment for minimum. Equivalent to + ``min - X.min(axis=0) * self.scale_`` + + scale_ : ndarray of shape (n_features,) + Per feature relative scaling of the data. Equivalent to + ``(max - min) / (X.max(axis=0) - X.min(axis=0))`` + + .. versionadded:: 0.17 + *scale_* attribute. + + data_min_ : ndarray of shape (n_features,) + Per feature minimum seen in the data + + .. versionadded:: 0.17 + *data_min_* + + data_max_ : ndarray of shape (n_features,) + Per feature maximum seen in the data + + .. versionadded:: 0.17 + *data_max_* + + data_range_ : ndarray of shape (n_features,) + Per feature range ``(data_max_ - data_min_)`` seen in the data + + .. versionadded:: 0.17 + *data_range_* + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + n_samples_seen_ : int + The number of samples processed by the estimator. + It will be reset on new calls to fit, but increments across + ``partial_fit`` calls. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + minmax_scale : Equivalent function without the estimator API. + + Notes + ----- + NaNs are treated as missing values: disregarded in fit, and maintained in + transform. + + Examples + -------- + >>> from sklearn.preprocessing import MinMaxScaler + >>> data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]] + >>> scaler = MinMaxScaler() + >>> print(scaler.fit(data)) + MinMaxScaler() + >>> print(scaler.data_max_) + [ 1. 18.] + >>> print(scaler.transform(data)) + [[0. 0. ] + [0.25 0.25] + [0.5 0.5 ] + [1. 1. ]] + >>> print(scaler.transform([[2, 2]])) + [[1.5 0. ]] + """ + + _parameter_constraints: dict = { + "feature_range": [tuple], + "copy": ["boolean"], + "clip": ["boolean"], + } + + def __init__(self, feature_range=(0, 1), *, copy=True, clip=False): + self.feature_range = feature_range + self.copy = copy + self.clip = clip + + def _reset(self): + """Reset internal data-dependent state of the scaler, if necessary. + + __init__ parameters are not touched. + """ + # Checking one attribute is enough, because they are all set together + # in partial_fit + if hasattr(self, "scale_"): + del self.scale_ + del self.min_ + del self.n_samples_seen_ + del self.data_min_ + del self.data_max_ + del self.data_range_ + + def fit(self, X, y=None): + """Compute the minimum and maximum to be used for later scaling. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data used to compute the per-feature minimum and maximum + used for later scaling along the features axis. + + y : None + Ignored. + + Returns + ------- + self : object + Fitted scaler. + """ + # Reset internal state before fitting + self._reset() + return self.partial_fit(X, y) + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y=None): + """Online computation of min and max on X for later scaling. + + All of X is processed as a single batch. This is intended for cases + when :meth:`fit` is not feasible due to very large number of + `n_samples` or because X is read from a continuous stream. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data used to compute the mean and standard deviation + used for later scaling along the features axis. + + y : None + Ignored. + + Returns + ------- + self : object + Fitted scaler. + """ + feature_range = self.feature_range + if feature_range[0] >= feature_range[1]: + raise ValueError( + "Minimum of desired feature range must be smaller than maximum. Got %s." + % str(feature_range) + ) + + if sparse.issparse(X): + raise TypeError( + "MinMaxScaler does not support sparse input. " + "Consider using MaxAbsScaler instead." + ) + + xp, _ = get_namespace(X) + + first_pass = not hasattr(self, "n_samples_seen_") + X = self._validate_data( + X, + reset=first_pass, + dtype=_array_api.supported_float_dtypes(xp), + force_all_finite="allow-nan", + ) + + data_min = _array_api._nanmin(X, axis=0) + data_max = _array_api._nanmax(X, axis=0) + + if first_pass: + self.n_samples_seen_ = X.shape[0] + else: + data_min = xp.minimum(self.data_min_, data_min) + data_max = xp.maximum(self.data_max_, data_max) + self.n_samples_seen_ += X.shape[0] + + data_range = data_max - data_min + self.scale_ = (feature_range[1] - feature_range[0]) / _handle_zeros_in_scale( + data_range, copy=True + ) + self.min_ = feature_range[0] - data_min * self.scale_ + self.data_min_ = data_min + self.data_max_ = data_max + self.data_range_ = data_range + return self + + def transform(self, X): + """Scale features of X according to feature_range. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input data that will be transformed. + + Returns + ------- + Xt : ndarray of shape (n_samples, n_features) + Transformed data. + """ + check_is_fitted(self) + + xp, _ = get_namespace(X) + + X = self._validate_data( + X, + copy=self.copy, + dtype=_array_api.supported_float_dtypes(xp), + force_all_finite="allow-nan", + reset=False, + ) + + X *= self.scale_ + X += self.min_ + if self.clip: + xp.clip(X, self.feature_range[0], self.feature_range[1], out=X) + return X + + def inverse_transform(self, X): + """Undo the scaling of X according to feature_range. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input data that will be transformed. It cannot be sparse. + + Returns + ------- + Xt : ndarray of shape (n_samples, n_features) + Transformed data. + """ + check_is_fitted(self) + + xp, _ = get_namespace(X) + + X = check_array( + X, + copy=self.copy, + dtype=_array_api.supported_float_dtypes(xp), + force_all_finite="allow-nan", + ) + + X -= self.min_ + X /= self.scale_ + return X + + def _more_tags(self): + return {"allow_nan": True} + + +@validate_params( + { + "X": ["array-like"], + "axis": [Options(Integral, {0, 1})], + }, + prefer_skip_nested_validation=False, +) +def minmax_scale(X, feature_range=(0, 1), *, axis=0, copy=True): + """Transform features by scaling each feature to a given range. + + This estimator scales and translates each feature individually such + that it is in the given range on the training set, i.e. between + zero and one. + + The transformation is given by (when ``axis=0``):: + + X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) + X_scaled = X_std * (max - min) + min + + where min, max = feature_range. + + The transformation is calculated as (when ``axis=0``):: + + X_scaled = scale * X + min - X.min(axis=0) * scale + where scale = (max - min) / (X.max(axis=0) - X.min(axis=0)) + + This transformation is often used as an alternative to zero mean, + unit variance scaling. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.17 + *minmax_scale* function interface + to :class:`~sklearn.preprocessing.MinMaxScaler`. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data. + + feature_range : tuple (min, max), default=(0, 1) + Desired range of transformed data. + + axis : {0, 1}, default=0 + Axis used to scale along. If 0, independently scale each feature, + otherwise (if 1) scale each sample. + + copy : bool, default=True + If False, try to avoid a copy and scale in place. + This is not guaranteed to always work in place; e.g. if the data is + a numpy array with an int dtype, a copy will be returned even with + copy=False. + + Returns + ------- + X_tr : ndarray of shape (n_samples, n_features) + The transformed data. + + .. warning:: Risk of data leak + + Do not use :func:`~sklearn.preprocessing.minmax_scale` unless you know + what you are doing. A common mistake is to apply it to the entire data + *before* splitting into training and test sets. This will bias the + model evaluation because information would have leaked from the test + set to the training set. + In general, we recommend using + :class:`~sklearn.preprocessing.MinMaxScaler` within a + :ref:`Pipeline ` in order to prevent most risks of data + leaking: `pipe = make_pipeline(MinMaxScaler(), LogisticRegression())`. + + See Also + -------- + MinMaxScaler : Performs scaling to a given range using the Transformer + API (e.g. as part of a preprocessing + :class:`~sklearn.pipeline.Pipeline`). + + Notes + ----- + For a comparison of the different scalers, transformers, and normalizers, + see: :ref:`sphx_glr_auto_examples_preprocessing_plot_all_scaling.py`. + + Examples + -------- + >>> from sklearn.preprocessing import minmax_scale + >>> X = [[-2, 1, 2], [-1, 0, 1]] + >>> minmax_scale(X, axis=0) # scale each column independently + array([[0., 1., 1.], + [1., 0., 0.]]) + >>> minmax_scale(X, axis=1) # scale each row independently + array([[0. , 0.75, 1. ], + [0. , 0.5 , 1. ]]) + """ + # Unlike the scaler object, this function allows 1d input. + # If copy is required, it will be done inside the scaler object. + X = check_array( + X, copy=False, ensure_2d=False, dtype=FLOAT_DTYPES, force_all_finite="allow-nan" + ) + original_ndim = X.ndim + + if original_ndim == 1: + X = X.reshape(X.shape[0], 1) + + s = MinMaxScaler(feature_range=feature_range, copy=copy) + if axis == 0: + X = s.fit_transform(X) + else: + X = s.fit_transform(X.T).T + + if original_ndim == 1: + X = X.ravel() + + return X + + +class StandardScaler(OneToOneFeatureMixin, TransformerMixin, BaseEstimator): + """Standardize features by removing the mean and scaling to unit variance. + + The standard score of a sample `x` is calculated as: + + z = (x - u) / s + + where `u` is the mean of the training samples or zero if `with_mean=False`, + and `s` is the standard deviation of the training samples or one if + `with_std=False`. + + Centering and scaling happen independently on each feature by computing + the relevant statistics on the samples in the training set. Mean and + standard deviation are then stored to be used on later data using + :meth:`transform`. + + Standardization of a dataset is a common requirement for many + machine learning estimators: they might behave badly if the + individual features do not more or less look like standard normally + distributed data (e.g. Gaussian with 0 mean and unit variance). + + For instance many elements used in the objective function of + a learning algorithm (such as the RBF kernel of Support Vector + Machines or the L1 and L2 regularizers of linear models) assume that + all features are centered around 0 and have variance in the same + order. If a feature has a variance that is orders of magnitude larger + than others, it might dominate the objective function and make the + estimator unable to learn from other features correctly as expected. + + `StandardScaler` is sensitive to outliers, and the features may scale + differently from each other in the presence of outliers. For an example + visualization, refer to :ref:`Compare StandardScaler with other scalers + `. + + This scaler can also be applied to sparse CSR or CSC matrices by passing + `with_mean=False` to avoid breaking the sparsity structure of the data. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + copy : bool, default=True + If False, try to avoid a copy and do inplace scaling instead. + This is not guaranteed to always work inplace; e.g. if the data is + not a NumPy array or scipy.sparse CSR matrix, a copy may still be + returned. + + with_mean : bool, default=True + If True, center the data before scaling. + This does not work (and will raise an exception) when attempted on + sparse matrices, because centering them entails building a dense + matrix which in common use cases is likely to be too large to fit in + memory. + + with_std : bool, default=True + If True, scale the data to unit variance (or equivalently, + unit standard deviation). + + Attributes + ---------- + scale_ : ndarray of shape (n_features,) or None + Per feature relative scaling of the data to achieve zero mean and unit + variance. Generally this is calculated using `np.sqrt(var_)`. If a + variance is zero, we can't achieve unit variance, and the data is left + as-is, giving a scaling factor of 1. `scale_` is equal to `None` + when `with_std=False`. + + .. versionadded:: 0.17 + *scale_* + + mean_ : ndarray of shape (n_features,) or None + The mean value for each feature in the training set. + Equal to ``None`` when ``with_mean=False`` and ``with_std=False``. + + var_ : ndarray of shape (n_features,) or None + The variance for each feature in the training set. Used to compute + `scale_`. Equal to ``None`` when ``with_mean=False`` and + ``with_std=False``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_samples_seen_ : int or ndarray of shape (n_features,) + The number of samples processed by the estimator for each feature. + If there are no missing samples, the ``n_samples_seen`` will be an + integer, otherwise it will be an array of dtype int. If + `sample_weights` are used it will be a float (if no missing data) + or an array of dtype float that sums the weights seen so far. + Will be reset on new calls to fit, but increments across + ``partial_fit`` calls. + + See Also + -------- + scale : Equivalent function without the estimator API. + + :class:`~sklearn.decomposition.PCA` : Further removes the linear + correlation across features with 'whiten=True'. + + Notes + ----- + NaNs are treated as missing values: disregarded in fit, and maintained in + transform. + + We use a biased estimator for the standard deviation, equivalent to + `numpy.std(x, ddof=0)`. Note that the choice of `ddof` is unlikely to + affect model performance. + + Examples + -------- + >>> from sklearn.preprocessing import StandardScaler + >>> data = [[0, 0], [0, 0], [1, 1], [1, 1]] + >>> scaler = StandardScaler() + >>> print(scaler.fit(data)) + StandardScaler() + >>> print(scaler.mean_) + [0.5 0.5] + >>> print(scaler.transform(data)) + [[-1. -1.] + [-1. -1.] + [ 1. 1.] + [ 1. 1.]] + >>> print(scaler.transform([[2, 2]])) + [[3. 3.]] + """ + + _parameter_constraints: dict = { + "copy": ["boolean"], + "with_mean": ["boolean"], + "with_std": ["boolean"], + } + + def __init__(self, *, copy=True, with_mean=True, with_std=True): + self.with_mean = with_mean + self.with_std = with_std + self.copy = copy + + def _reset(self): + """Reset internal data-dependent state of the scaler, if necessary. + + __init__ parameters are not touched. + """ + # Checking one attribute is enough, because they are all set together + # in partial_fit + if hasattr(self, "scale_"): + del self.scale_ + del self.n_samples_seen_ + del self.mean_ + del self.var_ + + def fit(self, X, y=None, sample_weight=None): + """Compute the mean and std to be used for later scaling. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data used to compute the mean and standard deviation + used for later scaling along the features axis. + + y : None + Ignored. + + sample_weight : array-like of shape (n_samples,), default=None + Individual weights for each sample. + + .. versionadded:: 0.24 + parameter *sample_weight* support to StandardScaler. + + Returns + ------- + self : object + Fitted scaler. + """ + # Reset internal state before fitting + self._reset() + return self.partial_fit(X, y, sample_weight) + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y=None, sample_weight=None): + """Online computation of mean and std on X for later scaling. + + All of X is processed as a single batch. This is intended for cases + when :meth:`fit` is not feasible due to very large number of + `n_samples` or because X is read from a continuous stream. + + The algorithm for incremental mean and std is given in Equation 1.5a,b + in Chan, Tony F., Gene H. Golub, and Randall J. LeVeque. "Algorithms + for computing the sample variance: Analysis and recommendations." + The American Statistician 37.3 (1983): 242-247: + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data used to compute the mean and standard deviation + used for later scaling along the features axis. + + y : None + Ignored. + + sample_weight : array-like of shape (n_samples,), default=None + Individual weights for each sample. + + .. versionadded:: 0.24 + parameter *sample_weight* support to StandardScaler. + + Returns + ------- + self : object + Fitted scaler. + """ + first_call = not hasattr(self, "n_samples_seen_") + X = self._validate_data( + X, + accept_sparse=("csr", "csc"), + dtype=FLOAT_DTYPES, + force_all_finite="allow-nan", + reset=first_call, + ) + n_features = X.shape[1] + + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + # Even in the case of `with_mean=False`, we update the mean anyway + # This is needed for the incremental computation of the var + # See incr_mean_variance_axis and _incremental_mean_variance_axis + + # if n_samples_seen_ is an integer (i.e. no missing values), we need to + # transform it to a NumPy array of shape (n_features,) required by + # incr_mean_variance_axis and _incremental_variance_axis + dtype = np.int64 if sample_weight is None else X.dtype + if not hasattr(self, "n_samples_seen_"): + self.n_samples_seen_ = np.zeros(n_features, dtype=dtype) + elif np.size(self.n_samples_seen_) == 1: + self.n_samples_seen_ = np.repeat(self.n_samples_seen_, X.shape[1]) + self.n_samples_seen_ = self.n_samples_seen_.astype(dtype, copy=False) + + if sparse.issparse(X): + if self.with_mean: + raise ValueError( + "Cannot center sparse matrices: pass `with_mean=False` " + "instead. See docstring for motivation and alternatives." + ) + sparse_constructor = ( + sparse.csr_matrix if X.format == "csr" else sparse.csc_matrix + ) + + if self.with_std: + # First pass + if not hasattr(self, "scale_"): + self.mean_, self.var_, self.n_samples_seen_ = mean_variance_axis( + X, axis=0, weights=sample_weight, return_sum_weights=True + ) + # Next passes + else: + ( + self.mean_, + self.var_, + self.n_samples_seen_, + ) = incr_mean_variance_axis( + X, + axis=0, + last_mean=self.mean_, + last_var=self.var_, + last_n=self.n_samples_seen_, + weights=sample_weight, + ) + # We force the mean and variance to float64 for large arrays + # See https://github.com/scikit-learn/scikit-learn/pull/12338 + self.mean_ = self.mean_.astype(np.float64, copy=False) + self.var_ = self.var_.astype(np.float64, copy=False) + else: + self.mean_ = None # as with_mean must be False for sparse + self.var_ = None + weights = _check_sample_weight(sample_weight, X) + sum_weights_nan = weights @ sparse_constructor( + (np.isnan(X.data), X.indices, X.indptr), shape=X.shape + ) + self.n_samples_seen_ += (np.sum(weights) - sum_weights_nan).astype( + dtype + ) + else: + # First pass + if not hasattr(self, "scale_"): + self.mean_ = 0.0 + if self.with_std: + self.var_ = 0.0 + else: + self.var_ = None + + if not self.with_mean and not self.with_std: + self.mean_ = None + self.var_ = None + self.n_samples_seen_ += X.shape[0] - np.isnan(X).sum(axis=0) + + else: + self.mean_, self.var_, self.n_samples_seen_ = _incremental_mean_and_var( + X, + self.mean_, + self.var_, + self.n_samples_seen_, + sample_weight=sample_weight, + ) + + # for backward-compatibility, reduce n_samples_seen_ to an integer + # if the number of samples is the same for each feature (i.e. no + # missing values) + if np.ptp(self.n_samples_seen_) == 0: + self.n_samples_seen_ = self.n_samples_seen_[0] + + if self.with_std: + # Extract the list of near constant features on the raw variances, + # before taking the square root. + constant_mask = _is_constant_feature( + self.var_, self.mean_, self.n_samples_seen_ + ) + self.scale_ = _handle_zeros_in_scale( + np.sqrt(self.var_), copy=False, constant_mask=constant_mask + ) + else: + self.scale_ = None + + return self + + def transform(self, X, copy=None): + """Perform standardization by centering and scaling. + + Parameters + ---------- + X : {array-like, sparse matrix of shape (n_samples, n_features) + The data used to scale along the features axis. + copy : bool, default=None + Copy the input X or not. + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + Transformed array. + """ + check_is_fitted(self) + + copy = copy if copy is not None else self.copy + X = self._validate_data( + X, + reset=False, + accept_sparse="csr", + copy=copy, + dtype=FLOAT_DTYPES, + force_all_finite="allow-nan", + ) + + if sparse.issparse(X): + if self.with_mean: + raise ValueError( + "Cannot center sparse matrices: pass `with_mean=False` " + "instead. See docstring for motivation and alternatives." + ) + if self.scale_ is not None: + inplace_column_scale(X, 1 / self.scale_) + else: + if self.with_mean: + X -= self.mean_ + if self.with_std: + X /= self.scale_ + return X + + def inverse_transform(self, X, copy=None): + """Scale back the data to the original representation. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data used to scale along the features axis. + copy : bool, default=None + Copy the input X or not. + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + Transformed array. + """ + check_is_fitted(self) + + copy = copy if copy is not None else self.copy + X = check_array( + X, + accept_sparse="csr", + copy=copy, + dtype=FLOAT_DTYPES, + force_all_finite="allow-nan", + ) + + if sparse.issparse(X): + if self.with_mean: + raise ValueError( + "Cannot uncenter sparse matrices: pass `with_mean=False` " + "instead See docstring for motivation and alternatives." + ) + if self.scale_ is not None: + inplace_column_scale(X, self.scale_) + else: + if self.with_std: + X *= self.scale_ + if self.with_mean: + X += self.mean_ + return X + + def _more_tags(self): + return {"allow_nan": True, "preserves_dtype": [np.float64, np.float32]} + + +class MaxAbsScaler(OneToOneFeatureMixin, TransformerMixin, BaseEstimator): + """Scale each feature by its maximum absolute value. + + This estimator scales and translates each feature individually such + that the maximal absolute value of each feature in the + training set will be 1.0. It does not shift/center the data, and + thus does not destroy any sparsity. + + This scaler can also be applied to sparse CSR or CSC matrices. + + `MaxAbsScaler` doesn't reduce the effect of outliers; it only linearly + scales them down. For an example visualization, refer to :ref:`Compare + MaxAbsScaler with other scalers `. + + .. versionadded:: 0.17 + + Parameters + ---------- + copy : bool, default=True + Set to False to perform inplace scaling and avoid a copy (if the input + is already a numpy array). + + Attributes + ---------- + scale_ : ndarray of shape (n_features,) + Per feature relative scaling of the data. + + .. versionadded:: 0.17 + *scale_* attribute. + + max_abs_ : ndarray of shape (n_features,) + Per feature maximum absolute value. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_samples_seen_ : int + The number of samples processed by the estimator. Will be reset on + new calls to fit, but increments across ``partial_fit`` calls. + + See Also + -------- + maxabs_scale : Equivalent function without the estimator API. + + Notes + ----- + NaNs are treated as missing values: disregarded in fit, and maintained in + transform. + + Examples + -------- + >>> from sklearn.preprocessing import MaxAbsScaler + >>> X = [[ 1., -1., 2.], + ... [ 2., 0., 0.], + ... [ 0., 1., -1.]] + >>> transformer = MaxAbsScaler().fit(X) + >>> transformer + MaxAbsScaler() + >>> transformer.transform(X) + array([[ 0.5, -1. , 1. ], + [ 1. , 0. , 0. ], + [ 0. , 1. , -0.5]]) + """ + + _parameter_constraints: dict = {"copy": ["boolean"]} + + def __init__(self, *, copy=True): + self.copy = copy + + def _reset(self): + """Reset internal data-dependent state of the scaler, if necessary. + + __init__ parameters are not touched. + """ + # Checking one attribute is enough, because they are all set together + # in partial_fit + if hasattr(self, "scale_"): + del self.scale_ + del self.n_samples_seen_ + del self.max_abs_ + + def fit(self, X, y=None): + """Compute the maximum absolute value to be used for later scaling. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data used to compute the per-feature minimum and maximum + used for later scaling along the features axis. + + y : None + Ignored. + + Returns + ------- + self : object + Fitted scaler. + """ + # Reset internal state before fitting + self._reset() + return self.partial_fit(X, y) + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y=None): + """Online computation of max absolute value of X for later scaling. + + All of X is processed as a single batch. This is intended for cases + when :meth:`fit` is not feasible due to very large number of + `n_samples` or because X is read from a continuous stream. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data used to compute the mean and standard deviation + used for later scaling along the features axis. + + y : None + Ignored. + + Returns + ------- + self : object + Fitted scaler. + """ + xp, _ = get_namespace(X) + + first_pass = not hasattr(self, "n_samples_seen_") + X = self._validate_data( + X, + reset=first_pass, + accept_sparse=("csr", "csc"), + dtype=_array_api.supported_float_dtypes(xp), + force_all_finite="allow-nan", + ) + + if sparse.issparse(X): + mins, maxs = min_max_axis(X, axis=0, ignore_nan=True) + max_abs = np.maximum(np.abs(mins), np.abs(maxs)) + else: + max_abs = _array_api._nanmax(xp.abs(X), axis=0) + + if first_pass: + self.n_samples_seen_ = X.shape[0] + else: + max_abs = xp.maximum(self.max_abs_, max_abs) + self.n_samples_seen_ += X.shape[0] + + self.max_abs_ = max_abs + self.scale_ = _handle_zeros_in_scale(max_abs, copy=True) + return self + + def transform(self, X): + """Scale the data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data that should be scaled. + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + Transformed array. + """ + check_is_fitted(self) + + xp, _ = get_namespace(X) + + X = self._validate_data( + X, + accept_sparse=("csr", "csc"), + copy=self.copy, + reset=False, + dtype=_array_api.supported_float_dtypes(xp), + force_all_finite="allow-nan", + ) + + if sparse.issparse(X): + inplace_column_scale(X, 1.0 / self.scale_) + else: + X /= self.scale_ + return X + + def inverse_transform(self, X): + """Scale back the data to the original representation. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data that should be transformed back. + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + Transformed array. + """ + check_is_fitted(self) + + xp, _ = get_namespace(X) + + X = check_array( + X, + accept_sparse=("csr", "csc"), + copy=self.copy, + dtype=_array_api.supported_float_dtypes(xp), + force_all_finite="allow-nan", + ) + + if sparse.issparse(X): + inplace_column_scale(X, self.scale_) + else: + X *= self.scale_ + return X + + def _more_tags(self): + return {"allow_nan": True} + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "axis": [Options(Integral, {0, 1})], + }, + prefer_skip_nested_validation=False, +) +def maxabs_scale(X, *, axis=0, copy=True): + """Scale each feature to the [-1, 1] range without breaking the sparsity. + + This estimator scales each feature individually such + that the maximal absolute value of each feature in the + training set will be 1.0. + + This scaler can also be applied to sparse CSR or CSC matrices. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data. + + axis : {0, 1}, default=0 + Axis used to scale along. If 0, independently scale each feature, + otherwise (if 1) scale each sample. + + copy : bool, default=True + If False, try to avoid a copy and scale in place. + This is not guaranteed to always work in place; e.g. if the data is + a numpy array with an int dtype, a copy will be returned even with + copy=False. + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + The transformed data. + + .. warning:: Risk of data leak + + Do not use :func:`~sklearn.preprocessing.maxabs_scale` unless you know + what you are doing. A common mistake is to apply it to the entire data + *before* splitting into training and test sets. This will bias the + model evaluation because information would have leaked from the test + set to the training set. + In general, we recommend using + :class:`~sklearn.preprocessing.MaxAbsScaler` within a + :ref:`Pipeline ` in order to prevent most risks of data + leaking: `pipe = make_pipeline(MaxAbsScaler(), LogisticRegression())`. + + See Also + -------- + MaxAbsScaler : Performs scaling to the [-1, 1] range using + the Transformer API (e.g. as part of a preprocessing + :class:`~sklearn.pipeline.Pipeline`). + + Notes + ----- + NaNs are treated as missing values: disregarded to compute the statistics, + and maintained during the data transformation. + + For a comparison of the different scalers, transformers, and normalizers, + see: :ref:`sphx_glr_auto_examples_preprocessing_plot_all_scaling.py`. + + Examples + -------- + >>> from sklearn.preprocessing import maxabs_scale + >>> X = [[-2, 1, 2], [-1, 0, 1]] + >>> maxabs_scale(X, axis=0) # scale each column independently + array([[-1. , 1. , 1. ], + [-0.5, 0. , 0.5]]) + >>> maxabs_scale(X, axis=1) # scale each row independently + array([[-1. , 0.5, 1. ], + [-1. , 0. , 1. ]]) + """ + # Unlike the scaler object, this function allows 1d input. + + # If copy is required, it will be done inside the scaler object. + X = check_array( + X, + accept_sparse=("csr", "csc"), + copy=False, + ensure_2d=False, + dtype=FLOAT_DTYPES, + force_all_finite="allow-nan", + ) + original_ndim = X.ndim + + if original_ndim == 1: + X = X.reshape(X.shape[0], 1) + + s = MaxAbsScaler(copy=copy) + if axis == 0: + X = s.fit_transform(X) + else: + X = s.fit_transform(X.T).T + + if original_ndim == 1: + X = X.ravel() + + return X + + +class RobustScaler(OneToOneFeatureMixin, TransformerMixin, BaseEstimator): + """Scale features using statistics that are robust to outliers. + + This Scaler removes the median and scales the data according to + the quantile range (defaults to IQR: Interquartile Range). + The IQR is the range between the 1st quartile (25th quantile) + and the 3rd quartile (75th quantile). + + Centering and scaling happen independently on each feature by + computing the relevant statistics on the samples in the training + set. Median and interquartile range are then stored to be used on + later data using the :meth:`transform` method. + + Standardization of a dataset is a common preprocessing for many machine + learning estimators. Typically this is done by removing the mean and + scaling to unit variance. However, outliers can often influence the sample + mean / variance in a negative way. In such cases, using the median and the + interquartile range often give better results. For an example visualization + and comparison to other scalers, refer to :ref:`Compare RobustScaler with + other scalers `. + + .. versionadded:: 0.17 + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + with_centering : bool, default=True + If `True`, center the data before scaling. + This will cause :meth:`transform` to raise an exception when attempted + on sparse matrices, because centering them entails building a dense + matrix which in common use cases is likely to be too large to fit in + memory. + + with_scaling : bool, default=True + If `True`, scale the data to interquartile range. + + quantile_range : tuple (q_min, q_max), 0.0 < q_min < q_max < 100.0, \ + default=(25.0, 75.0) + Quantile range used to calculate `scale_`. By default this is equal to + the IQR, i.e., `q_min` is the first quantile and `q_max` is the third + quantile. + + .. versionadded:: 0.18 + + copy : bool, default=True + If `False`, try to avoid a copy and do inplace scaling instead. + This is not guaranteed to always work inplace; e.g. if the data is + not a NumPy array or scipy.sparse CSR matrix, a copy may still be + returned. + + unit_variance : bool, default=False + If `True`, scale data so that normally distributed features have a + variance of 1. In general, if the difference between the x-values of + `q_max` and `q_min` for a standard normal distribution is greater + than 1, the dataset will be scaled down. If less than 1, the dataset + will be scaled up. + + .. versionadded:: 0.24 + + Attributes + ---------- + center_ : array of floats + The median value for each feature in the training set. + + scale_ : array of floats + The (scaled) interquartile range for each feature in the training set. + + .. versionadded:: 0.17 + *scale_* attribute. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + robust_scale : Equivalent function without the estimator API. + sklearn.decomposition.PCA : Further removes the linear correlation across + features with 'whiten=True'. + + Notes + ----- + + https://en.wikipedia.org/wiki/Median + https://en.wikipedia.org/wiki/Interquartile_range + + Examples + -------- + >>> from sklearn.preprocessing import RobustScaler + >>> X = [[ 1., -2., 2.], + ... [ -2., 1., 3.], + ... [ 4., 1., -2.]] + >>> transformer = RobustScaler().fit(X) + >>> transformer + RobustScaler() + >>> transformer.transform(X) + array([[ 0. , -2. , 0. ], + [-1. , 0. , 0.4], + [ 1. , 0. , -1.6]]) + """ + + _parameter_constraints: dict = { + "with_centering": ["boolean"], + "with_scaling": ["boolean"], + "quantile_range": [tuple], + "copy": ["boolean"], + "unit_variance": ["boolean"], + } + + def __init__( + self, + *, + with_centering=True, + with_scaling=True, + quantile_range=(25.0, 75.0), + copy=True, + unit_variance=False, + ): + self.with_centering = with_centering + self.with_scaling = with_scaling + self.quantile_range = quantile_range + self.unit_variance = unit_variance + self.copy = copy + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Compute the median and quantiles to be used for scaling. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data used to compute the median and quantiles + used for later scaling along the features axis. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + Fitted scaler. + """ + # at fit, convert sparse matrices to csc for optimized computation of + # the quantiles + X = self._validate_data( + X, + accept_sparse="csc", + dtype=FLOAT_DTYPES, + force_all_finite="allow-nan", + ) + + q_min, q_max = self.quantile_range + if not 0 <= q_min <= q_max <= 100: + raise ValueError("Invalid quantile range: %s" % str(self.quantile_range)) + + if self.with_centering: + if sparse.issparse(X): + raise ValueError( + "Cannot center sparse matrices: use `with_centering=False`" + " instead. See docstring for motivation and alternatives." + ) + self.center_ = np.nanmedian(X, axis=0) + else: + self.center_ = None + + if self.with_scaling: + quantiles = [] + for feature_idx in range(X.shape[1]): + if sparse.issparse(X): + column_nnz_data = X.data[ + X.indptr[feature_idx] : X.indptr[feature_idx + 1] + ] + column_data = np.zeros(shape=X.shape[0], dtype=X.dtype) + column_data[: len(column_nnz_data)] = column_nnz_data + else: + column_data = X[:, feature_idx] + + quantiles.append(np.nanpercentile(column_data, self.quantile_range)) + + quantiles = np.transpose(quantiles) + + self.scale_ = quantiles[1] - quantiles[0] + self.scale_ = _handle_zeros_in_scale(self.scale_, copy=False) + if self.unit_variance: + adjust = stats.norm.ppf(q_max / 100.0) - stats.norm.ppf(q_min / 100.0) + self.scale_ = self.scale_ / adjust + else: + self.scale_ = None + + return self + + def transform(self, X): + """Center and scale the data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data used to scale along the specified axis. + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + Transformed array. + """ + check_is_fitted(self) + X = self._validate_data( + X, + accept_sparse=("csr", "csc"), + copy=self.copy, + dtype=FLOAT_DTYPES, + reset=False, + force_all_finite="allow-nan", + ) + + if sparse.issparse(X): + if self.with_scaling: + inplace_column_scale(X, 1.0 / self.scale_) + else: + if self.with_centering: + X -= self.center_ + if self.with_scaling: + X /= self.scale_ + return X + + def inverse_transform(self, X): + """Scale back the data to the original representation. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The rescaled data to be transformed back. + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + Transformed array. + """ + check_is_fitted(self) + X = check_array( + X, + accept_sparse=("csr", "csc"), + copy=self.copy, + dtype=FLOAT_DTYPES, + force_all_finite="allow-nan", + ) + + if sparse.issparse(X): + if self.with_scaling: + inplace_column_scale(X, self.scale_) + else: + if self.with_scaling: + X *= self.scale_ + if self.with_centering: + X += self.center_ + return X + + def _more_tags(self): + return {"allow_nan": True} + + +@validate_params( + {"X": ["array-like", "sparse matrix"], "axis": [Options(Integral, {0, 1})]}, + prefer_skip_nested_validation=False, +) +def robust_scale( + X, + *, + axis=0, + with_centering=True, + with_scaling=True, + quantile_range=(25.0, 75.0), + copy=True, + unit_variance=False, +): + """Standardize a dataset along any axis. + + Center to the median and component wise scale + according to the interquartile range. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_sample, n_features) + The data to center and scale. + + axis : int, default=0 + Axis used to compute the medians and IQR along. If 0, + independently scale each feature, otherwise (if 1) scale + each sample. + + with_centering : bool, default=True + If `True`, center the data before scaling. + + with_scaling : bool, default=True + If `True`, scale the data to unit variance (or equivalently, + unit standard deviation). + + quantile_range : tuple (q_min, q_max), 0.0 < q_min < q_max < 100.0,\ + default=(25.0, 75.0) + Quantile range used to calculate `scale_`. By default this is equal to + the IQR, i.e., `q_min` is the first quantile and `q_max` is the third + quantile. + + .. versionadded:: 0.18 + + copy : bool, default=True + If False, try to avoid a copy and scale in place. + This is not guaranteed to always work in place; e.g. if the data is + a numpy array with an int dtype, a copy will be returned even with + copy=False. + + unit_variance : bool, default=False + If `True`, scale data so that normally distributed features have a + variance of 1. In general, if the difference between the x-values of + `q_max` and `q_min` for a standard normal distribution is greater + than 1, the dataset will be scaled down. If less than 1, the dataset + will be scaled up. + + .. versionadded:: 0.24 + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + The transformed data. + + See Also + -------- + RobustScaler : Performs centering and scaling using the Transformer API + (e.g. as part of a preprocessing :class:`~sklearn.pipeline.Pipeline`). + + Notes + ----- + This implementation will refuse to center scipy.sparse matrices + since it would make them non-sparse and would potentially crash the + program with memory exhaustion problems. + + Instead the caller is expected to either set explicitly + `with_centering=False` (in that case, only variance scaling will be + performed on the features of the CSR matrix) or to call `X.toarray()` + if he/she expects the materialized dense array to fit in memory. + + To avoid memory copy the caller should pass a CSR matrix. + + For a comparison of the different scalers, transformers, and normalizers, + see: :ref:`sphx_glr_auto_examples_preprocessing_plot_all_scaling.py`. + + .. warning:: Risk of data leak + + Do not use :func:`~sklearn.preprocessing.robust_scale` unless you know + what you are doing. A common mistake is to apply it to the entire data + *before* splitting into training and test sets. This will bias the + model evaluation because information would have leaked from the test + set to the training set. + In general, we recommend using + :class:`~sklearn.preprocessing.RobustScaler` within a + :ref:`Pipeline ` in order to prevent most risks of data + leaking: `pipe = make_pipeline(RobustScaler(), LogisticRegression())`. + + Examples + -------- + >>> from sklearn.preprocessing import robust_scale + >>> X = [[-2, 1, 2], [-1, 0, 1]] + >>> robust_scale(X, axis=0) # scale each column independently + array([[-1., 1., 1.], + [ 1., -1., -1.]]) + >>> robust_scale(X, axis=1) # scale each row independently + array([[-1.5, 0. , 0.5], + [-1. , 0. , 1. ]]) + """ + X = check_array( + X, + accept_sparse=("csr", "csc"), + copy=False, + ensure_2d=False, + dtype=FLOAT_DTYPES, + force_all_finite="allow-nan", + ) + original_ndim = X.ndim + + if original_ndim == 1: + X = X.reshape(X.shape[0], 1) + + s = RobustScaler( + with_centering=with_centering, + with_scaling=with_scaling, + quantile_range=quantile_range, + unit_variance=unit_variance, + copy=copy, + ) + if axis == 0: + X = s.fit_transform(X) + else: + X = s.fit_transform(X.T).T + + if original_ndim == 1: + X = X.ravel() + + return X + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "norm": [StrOptions({"l1", "l2", "max"})], + "axis": [Options(Integral, {0, 1})], + "copy": ["boolean"], + "return_norm": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def normalize(X, norm="l2", *, axis=1, copy=True, return_norm=False): + """Scale input vectors individually to unit norm (vector length). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to normalize, element by element. + scipy.sparse matrices should be in CSR format to avoid an + un-necessary copy. + + norm : {'l1', 'l2', 'max'}, default='l2' + The norm to use to normalize each non zero sample (or each non-zero + feature if axis is 0). + + axis : {0, 1}, default=1 + Define axis used to normalize the data along. If 1, independently + normalize each sample, otherwise (if 0) normalize each feature. + + copy : bool, default=True + If False, try to avoid a copy and normalize in place. + This is not guaranteed to always work in place; e.g. if the data is + a numpy array with an int dtype, a copy will be returned even with + copy=False. + + return_norm : bool, default=False + Whether to return the computed norms. + + Returns + ------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + Normalized input X. + + norms : ndarray of shape (n_samples, ) if axis=1 else (n_features, ) + An array of norms along given axis for X. + When X is sparse, a NotImplementedError will be raised + for norm 'l1' or 'l2'. + + See Also + -------- + Normalizer : Performs normalization using the Transformer API + (e.g. as part of a preprocessing :class:`~sklearn.pipeline.Pipeline`). + + Notes + ----- + For a comparison of the different scalers, transformers, and normalizers, + see: :ref:`sphx_glr_auto_examples_preprocessing_plot_all_scaling.py`. + + Examples + -------- + >>> from sklearn.preprocessing import normalize + >>> X = [[-2, 1, 2], [-1, 0, 1]] + >>> normalize(X, norm="l1") # L1 normalization each row independently + array([[-0.4, 0.2, 0.4], + [-0.5, 0. , 0.5]]) + >>> normalize(X, norm="l2") # L2 normalization each row independently + array([[-0.66..., 0.33..., 0.66...], + [-0.70..., 0. , 0.70...]]) + """ + if axis == 0: + sparse_format = "csc" + else: # axis == 1: + sparse_format = "csr" + + xp, _ = get_namespace(X) + + X = check_array( + X, + accept_sparse=sparse_format, + copy=copy, + estimator="the normalize function", + dtype=_array_api.supported_float_dtypes(xp), + ) + if axis == 0: + X = X.T + + if sparse.issparse(X): + if return_norm and norm in ("l1", "l2"): + raise NotImplementedError( + "return_norm=True is not implemented " + "for sparse matrices with norm 'l1' " + "or norm 'l2'" + ) + if norm == "l1": + inplace_csr_row_normalize_l1(X) + elif norm == "l2": + inplace_csr_row_normalize_l2(X) + elif norm == "max": + mins, maxes = min_max_axis(X, 1) + norms = np.maximum(abs(mins), maxes) + norms_elementwise = norms.repeat(np.diff(X.indptr)) + mask = norms_elementwise != 0 + X.data[mask] /= norms_elementwise[mask] + else: + if norm == "l1": + norms = xp.sum(xp.abs(X), axis=1) + elif norm == "l2": + norms = row_norms(X) + elif norm == "max": + norms = xp.max(xp.abs(X), axis=1) + norms = _handle_zeros_in_scale(norms, copy=False) + X /= norms[:, None] + + if axis == 0: + X = X.T + + if return_norm: + return X, norms + else: + return X + + +class Normalizer(OneToOneFeatureMixin, TransformerMixin, BaseEstimator): + """Normalize samples individually to unit norm. + + Each sample (i.e. each row of the data matrix) with at least one + non zero component is rescaled independently of other samples so + that its norm (l1, l2 or inf) equals one. + + This transformer is able to work both with dense numpy arrays and + scipy.sparse matrix (use CSR format if you want to avoid the burden of + a copy / conversion). + + Scaling inputs to unit norms is a common operation for text + classification or clustering for instance. For instance the dot + product of two l2-normalized TF-IDF vectors is the cosine similarity + of the vectors and is the base similarity metric for the Vector + Space Model commonly used by the Information Retrieval community. + + For an example visualization, refer to :ref:`Compare Normalizer with other + scalers `. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + norm : {'l1', 'l2', 'max'}, default='l2' + The norm to use to normalize each non zero sample. If norm='max' + is used, values will be rescaled by the maximum of the absolute + values. + + copy : bool, default=True + Set to False to perform inplace row normalization and avoid a + copy (if the input is already a numpy array or a scipy.sparse + CSR matrix). + + Attributes + ---------- + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + normalize : Equivalent function without the estimator API. + + Notes + ----- + This estimator is :term:`stateless` and does not need to be fitted. + However, we recommend to call :meth:`fit_transform` instead of + :meth:`transform`, as parameter validation is only performed in + :meth:`fit`. + + Examples + -------- + >>> from sklearn.preprocessing import Normalizer + >>> X = [[4, 1, 2, 2], + ... [1, 3, 9, 3], + ... [5, 7, 5, 1]] + >>> transformer = Normalizer().fit(X) # fit does nothing. + >>> transformer + Normalizer() + >>> transformer.transform(X) + array([[0.8, 0.2, 0.4, 0.4], + [0.1, 0.3, 0.9, 0.3], + [0.5, 0.7, 0.5, 0.1]]) + """ + + _parameter_constraints: dict = { + "norm": [StrOptions({"l1", "l2", "max"})], + "copy": ["boolean"], + } + + def __init__(self, norm="l2", *, copy=True): + self.norm = norm + self.copy = copy + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Only validates estimator's parameters. + + This method allows to: (i) validate the estimator's parameters and + (ii) be consistent with the scikit-learn transformer API. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to estimate the normalization parameters. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + Fitted transformer. + """ + self._validate_data(X, accept_sparse="csr") + return self + + def transform(self, X, copy=None): + """Scale each non zero row of X to unit norm. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to normalize, row by row. scipy.sparse matrices should be + in CSR format to avoid an un-necessary copy. + + copy : bool, default=None + Copy the input X or not. + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + Transformed array. + """ + copy = copy if copy is not None else self.copy + X = self._validate_data(X, accept_sparse="csr", reset=False) + return normalize(X, norm=self.norm, axis=1, copy=copy) + + def _more_tags(self): + return {"stateless": True, "array_api_support": True} + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "threshold": [Interval(Real, None, None, closed="neither")], + "copy": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def binarize(X, *, threshold=0.0, copy=True): + """Boolean thresholding of array-like or scipy.sparse matrix. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to binarize, element by element. + scipy.sparse matrices should be in CSR or CSC format to avoid an + un-necessary copy. + + threshold : float, default=0.0 + Feature values below or equal to this are replaced by 0, above it by 1. + Threshold may not be less than 0 for operations on sparse matrices. + + copy : bool, default=True + If False, try to avoid a copy and binarize in place. + This is not guaranteed to always work in place; e.g. if the data is + a numpy array with an object dtype, a copy will be returned even with + copy=False. + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + The transformed data. + + See Also + -------- + Binarizer : Performs binarization using the Transformer API + (e.g. as part of a preprocessing :class:`~sklearn.pipeline.Pipeline`). + + Examples + -------- + >>> from sklearn.preprocessing import binarize + >>> X = [[0.4, 0.6, 0.5], [0.6, 0.1, 0.2]] + >>> binarize(X, threshold=0.5) + array([[0., 1., 0.], + [1., 0., 0.]]) + """ + X = check_array(X, accept_sparse=["csr", "csc"], copy=copy) + if sparse.issparse(X): + if threshold < 0: + raise ValueError("Cannot binarize a sparse matrix with threshold < 0") + cond = X.data > threshold + not_cond = np.logical_not(cond) + X.data[cond] = 1 + X.data[not_cond] = 0 + X.eliminate_zeros() + else: + cond = X > threshold + not_cond = np.logical_not(cond) + X[cond] = 1 + X[not_cond] = 0 + return X + + +class Binarizer(OneToOneFeatureMixin, TransformerMixin, BaseEstimator): + """Binarize data (set feature values to 0 or 1) according to a threshold. + + Values greater than the threshold map to 1, while values less than + or equal to the threshold map to 0. With the default threshold of 0, + only positive values map to 1. + + Binarization is a common operation on text count data where the + analyst can decide to only consider the presence or absence of a + feature rather than a quantified number of occurrences for instance. + + It can also be used as a pre-processing step for estimators that + consider boolean random variables (e.g. modelled using the Bernoulli + distribution in a Bayesian setting). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + threshold : float, default=0.0 + Feature values below or equal to this are replaced by 0, above it by 1. + Threshold may not be less than 0 for operations on sparse matrices. + + copy : bool, default=True + Set to False to perform inplace binarization and avoid a copy (if + the input is already a numpy array or a scipy.sparse CSR matrix). + + Attributes + ---------- + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + binarize : Equivalent function without the estimator API. + KBinsDiscretizer : Bin continuous data into intervals. + OneHotEncoder : Encode categorical features as a one-hot numeric array. + + Notes + ----- + If the input is a sparse matrix, only the non-zero values are subject + to update by the :class:`Binarizer` class. + + This estimator is :term:`stateless` and does not need to be fitted. + However, we recommend to call :meth:`fit_transform` instead of + :meth:`transform`, as parameter validation is only performed in + :meth:`fit`. + + Examples + -------- + >>> from sklearn.preprocessing import Binarizer + >>> X = [[ 1., -1., 2.], + ... [ 2., 0., 0.], + ... [ 0., 1., -1.]] + >>> transformer = Binarizer().fit(X) # fit does nothing. + >>> transformer + Binarizer() + >>> transformer.transform(X) + array([[1., 0., 1.], + [1., 0., 0.], + [0., 1., 0.]]) + """ + + _parameter_constraints: dict = { + "threshold": [Real], + "copy": ["boolean"], + } + + def __init__(self, *, threshold=0.0, copy=True): + self.threshold = threshold + self.copy = copy + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Only validates estimator's parameters. + + This method allows to: (i) validate the estimator's parameters and + (ii) be consistent with the scikit-learn transformer API. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data. + + y : None + Ignored. + + Returns + ------- + self : object + Fitted transformer. + """ + self._validate_data(X, accept_sparse="csr") + return self + + def transform(self, X, copy=None): + """Binarize each element of X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to binarize, element by element. + scipy.sparse matrices should be in CSR format to avoid an + un-necessary copy. + + copy : bool + Copy the input X or not. + + Returns + ------- + X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) + Transformed array. + """ + copy = copy if copy is not None else self.copy + # TODO: This should be refactored because binarize also calls + # check_array + X = self._validate_data(X, accept_sparse=["csr", "csc"], copy=copy, reset=False) + return binarize(X, threshold=self.threshold, copy=False) + + def _more_tags(self): + return {"stateless": True} + + +class KernelCenterer(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): + r"""Center an arbitrary kernel matrix :math:`K`. + + Let define a kernel :math:`K` such that: + + .. math:: + K(X, Y) = \phi(X) . \phi(Y)^{T} + + :math:`\phi(X)` is a function mapping of rows of :math:`X` to a + Hilbert space and :math:`K` is of shape `(n_samples, n_samples)`. + + This class allows to compute :math:`\tilde{K}(X, Y)` such that: + + .. math:: + \tilde{K(X, Y)} = \tilde{\phi}(X) . \tilde{\phi}(Y)^{T} + + :math:`\tilde{\phi}(X)` is the centered mapped data in the Hilbert + space. + + `KernelCenterer` centers the features without explicitly computing the + mapping :math:`\phi(\cdot)`. Working with centered kernels is sometime + expected when dealing with algebra computation such as eigendecomposition + for :class:`~sklearn.decomposition.KernelPCA` for instance. + + Read more in the :ref:`User Guide `. + + Attributes + ---------- + K_fit_rows_ : ndarray of shape (n_samples,) + Average of each column of kernel matrix. + + K_fit_all_ : float + Average of kernel matrix. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + sklearn.kernel_approximation.Nystroem : Approximate a kernel map + using a subset of the training data. + + References + ---------- + .. [1] `Schölkopf, Bernhard, Alexander Smola, and Klaus-Robert Müller. + "Nonlinear component analysis as a kernel eigenvalue problem." + Neural computation 10.5 (1998): 1299-1319. + `_ + + Examples + -------- + >>> from sklearn.preprocessing import KernelCenterer + >>> from sklearn.metrics.pairwise import pairwise_kernels + >>> X = [[ 1., -2., 2.], + ... [ -2., 1., 3.], + ... [ 4., 1., -2.]] + >>> K = pairwise_kernels(X, metric='linear') + >>> K + array([[ 9., 2., -2.], + [ 2., 14., -13.], + [ -2., -13., 21.]]) + >>> transformer = KernelCenterer().fit(K) + >>> transformer + KernelCenterer() + >>> transformer.transform(K) + array([[ 5., 0., -5.], + [ 0., 14., -14.], + [ -5., -14., 19.]]) + """ + + def __init__(self): + # Needed for backported inspect.signature compatibility with PyPy + pass + + def fit(self, K, y=None): + """Fit KernelCenterer. + + Parameters + ---------- + K : ndarray of shape (n_samples, n_samples) + Kernel matrix. + + y : None + Ignored. + + Returns + ------- + self : object + Returns the instance itself. + """ + xp, _ = get_namespace(K) + + K = self._validate_data(K, dtype=_array_api.supported_float_dtypes(xp)) + + if K.shape[0] != K.shape[1]: + raise ValueError( + "Kernel matrix must be a square matrix." + " Input is a {}x{} matrix.".format(K.shape[0], K.shape[1]) + ) + + n_samples = K.shape[0] + self.K_fit_rows_ = xp.sum(K, axis=0) / n_samples + self.K_fit_all_ = xp.sum(self.K_fit_rows_) / n_samples + return self + + def transform(self, K, copy=True): + """Center kernel matrix. + + Parameters + ---------- + K : ndarray of shape (n_samples1, n_samples2) + Kernel matrix. + + copy : bool, default=True + Set to False to perform inplace computation. + + Returns + ------- + K_new : ndarray of shape (n_samples1, n_samples2) + Returns the instance itself. + """ + check_is_fitted(self) + + xp, _ = get_namespace(K) + + K = self._validate_data( + K, copy=copy, dtype=_array_api.supported_float_dtypes(xp), reset=False + ) + + K_pred_cols = (xp.sum(K, axis=1) / self.K_fit_rows_.shape[0])[:, None] + + K -= self.K_fit_rows_ + K -= K_pred_cols + K += self.K_fit_all_ + + return K + + @property + def _n_features_out(self): + """Number of transformed output features.""" + # Used by ClassNamePrefixFeaturesOutMixin. This model preserves the + # number of input features but this is not a one-to-one mapping in the + # usual sense. Hence the choice not to use OneToOneFeatureMixin to + # implement get_feature_names_out for this class. + return self.n_features_in_ + + def _more_tags(self): + return {"pairwise": True, "array_api_support": True} + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "value": [Interval(Real, None, None, closed="neither")], + }, + prefer_skip_nested_validation=True, +) +def add_dummy_feature(X, value=1.0): + """Augment dataset with an additional dummy feature. + + This is useful for fitting an intercept term with implementations which + cannot otherwise fit it directly. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Data. + + value : float + Value to use for the dummy feature. + + Returns + ------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features + 1) + Same data with dummy feature added as first column. + + Examples + -------- + >>> from sklearn.preprocessing import add_dummy_feature + >>> add_dummy_feature([[0, 1], [1, 0]]) + array([[1., 0., 1.], + [1., 1., 0.]]) + """ + X = check_array(X, accept_sparse=["csc", "csr", "coo"], dtype=FLOAT_DTYPES) + n_samples, n_features = X.shape + shape = (n_samples, n_features + 1) + if sparse.issparse(X): + if X.format == "coo": + # Shift columns to the right. + col = X.col + 1 + # Column indices of dummy feature are 0 everywhere. + col = np.concatenate((np.zeros(n_samples), col)) + # Row indices of dummy feature are 0, ..., n_samples-1. + row = np.concatenate((np.arange(n_samples), X.row)) + # Prepend the dummy feature n_samples times. + data = np.concatenate((np.full(n_samples, value), X.data)) + return sparse.coo_matrix((data, (row, col)), shape) + elif X.format == "csc": + # Shift index pointers since we need to add n_samples elements. + indptr = X.indptr + n_samples + # indptr[0] must be 0. + indptr = np.concatenate((np.array([0]), indptr)) + # Row indices of dummy feature are 0, ..., n_samples-1. + indices = np.concatenate((np.arange(n_samples), X.indices)) + # Prepend the dummy feature n_samples times. + data = np.concatenate((np.full(n_samples, value), X.data)) + return sparse.csc_matrix((data, indices, indptr), shape) + else: + klass = X.__class__ + return klass(add_dummy_feature(X.tocoo(), value)) + else: + return np.hstack((np.full((n_samples, 1), value), X)) + + +class QuantileTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimator): + """Transform features using quantiles information. + + This method transforms the features to follow a uniform or a normal + distribution. Therefore, for a given feature, this transformation tends + to spread out the most frequent values. It also reduces the impact of + (marginal) outliers: this is therefore a robust preprocessing scheme. + + The transformation is applied on each feature independently. First an + estimate of the cumulative distribution function of a feature is + used to map the original values to a uniform distribution. The obtained + values are then mapped to the desired output distribution using the + associated quantile function. Features values of new/unseen data that fall + below or above the fitted range will be mapped to the bounds of the output + distribution. Note that this transform is non-linear. It may distort linear + correlations between variables measured at the same scale but renders + variables measured at different scales more directly comparable. + + For example visualizations, refer to :ref:`Compare QuantileTransformer with + other scalers `. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.19 + + Parameters + ---------- + n_quantiles : int, default=1000 or n_samples + Number of quantiles to be computed. It corresponds to the number + of landmarks used to discretize the cumulative distribution function. + If n_quantiles is larger than the number of samples, n_quantiles is set + to the number of samples as a larger number of quantiles does not give + a better approximation of the cumulative distribution function + estimator. + + output_distribution : {'uniform', 'normal'}, default='uniform' + Marginal distribution for the transformed data. The choices are + 'uniform' (default) or 'normal'. + + ignore_implicit_zeros : bool, default=False + Only applies to sparse matrices. If True, the sparse entries of the + matrix are discarded to compute the quantile statistics. If False, + these entries are treated as zeros. + + subsample : int, default=10_000 + Maximum number of samples used to estimate the quantiles for + computational efficiency. Note that the subsampling procedure may + differ for value-identical sparse and dense matrices. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for subsampling and smoothing + noise. + Please see ``subsample`` for more details. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + copy : bool, default=True + Set to False to perform inplace transformation and avoid a copy (if the + input is already a numpy array). + + Attributes + ---------- + n_quantiles_ : int + The actual number of quantiles used to discretize the cumulative + distribution function. + + quantiles_ : ndarray of shape (n_quantiles, n_features) + The values corresponding the quantiles of reference. + + references_ : ndarray of shape (n_quantiles, ) + Quantiles of references. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + quantile_transform : Equivalent function without the estimator API. + PowerTransformer : Perform mapping to a normal distribution using a power + transform. + StandardScaler : Perform standardization that is faster, but less robust + to outliers. + RobustScaler : Perform robust standardization that removes the influence + of outliers but does not put outliers and inliers on the same scale. + + Notes + ----- + NaNs are treated as missing values: disregarded in fit, and maintained in + transform. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.preprocessing import QuantileTransformer + >>> rng = np.random.RandomState(0) + >>> X = np.sort(rng.normal(loc=0.5, scale=0.25, size=(25, 1)), axis=0) + >>> qt = QuantileTransformer(n_quantiles=10, random_state=0) + >>> qt.fit_transform(X) + array([...]) + """ + + _parameter_constraints: dict = { + "n_quantiles": [Interval(Integral, 1, None, closed="left")], + "output_distribution": [StrOptions({"uniform", "normal"})], + "ignore_implicit_zeros": ["boolean"], + "subsample": [Interval(Integral, 1, None, closed="left")], + "random_state": ["random_state"], + "copy": ["boolean"], + } + + def __init__( + self, + *, + n_quantiles=1000, + output_distribution="uniform", + ignore_implicit_zeros=False, + subsample=10_000, + random_state=None, + copy=True, + ): + self.n_quantiles = n_quantiles + self.output_distribution = output_distribution + self.ignore_implicit_zeros = ignore_implicit_zeros + self.subsample = subsample + self.random_state = random_state + self.copy = copy + + def _dense_fit(self, X, random_state): + """Compute percentiles for dense matrices. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The data used to scale along the features axis. + """ + if self.ignore_implicit_zeros: + warnings.warn( + "'ignore_implicit_zeros' takes effect only with" + " sparse matrix. This parameter has no effect." + ) + + n_samples, n_features = X.shape + references = self.references_ * 100 + + self.quantiles_ = [] + for col in X.T: + if self.subsample < n_samples: + subsample_idx = random_state.choice( + n_samples, size=self.subsample, replace=False + ) + col = col.take(subsample_idx, mode="clip") + self.quantiles_.append(np.nanpercentile(col, references)) + self.quantiles_ = np.transpose(self.quantiles_) + # Due to floating-point precision error in `np.nanpercentile`, + # make sure that quantiles are monotonically increasing. + # Upstream issue in numpy: + # https://github.com/numpy/numpy/issues/14685 + self.quantiles_ = np.maximum.accumulate(self.quantiles_) + + def _sparse_fit(self, X, random_state): + """Compute percentiles for sparse matrices. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + The data used to scale along the features axis. The sparse matrix + needs to be nonnegative. If a sparse matrix is provided, + it will be converted into a sparse ``csc_matrix``. + """ + n_samples, n_features = X.shape + references = self.references_ * 100 + + self.quantiles_ = [] + for feature_idx in range(n_features): + column_nnz_data = X.data[X.indptr[feature_idx] : X.indptr[feature_idx + 1]] + if len(column_nnz_data) > self.subsample: + column_subsample = self.subsample * len(column_nnz_data) // n_samples + if self.ignore_implicit_zeros: + column_data = np.zeros(shape=column_subsample, dtype=X.dtype) + else: + column_data = np.zeros(shape=self.subsample, dtype=X.dtype) + column_data[:column_subsample] = random_state.choice( + column_nnz_data, size=column_subsample, replace=False + ) + else: + if self.ignore_implicit_zeros: + column_data = np.zeros(shape=len(column_nnz_data), dtype=X.dtype) + else: + column_data = np.zeros(shape=n_samples, dtype=X.dtype) + column_data[: len(column_nnz_data)] = column_nnz_data + + if not column_data.size: + # if no nnz, an error will be raised for computing the + # quantiles. Force the quantiles to be zeros. + self.quantiles_.append([0] * len(references)) + else: + self.quantiles_.append(np.nanpercentile(column_data, references)) + self.quantiles_ = np.transpose(self.quantiles_) + # due to floating-point precision error in `np.nanpercentile`, + # make sure the quantiles are monotonically increasing + # Upstream issue in numpy: + # https://github.com/numpy/numpy/issues/14685 + self.quantiles_ = np.maximum.accumulate(self.quantiles_) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Compute the quantiles used for transforming. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data used to scale along the features axis. If a sparse + matrix is provided, it will be converted into a sparse + ``csc_matrix``. Additionally, the sparse matrix needs to be + nonnegative if `ignore_implicit_zeros` is False. + + y : None + Ignored. + + Returns + ------- + self : object + Fitted transformer. + """ + if self.n_quantiles > self.subsample: + raise ValueError( + "The number of quantiles cannot be greater than" + " the number of samples used. Got {} quantiles" + " and {} samples.".format(self.n_quantiles, self.subsample) + ) + + X = self._check_inputs(X, in_fit=True, copy=False) + n_samples = X.shape[0] + + if self.n_quantiles > n_samples: + warnings.warn( + "n_quantiles (%s) is greater than the total number " + "of samples (%s). n_quantiles is set to " + "n_samples." % (self.n_quantiles, n_samples) + ) + self.n_quantiles_ = max(1, min(self.n_quantiles, n_samples)) + + rng = check_random_state(self.random_state) + + # Create the quantiles of reference + self.references_ = np.linspace(0, 1, self.n_quantiles_, endpoint=True) + if sparse.issparse(X): + self._sparse_fit(X, rng) + else: + self._dense_fit(X, rng) + + return self + + def _transform_col(self, X_col, quantiles, inverse): + """Private function to transform a single feature.""" + + output_distribution = self.output_distribution + + if not inverse: + lower_bound_x = quantiles[0] + upper_bound_x = quantiles[-1] + lower_bound_y = 0 + upper_bound_y = 1 + else: + lower_bound_x = 0 + upper_bound_x = 1 + lower_bound_y = quantiles[0] + upper_bound_y = quantiles[-1] + # for inverse transform, match a uniform distribution + with np.errstate(invalid="ignore"): # hide NaN comparison warnings + if output_distribution == "normal": + X_col = stats.norm.cdf(X_col) + # else output distribution is already a uniform distribution + + # find index for lower and higher bounds + with np.errstate(invalid="ignore"): # hide NaN comparison warnings + if output_distribution == "normal": + lower_bounds_idx = X_col - BOUNDS_THRESHOLD < lower_bound_x + upper_bounds_idx = X_col + BOUNDS_THRESHOLD > upper_bound_x + if output_distribution == "uniform": + lower_bounds_idx = X_col == lower_bound_x + upper_bounds_idx = X_col == upper_bound_x + + isfinite_mask = ~np.isnan(X_col) + X_col_finite = X_col[isfinite_mask] + if not inverse: + # Interpolate in one direction and in the other and take the + # mean. This is in case of repeated values in the features + # and hence repeated quantiles + # + # If we don't do this, only one extreme of the duplicated is + # used (the upper when we do ascending, and the + # lower for descending). We take the mean of these two + X_col[isfinite_mask] = 0.5 * ( + np.interp(X_col_finite, quantiles, self.references_) + - np.interp(-X_col_finite, -quantiles[::-1], -self.references_[::-1]) + ) + else: + X_col[isfinite_mask] = np.interp(X_col_finite, self.references_, quantiles) + + X_col[upper_bounds_idx] = upper_bound_y + X_col[lower_bounds_idx] = lower_bound_y + # for forward transform, match the output distribution + if not inverse: + with np.errstate(invalid="ignore"): # hide NaN comparison warnings + if output_distribution == "normal": + X_col = stats.norm.ppf(X_col) + # find the value to clip the data to avoid mapping to + # infinity. Clip such that the inverse transform will be + # consistent + clip_min = stats.norm.ppf(BOUNDS_THRESHOLD - np.spacing(1)) + clip_max = stats.norm.ppf(1 - (BOUNDS_THRESHOLD - np.spacing(1))) + X_col = np.clip(X_col, clip_min, clip_max) + # else output distribution is uniform and the ppf is the + # identity function so we let X_col unchanged + + return X_col + + def _check_inputs(self, X, in_fit, accept_sparse_negative=False, copy=False): + """Check inputs before fit and transform.""" + X = self._validate_data( + X, + reset=in_fit, + accept_sparse="csc", + copy=copy, + dtype=FLOAT_DTYPES, + force_all_finite="allow-nan", + ) + # we only accept positive sparse matrix when ignore_implicit_zeros is + # false and that we call fit or transform. + with np.errstate(invalid="ignore"): # hide NaN comparison warnings + if ( + not accept_sparse_negative + and not self.ignore_implicit_zeros + and (sparse.issparse(X) and np.any(X.data < 0)) + ): + raise ValueError( + "QuantileTransformer only accepts non-negative sparse matrices." + ) + + return X + + def _transform(self, X, inverse=False): + """Forward and inverse transform. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The data used to scale along the features axis. + + inverse : bool, default=False + If False, apply forward transform. If True, apply + inverse transform. + + Returns + ------- + X : ndarray of shape (n_samples, n_features) + Projected data. + """ + if sparse.issparse(X): + for feature_idx in range(X.shape[1]): + column_slice = slice(X.indptr[feature_idx], X.indptr[feature_idx + 1]) + X.data[column_slice] = self._transform_col( + X.data[column_slice], self.quantiles_[:, feature_idx], inverse + ) + else: + for feature_idx in range(X.shape[1]): + X[:, feature_idx] = self._transform_col( + X[:, feature_idx], self.quantiles_[:, feature_idx], inverse + ) + + return X + + def transform(self, X): + """Feature-wise transformation of the data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data used to scale along the features axis. If a sparse + matrix is provided, it will be converted into a sparse + ``csc_matrix``. Additionally, the sparse matrix needs to be + nonnegative if `ignore_implicit_zeros` is False. + + Returns + ------- + Xt : {ndarray, sparse matrix} of shape (n_samples, n_features) + The projected data. + """ + check_is_fitted(self) + X = self._check_inputs(X, in_fit=False, copy=self.copy) + + return self._transform(X, inverse=False) + + def inverse_transform(self, X): + """Back-projection to the original space. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data used to scale along the features axis. If a sparse + matrix is provided, it will be converted into a sparse + ``csc_matrix``. Additionally, the sparse matrix needs to be + nonnegative if `ignore_implicit_zeros` is False. + + Returns + ------- + Xt : {ndarray, sparse matrix} of (n_samples, n_features) + The projected data. + """ + check_is_fitted(self) + X = self._check_inputs( + X, in_fit=False, accept_sparse_negative=True, copy=self.copy + ) + + return self._transform(X, inverse=True) + + def _more_tags(self): + return {"allow_nan": True} + + +@validate_params( + {"X": ["array-like", "sparse matrix"], "axis": [Options(Integral, {0, 1})]}, + prefer_skip_nested_validation=False, +) +def quantile_transform( + X, + *, + axis=0, + n_quantiles=1000, + output_distribution="uniform", + ignore_implicit_zeros=False, + subsample=int(1e5), + random_state=None, + copy=True, +): + """Transform features using quantiles information. + + This method transforms the features to follow a uniform or a normal + distribution. Therefore, for a given feature, this transformation tends + to spread out the most frequent values. It also reduces the impact of + (marginal) outliers: this is therefore a robust preprocessing scheme. + + The transformation is applied on each feature independently. First an + estimate of the cumulative distribution function of a feature is + used to map the original values to a uniform distribution. The obtained + values are then mapped to the desired output distribution using the + associated quantile function. Features values of new/unseen data that fall + below or above the fitted range will be mapped to the bounds of the output + distribution. Note that this transform is non-linear. It may distort linear + correlations between variables measured at the same scale but renders + variables measured at different scales more directly comparable. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to transform. + + axis : int, default=0 + Axis used to compute the means and standard deviations along. If 0, + transform each feature, otherwise (if 1) transform each sample. + + n_quantiles : int, default=1000 or n_samples + Number of quantiles to be computed. It corresponds to the number + of landmarks used to discretize the cumulative distribution function. + If n_quantiles is larger than the number of samples, n_quantiles is set + to the number of samples as a larger number of quantiles does not give + a better approximation of the cumulative distribution function + estimator. + + output_distribution : {'uniform', 'normal'}, default='uniform' + Marginal distribution for the transformed data. The choices are + 'uniform' (default) or 'normal'. + + ignore_implicit_zeros : bool, default=False + Only applies to sparse matrices. If True, the sparse entries of the + matrix are discarded to compute the quantile statistics. If False, + these entries are treated as zeros. + + subsample : int, default=1e5 + Maximum number of samples used to estimate the quantiles for + computational efficiency. Note that the subsampling procedure may + differ for value-identical sparse and dense matrices. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for subsampling and smoothing + noise. + Please see ``subsample`` for more details. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + copy : bool, default=True + If False, try to avoid a copy and transform in place. + This is not guaranteed to always work in place; e.g. if the data is + a numpy array with an int dtype, a copy will be returned even with + copy=False. + + .. versionchanged:: 0.23 + The default value of `copy` changed from False to True in 0.23. + + Returns + ------- + Xt : {ndarray, sparse matrix} of shape (n_samples, n_features) + The transformed data. + + See Also + -------- + QuantileTransformer : Performs quantile-based scaling using the + Transformer API (e.g. as part of a preprocessing + :class:`~sklearn.pipeline.Pipeline`). + power_transform : Maps data to a normal distribution using a + power transformation. + scale : Performs standardization that is faster, but less robust + to outliers. + robust_scale : Performs robust standardization that removes the influence + of outliers but does not put outliers and inliers on the same scale. + + Notes + ----- + NaNs are treated as missing values: disregarded in fit, and maintained in + transform. + + .. warning:: Risk of data leak + + Do not use :func:`~sklearn.preprocessing.quantile_transform` unless + you know what you are doing. A common mistake is to apply it + to the entire data *before* splitting into training and + test sets. This will bias the model evaluation because + information would have leaked from the test set to the + training set. + In general, we recommend using + :class:`~sklearn.preprocessing.QuantileTransformer` within a + :ref:`Pipeline ` in order to prevent most risks of data + leaking:`pipe = make_pipeline(QuantileTransformer(), + LogisticRegression())`. + + For a comparison of the different scalers, transformers, and normalizers, + see: :ref:`sphx_glr_auto_examples_preprocessing_plot_all_scaling.py`. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.preprocessing import quantile_transform + >>> rng = np.random.RandomState(0) + >>> X = np.sort(rng.normal(loc=0.5, scale=0.25, size=(25, 1)), axis=0) + >>> quantile_transform(X, n_quantiles=10, random_state=0, copy=True) + array([...]) + """ + n = QuantileTransformer( + n_quantiles=n_quantiles, + output_distribution=output_distribution, + subsample=subsample, + ignore_implicit_zeros=ignore_implicit_zeros, + random_state=random_state, + copy=copy, + ) + if axis == 0: + X = n.fit_transform(X) + else: # axis == 1 + X = n.fit_transform(X.T).T + return X + + +class PowerTransformer(OneToOneFeatureMixin, TransformerMixin, BaseEstimator): + """Apply a power transform featurewise to make data more Gaussian-like. + + Power transforms are a family of parametric, monotonic transformations + that are applied to make data more Gaussian-like. This is useful for + modeling issues related to heteroscedasticity (non-constant variance), + or other situations where normality is desired. + + Currently, PowerTransformer supports the Box-Cox transform and the + Yeo-Johnson transform. The optimal parameter for stabilizing variance and + minimizing skewness is estimated through maximum likelihood. + + Box-Cox requires input data to be strictly positive, while Yeo-Johnson + supports both positive or negative data. + + By default, zero-mean, unit-variance normalization is applied to the + transformed data. + + For an example visualization, refer to :ref:`Compare PowerTransformer with + other scalers `. To see the + effect of Box-Cox and Yeo-Johnson transformations on different + distributions, see: + :ref:`sphx_glr_auto_examples_preprocessing_plot_map_data_to_normal.py`. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.20 + + Parameters + ---------- + method : {'yeo-johnson', 'box-cox'}, default='yeo-johnson' + The power transform method. Available methods are: + + - 'yeo-johnson' [1]_, works with positive and negative values + - 'box-cox' [2]_, only works with strictly positive values + + standardize : bool, default=True + Set to True to apply zero-mean, unit-variance normalization to the + transformed output. + + copy : bool, default=True + Set to False to perform inplace computation during transformation. + + Attributes + ---------- + lambdas_ : ndarray of float of shape (n_features,) + The parameters of the power transformation for the selected features. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + power_transform : Equivalent function without the estimator API. + + QuantileTransformer : Maps data to a standard normal distribution with + the parameter `output_distribution='normal'`. + + Notes + ----- + NaNs are treated as missing values: disregarded in ``fit``, and maintained + in ``transform``. + + References + ---------- + + .. [1] :doi:`I.K. Yeo and R.A. Johnson, "A new family of power + transformations to improve normality or symmetry." Biometrika, + 87(4), pp.954-959, (2000). <10.1093/biomet/87.4.954>` + + .. [2] :doi:`G.E.P. Box and D.R. Cox, "An Analysis of Transformations", + Journal of the Royal Statistical Society B, 26, 211-252 (1964). + <10.1111/j.2517-6161.1964.tb00553.x>` + + Examples + -------- + >>> import numpy as np + >>> from sklearn.preprocessing import PowerTransformer + >>> pt = PowerTransformer() + >>> data = [[1, 2], [3, 2], [4, 5]] + >>> print(pt.fit(data)) + PowerTransformer() + >>> print(pt.lambdas_) + [ 1.386... -3.100...] + >>> print(pt.transform(data)) + [[-1.316... -0.707...] + [ 0.209... -0.707...] + [ 1.106... 1.414...]] + """ + + _parameter_constraints: dict = { + "method": [StrOptions({"yeo-johnson", "box-cox"})], + "standardize": ["boolean"], + "copy": ["boolean"], + } + + def __init__(self, method="yeo-johnson", *, standardize=True, copy=True): + self.method = method + self.standardize = standardize + self.copy = copy + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Estimate the optimal parameter lambda for each feature. + + The optimal lambda parameter for minimizing skewness is estimated on + each feature independently using maximum likelihood. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data used to estimate the optimal transformation parameters. + + y : None + Ignored. + + Returns + ------- + self : object + Fitted transformer. + """ + self._fit(X, y=y, force_transform=False) + return self + + @_fit_context(prefer_skip_nested_validation=True) + def fit_transform(self, X, y=None): + """Fit `PowerTransformer` to `X`, then transform `X`. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data used to estimate the optimal transformation parameters + and to be transformed using a power transformation. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_features) + Transformed data. + """ + return self._fit(X, y, force_transform=True) + + def _fit(self, X, y=None, force_transform=False): + X = self._check_input(X, in_fit=True, check_positive=True) + + if not self.copy and not force_transform: # if call from fit() + X = X.copy() # force copy so that fit does not change X inplace + + n_samples = X.shape[0] + mean = np.mean(X, axis=0, dtype=np.float64) + var = np.var(X, axis=0, dtype=np.float64) + + optim_function = { + "box-cox": self._box_cox_optimize, + "yeo-johnson": self._yeo_johnson_optimize, + }[self.method] + + transform_function = { + "box-cox": boxcox, + "yeo-johnson": self._yeo_johnson_transform, + }[self.method] + + with np.errstate(invalid="ignore"): # hide NaN warnings + self.lambdas_ = np.empty(X.shape[1], dtype=X.dtype) + for i, col in enumerate(X.T): + # For yeo-johnson, leave constant features unchanged + # lambda=1 corresponds to the identity transformation + is_constant_feature = _is_constant_feature(var[i], mean[i], n_samples) + if self.method == "yeo-johnson" and is_constant_feature: + self.lambdas_[i] = 1.0 + continue + + self.lambdas_[i] = optim_function(col) + + if self.standardize or force_transform: + X[:, i] = transform_function(X[:, i], self.lambdas_[i]) + + if self.standardize: + self._scaler = StandardScaler(copy=False).set_output(transform="default") + if force_transform: + X = self._scaler.fit_transform(X) + else: + self._scaler.fit(X) + + return X + + def transform(self, X): + """Apply the power transform to each feature using the fitted lambdas. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data to be transformed using a power transformation. + + Returns + ------- + X_trans : ndarray of shape (n_samples, n_features) + The transformed data. + """ + check_is_fitted(self) + X = self._check_input(X, in_fit=False, check_positive=True, check_shape=True) + + transform_function = { + "box-cox": boxcox, + "yeo-johnson": self._yeo_johnson_transform, + }[self.method] + for i, lmbda in enumerate(self.lambdas_): + with np.errstate(invalid="ignore"): # hide NaN warnings + X[:, i] = transform_function(X[:, i], lmbda) + + if self.standardize: + X = self._scaler.transform(X) + + return X + + def inverse_transform(self, X): + """Apply the inverse power transformation using the fitted lambdas. + + The inverse of the Box-Cox transformation is given by:: + + if lambda_ == 0: + X = exp(X_trans) + else: + X = (X_trans * lambda_ + 1) ** (1 / lambda_) + + The inverse of the Yeo-Johnson transformation is given by:: + + if X >= 0 and lambda_ == 0: + X = exp(X_trans) - 1 + elif X >= 0 and lambda_ != 0: + X = (X_trans * lambda_ + 1) ** (1 / lambda_) - 1 + elif X < 0 and lambda_ != 2: + X = 1 - (-(2 - lambda_) * X_trans + 1) ** (1 / (2 - lambda_)) + elif X < 0 and lambda_ == 2: + X = 1 - exp(-X_trans) + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The transformed data. + + Returns + ------- + X : ndarray of shape (n_samples, n_features) + The original data. + """ + check_is_fitted(self) + X = self._check_input(X, in_fit=False, check_shape=True) + + if self.standardize: + X = self._scaler.inverse_transform(X) + + inv_fun = { + "box-cox": self._box_cox_inverse_tranform, + "yeo-johnson": self._yeo_johnson_inverse_transform, + }[self.method] + for i, lmbda in enumerate(self.lambdas_): + with np.errstate(invalid="ignore"): # hide NaN warnings + X[:, i] = inv_fun(X[:, i], lmbda) + + return X + + def _box_cox_inverse_tranform(self, x, lmbda): + """Return inverse-transformed input x following Box-Cox inverse + transform with parameter lambda. + """ + if lmbda == 0: + x_inv = np.exp(x) + else: + x_inv = (x * lmbda + 1) ** (1 / lmbda) + + return x_inv + + def _yeo_johnson_inverse_transform(self, x, lmbda): + """Return inverse-transformed input x following Yeo-Johnson inverse + transform with parameter lambda. + """ + x_inv = np.zeros_like(x) + pos = x >= 0 + + # when x >= 0 + if abs(lmbda) < np.spacing(1.0): + x_inv[pos] = np.exp(x[pos]) - 1 + else: # lmbda != 0 + x_inv[pos] = np.power(x[pos] * lmbda + 1, 1 / lmbda) - 1 + + # when x < 0 + if abs(lmbda - 2) > np.spacing(1.0): + x_inv[~pos] = 1 - np.power(-(2 - lmbda) * x[~pos] + 1, 1 / (2 - lmbda)) + else: # lmbda == 2 + x_inv[~pos] = 1 - np.exp(-x[~pos]) + + return x_inv + + def _yeo_johnson_transform(self, x, lmbda): + """Return transformed input x following Yeo-Johnson transform with + parameter lambda. + """ + + out = np.zeros_like(x) + pos = x >= 0 # binary mask + + # when x >= 0 + if abs(lmbda) < np.spacing(1.0): + out[pos] = np.log1p(x[pos]) + else: # lmbda != 0 + out[pos] = (np.power(x[pos] + 1, lmbda) - 1) / lmbda + + # when x < 0 + if abs(lmbda - 2) > np.spacing(1.0): + out[~pos] = -(np.power(-x[~pos] + 1, 2 - lmbda) - 1) / (2 - lmbda) + else: # lmbda == 2 + out[~pos] = -np.log1p(-x[~pos]) + + return out + + def _box_cox_optimize(self, x): + """Find and return optimal lambda parameter of the Box-Cox transform by + MLE, for observed data x. + + We here use scipy builtins which uses the brent optimizer. + """ + mask = np.isnan(x) + if np.all(mask): + raise ValueError("Column must not be all nan.") + + # the computation of lambda is influenced by NaNs so we need to + # get rid of them + _, lmbda = stats.boxcox(x[~mask], lmbda=None) + + return lmbda + + def _yeo_johnson_optimize(self, x): + """Find and return optimal lambda parameter of the Yeo-Johnson + transform by MLE, for observed data x. + + Like for Box-Cox, MLE is done via the brent optimizer. + """ + x_tiny = np.finfo(np.float64).tiny + + def _neg_log_likelihood(lmbda): + """Return the negative log likelihood of the observed data x as a + function of lambda.""" + x_trans = self._yeo_johnson_transform(x, lmbda) + n_samples = x.shape[0] + x_trans_var = x_trans.var() + + # Reject transformed data that would raise a RuntimeWarning in np.log + if x_trans_var < x_tiny: + return np.inf + + log_var = np.log(x_trans_var) + loglike = -n_samples / 2 * log_var + loglike += (lmbda - 1) * (np.sign(x) * np.log1p(np.abs(x))).sum() + + return -loglike + + # the computation of lambda is influenced by NaNs so we need to + # get rid of them + x = x[~np.isnan(x)] + # choosing bracket -2, 2 like for boxcox + return optimize.brent(_neg_log_likelihood, brack=(-2, 2)) + + def _check_input(self, X, in_fit, check_positive=False, check_shape=False): + """Validate the input before fit and transform. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + in_fit : bool + Whether or not `_check_input` is called from `fit` or other + methods, e.g. `predict`, `transform`, etc. + + check_positive : bool, default=False + If True, check that all data is positive and non-zero (only if + ``self.method=='box-cox'``). + + check_shape : bool, default=False + If True, check that n_features matches the length of self.lambdas_ + """ + X = self._validate_data( + X, + ensure_2d=True, + dtype=FLOAT_DTYPES, + copy=self.copy, + force_all_finite="allow-nan", + reset=in_fit, + ) + + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", r"All-NaN (slice|axis) encountered") + if check_positive and self.method == "box-cox" and np.nanmin(X) <= 0: + raise ValueError( + "The Box-Cox transformation can only be " + "applied to strictly positive data" + ) + + if check_shape and not X.shape[1] == len(self.lambdas_): + raise ValueError( + "Input data has a different number of features " + "than fitting data. Should have {n}, data has {m}".format( + n=len(self.lambdas_), m=X.shape[1] + ) + ) + + return X + + def _more_tags(self): + return {"allow_nan": True} + + +@validate_params( + {"X": ["array-like"]}, + prefer_skip_nested_validation=False, +) +def power_transform(X, method="yeo-johnson", *, standardize=True, copy=True): + """Parametric, monotonic transformation to make data more Gaussian-like. + + Power transforms are a family of parametric, monotonic transformations + that are applied to make data more Gaussian-like. This is useful for + modeling issues related to heteroscedasticity (non-constant variance), + or other situations where normality is desired. + + Currently, power_transform supports the Box-Cox transform and the + Yeo-Johnson transform. The optimal parameter for stabilizing variance and + minimizing skewness is estimated through maximum likelihood. + + Box-Cox requires input data to be strictly positive, while Yeo-Johnson + supports both positive or negative data. + + By default, zero-mean, unit-variance normalization is applied to the + transformed data. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data to be transformed using a power transformation. + + method : {'yeo-johnson', 'box-cox'}, default='yeo-johnson' + The power transform method. Available methods are: + + - 'yeo-johnson' [1]_, works with positive and negative values + - 'box-cox' [2]_, only works with strictly positive values + + .. versionchanged:: 0.23 + The default value of the `method` parameter changed from + 'box-cox' to 'yeo-johnson' in 0.23. + + standardize : bool, default=True + Set to True to apply zero-mean, unit-variance normalization to the + transformed output. + + copy : bool, default=True + If False, try to avoid a copy and transform in place. + This is not guaranteed to always work in place; e.g. if the data is + a numpy array with an int dtype, a copy will be returned even with + copy=False. + + Returns + ------- + X_trans : ndarray of shape (n_samples, n_features) + The transformed data. + + See Also + -------- + PowerTransformer : Equivalent transformation with the + Transformer API (e.g. as part of a preprocessing + :class:`~sklearn.pipeline.Pipeline`). + + quantile_transform : Maps data to a standard normal distribution with + the parameter `output_distribution='normal'`. + + Notes + ----- + NaNs are treated as missing values: disregarded in ``fit``, and maintained + in ``transform``. + + For a comparison of the different scalers, transformers, and normalizers, + see: :ref:`sphx_glr_auto_examples_preprocessing_plot_all_scaling.py`. + + References + ---------- + + .. [1] I.K. Yeo and R.A. Johnson, "A new family of power transformations to + improve normality or symmetry." Biometrika, 87(4), pp.954-959, + (2000). + + .. [2] G.E.P. Box and D.R. Cox, "An Analysis of Transformations", Journal + of the Royal Statistical Society B, 26, 211-252 (1964). + + Examples + -------- + >>> import numpy as np + >>> from sklearn.preprocessing import power_transform + >>> data = [[1, 2], [3, 2], [4, 5]] + >>> print(power_transform(data, method='box-cox')) + [[-1.332... -0.707...] + [ 0.256... -0.707...] + [ 1.076... 1.414...]] + + .. warning:: Risk of data leak. + Do not use :func:`~sklearn.preprocessing.power_transform` unless you + know what you are doing. A common mistake is to apply it to the entire + data *before* splitting into training and test sets. This will bias the + model evaluation because information would have leaked from the test + set to the training set. + In general, we recommend using + :class:`~sklearn.preprocessing.PowerTransformer` within a + :ref:`Pipeline ` in order to prevent most risks of data + leaking, e.g.: `pipe = make_pipeline(PowerTransformer(), + LogisticRegression())`. + """ + pt = PowerTransformer(method=method, standardize=standardize, copy=copy) + return pt.fit_transform(X) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_discretization.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_discretization.py new file mode 100644 index 0000000000000000000000000000000000000000..033bdd960d2b215bde276e17637858b62e98ffa0 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_discretization.py @@ -0,0 +1,472 @@ +# Author: Henry Lin +# Tom Dupré la Tour + +# License: BSD + + +import warnings +from numbers import Integral + +import numpy as np + +from ..base import BaseEstimator, TransformerMixin, _fit_context +from ..utils import _safe_indexing +from ..utils._param_validation import Hidden, Interval, Options, StrOptions +from ..utils.stats import _weighted_percentile +from ..utils.validation import ( + _check_feature_names_in, + _check_sample_weight, + check_array, + check_is_fitted, + check_random_state, +) +from ._encoders import OneHotEncoder + + +class KBinsDiscretizer(TransformerMixin, BaseEstimator): + """ + Bin continuous data into intervals. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.20 + + Parameters + ---------- + n_bins : int or array-like of shape (n_features,), default=5 + The number of bins to produce. Raises ValueError if ``n_bins < 2``. + + encode : {'onehot', 'onehot-dense', 'ordinal'}, default='onehot' + Method used to encode the transformed result. + + - 'onehot': Encode the transformed result with one-hot encoding + and return a sparse matrix. Ignored features are always + stacked to the right. + - 'onehot-dense': Encode the transformed result with one-hot encoding + and return a dense array. Ignored features are always + stacked to the right. + - 'ordinal': Return the bin identifier encoded as an integer value. + + strategy : {'uniform', 'quantile', 'kmeans'}, default='quantile' + Strategy used to define the widths of the bins. + + - 'uniform': All bins in each feature have identical widths. + - 'quantile': All bins in each feature have the same number of points. + - 'kmeans': Values in each bin have the same nearest center of a 1D + k-means cluster. + + For an example of the different strategies see: + :ref:`sphx_glr_auto_examples_preprocessing_plot_discretization_strategies.py`. + + dtype : {np.float32, np.float64}, default=None + The desired data-type for the output. If None, output dtype is + consistent with input dtype. Only np.float32 and np.float64 are + supported. + + .. versionadded:: 0.24 + + subsample : int or None, default='warn' + Maximum number of samples, used to fit the model, for computational + efficiency. Defaults to 200_000 when `strategy='quantile'` and to `None` + when `strategy='uniform'` or `strategy='kmeans'`. + `subsample=None` means that all the training samples are used when + computing the quantiles that determine the binning thresholds. + Since quantile computation relies on sorting each column of `X` and + that sorting has an `n log(n)` time complexity, + it is recommended to use subsampling on datasets with a + very large number of samples. + + .. versionchanged:: 1.3 + The default value of `subsample` changed from `None` to `200_000` when + `strategy="quantile"`. + + .. versionchanged:: 1.5 + The default value of `subsample` changed from `None` to `200_000` when + `strategy="uniform"` or `strategy="kmeans"`. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for subsampling. + Pass an int for reproducible results across multiple function calls. + See the `subsample` parameter for more details. + See :term:`Glossary `. + + .. versionadded:: 1.1 + + Attributes + ---------- + bin_edges_ : ndarray of ndarray of shape (n_features,) + The edges of each bin. Contain arrays of varying shapes ``(n_bins_, )`` + Ignored features will have empty arrays. + + n_bins_ : ndarray of shape (n_features,), dtype=np.int64 + Number of bins per feature. Bins whose width are too small + (i.e., <= 1e-8) are removed with a warning. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + Binarizer : Class used to bin values as ``0`` or + ``1`` based on a parameter ``threshold``. + + Notes + ----- + + For a visualization of discretization on different datasets refer to + :ref:`sphx_glr_auto_examples_preprocessing_plot_discretization_classification.py`. + On the effect of discretization on linear models see: + :ref:`sphx_glr_auto_examples_preprocessing_plot_discretization.py`. + + In bin edges for feature ``i``, the first and last values are used only for + ``inverse_transform``. During transform, bin edges are extended to:: + + np.concatenate([-np.inf, bin_edges_[i][1:-1], np.inf]) + + You can combine ``KBinsDiscretizer`` with + :class:`~sklearn.compose.ColumnTransformer` if you only want to preprocess + part of the features. + + ``KBinsDiscretizer`` might produce constant features (e.g., when + ``encode = 'onehot'`` and certain bins do not contain any data). + These features can be removed with feature selection algorithms + (e.g., :class:`~sklearn.feature_selection.VarianceThreshold`). + + Examples + -------- + >>> from sklearn.preprocessing import KBinsDiscretizer + >>> X = [[-2, 1, -4, -1], + ... [-1, 2, -3, -0.5], + ... [ 0, 3, -2, 0.5], + ... [ 1, 4, -1, 2]] + >>> est = KBinsDiscretizer( + ... n_bins=3, encode='ordinal', strategy='uniform', subsample=None + ... ) + >>> est.fit(X) + KBinsDiscretizer(...) + >>> Xt = est.transform(X) + >>> Xt # doctest: +SKIP + array([[ 0., 0., 0., 0.], + [ 1., 1., 1., 0.], + [ 2., 2., 2., 1.], + [ 2., 2., 2., 2.]]) + + Sometimes it may be useful to convert the data back into the original + feature space. The ``inverse_transform`` function converts the binned + data into the original feature space. Each value will be equal to the mean + of the two bin edges. + + >>> est.bin_edges_[0] + array([-2., -1., 0., 1.]) + >>> est.inverse_transform(Xt) + array([[-1.5, 1.5, -3.5, -0.5], + [-0.5, 2.5, -2.5, -0.5], + [ 0.5, 3.5, -1.5, 0.5], + [ 0.5, 3.5, -1.5, 1.5]]) + """ + + _parameter_constraints: dict = { + "n_bins": [Interval(Integral, 2, None, closed="left"), "array-like"], + "encode": [StrOptions({"onehot", "onehot-dense", "ordinal"})], + "strategy": [StrOptions({"uniform", "quantile", "kmeans"})], + "dtype": [Options(type, {np.float64, np.float32}), None], + "subsample": [ + Interval(Integral, 1, None, closed="left"), + None, + Hidden(StrOptions({"warn"})), + ], + "random_state": ["random_state"], + } + + def __init__( + self, + n_bins=5, + *, + encode="onehot", + strategy="quantile", + dtype=None, + subsample="warn", + random_state=None, + ): + self.n_bins = n_bins + self.encode = encode + self.strategy = strategy + self.dtype = dtype + self.subsample = subsample + self.random_state = random_state + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None, sample_weight=None): + """ + Fit the estimator. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Data to be discretized. + + y : None + Ignored. This parameter exists only for compatibility with + :class:`~sklearn.pipeline.Pipeline`. + + sample_weight : ndarray of shape (n_samples,) + Contains weight values to be associated with each sample. + Only possible when `strategy` is set to `"quantile"`. + + .. versionadded:: 1.3 + + Returns + ------- + self : object + Returns the instance itself. + """ + X = self._validate_data(X, dtype="numeric") + + if self.dtype in (np.float64, np.float32): + output_dtype = self.dtype + else: # self.dtype is None + output_dtype = X.dtype + + n_samples, n_features = X.shape + + if sample_weight is not None and self.strategy == "uniform": + raise ValueError( + "`sample_weight` was provided but it cannot be " + "used with strategy='uniform'. Got strategy=" + f"{self.strategy!r} instead." + ) + + if self.strategy in ("uniform", "kmeans") and self.subsample == "warn": + warnings.warn( + ( + "In version 1.5 onwards, subsample=200_000 " + "will be used by default. Set subsample explicitly to " + "silence this warning in the mean time. Set " + "subsample=None to disable subsampling explicitly." + ), + FutureWarning, + ) + + subsample = self.subsample + if subsample == "warn": + subsample = 200000 if self.strategy == "quantile" else None + if subsample is not None and n_samples > subsample: + rng = check_random_state(self.random_state) + subsample_idx = rng.choice(n_samples, size=subsample, replace=False) + X = _safe_indexing(X, subsample_idx) + + n_features = X.shape[1] + n_bins = self._validate_n_bins(n_features) + + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + bin_edges = np.zeros(n_features, dtype=object) + for jj in range(n_features): + column = X[:, jj] + col_min, col_max = column.min(), column.max() + + if col_min == col_max: + warnings.warn( + "Feature %d is constant and will be replaced with 0." % jj + ) + n_bins[jj] = 1 + bin_edges[jj] = np.array([-np.inf, np.inf]) + continue + + if self.strategy == "uniform": + bin_edges[jj] = np.linspace(col_min, col_max, n_bins[jj] + 1) + + elif self.strategy == "quantile": + quantiles = np.linspace(0, 100, n_bins[jj] + 1) + if sample_weight is None: + bin_edges[jj] = np.asarray(np.percentile(column, quantiles)) + else: + bin_edges[jj] = np.asarray( + [ + _weighted_percentile(column, sample_weight, q) + for q in quantiles + ], + dtype=np.float64, + ) + elif self.strategy == "kmeans": + from ..cluster import KMeans # fixes import loops + + # Deterministic initialization with uniform spacing + uniform_edges = np.linspace(col_min, col_max, n_bins[jj] + 1) + init = (uniform_edges[1:] + uniform_edges[:-1])[:, None] * 0.5 + + # 1D k-means procedure + km = KMeans(n_clusters=n_bins[jj], init=init, n_init=1) + centers = km.fit( + column[:, None], sample_weight=sample_weight + ).cluster_centers_[:, 0] + # Must sort, centers may be unsorted even with sorted init + centers.sort() + bin_edges[jj] = (centers[1:] + centers[:-1]) * 0.5 + bin_edges[jj] = np.r_[col_min, bin_edges[jj], col_max] + + # Remove bins whose width are too small (i.e., <= 1e-8) + if self.strategy in ("quantile", "kmeans"): + mask = np.ediff1d(bin_edges[jj], to_begin=np.inf) > 1e-8 + bin_edges[jj] = bin_edges[jj][mask] + if len(bin_edges[jj]) - 1 != n_bins[jj]: + warnings.warn( + "Bins whose width are too small (i.e., <= " + "1e-8) in feature %d are removed. Consider " + "decreasing the number of bins." % jj + ) + n_bins[jj] = len(bin_edges[jj]) - 1 + + self.bin_edges_ = bin_edges + self.n_bins_ = n_bins + + if "onehot" in self.encode: + self._encoder = OneHotEncoder( + categories=[np.arange(i) for i in self.n_bins_], + sparse_output=self.encode == "onehot", + dtype=output_dtype, + ) + # Fit the OneHotEncoder with toy datasets + # so that it's ready for use after the KBinsDiscretizer is fitted + self._encoder.fit(np.zeros((1, len(self.n_bins_)))) + + return self + + def _validate_n_bins(self, n_features): + """Returns n_bins_, the number of bins per feature.""" + orig_bins = self.n_bins + if isinstance(orig_bins, Integral): + return np.full(n_features, orig_bins, dtype=int) + + n_bins = check_array(orig_bins, dtype=int, copy=True, ensure_2d=False) + + if n_bins.ndim > 1 or n_bins.shape[0] != n_features: + raise ValueError("n_bins must be a scalar or array of shape (n_features,).") + + bad_nbins_value = (n_bins < 2) | (n_bins != orig_bins) + + violating_indices = np.where(bad_nbins_value)[0] + if violating_indices.shape[0] > 0: + indices = ", ".join(str(i) for i in violating_indices) + raise ValueError( + "{} received an invalid number " + "of bins at indices {}. Number of bins " + "must be at least 2, and must be an int.".format( + KBinsDiscretizer.__name__, indices + ) + ) + return n_bins + + def transform(self, X): + """ + Discretize the data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Data to be discretized. + + Returns + ------- + Xt : {ndarray, sparse matrix}, dtype={np.float32, np.float64} + Data in the binned space. Will be a sparse matrix if + `self.encode='onehot'` and ndarray otherwise. + """ + check_is_fitted(self) + + # check input and attribute dtypes + dtype = (np.float64, np.float32) if self.dtype is None else self.dtype + Xt = self._validate_data(X, copy=True, dtype=dtype, reset=False) + + bin_edges = self.bin_edges_ + for jj in range(Xt.shape[1]): + Xt[:, jj] = np.searchsorted(bin_edges[jj][1:-1], Xt[:, jj], side="right") + + if self.encode == "ordinal": + return Xt + + dtype_init = None + if "onehot" in self.encode: + dtype_init = self._encoder.dtype + self._encoder.dtype = Xt.dtype + try: + Xt_enc = self._encoder.transform(Xt) + finally: + # revert the initial dtype to avoid modifying self. + self._encoder.dtype = dtype_init + return Xt_enc + + def inverse_transform(self, Xt): + """ + Transform discretized data back to original feature space. + + Note that this function does not regenerate the original data + due to discretization rounding. + + Parameters + ---------- + Xt : array-like of shape (n_samples, n_features) + Transformed data in the binned space. + + Returns + ------- + Xinv : ndarray, dtype={np.float32, np.float64} + Data in the original feature space. + """ + check_is_fitted(self) + + if "onehot" in self.encode: + Xt = self._encoder.inverse_transform(Xt) + + Xinv = check_array(Xt, copy=True, dtype=(np.float64, np.float32)) + n_features = self.n_bins_.shape[0] + if Xinv.shape[1] != n_features: + raise ValueError( + "Incorrect number of features. Expecting {}, received {}.".format( + n_features, Xinv.shape[1] + ) + ) + + for jj in range(n_features): + bin_edges = self.bin_edges_[jj] + bin_centers = (bin_edges[1:] + bin_edges[:-1]) * 0.5 + Xinv[:, jj] = bin_centers[(Xinv[:, jj]).astype(np.int64)] + + return Xinv + + def get_feature_names_out(self, input_features=None): + """Get output feature names. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input features. + + - If `input_features` is `None`, then `feature_names_in_` is + used as feature names in. If `feature_names_in_` is not defined, + then the following input feature names are generated: + `["x0", "x1", ..., "x(n_features_in_ - 1)"]`. + - If `input_features` is an array-like, then `input_features` must + match `feature_names_in_` if `feature_names_in_` is defined. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + check_is_fitted(self, "n_features_in_") + input_features = _check_feature_names_in(self, input_features) + if hasattr(self, "_encoder"): + return self._encoder.get_feature_names_out(input_features) + + # ordinal encoding + return input_features diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_encoders.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..3feadc68e8d2dc3d7829363a9ba9f2db1b6d6910 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_encoders.py @@ -0,0 +1,1678 @@ +# Authors: Andreas Mueller +# Joris Van den Bossche +# License: BSD 3 clause + +import numbers +import warnings +from numbers import Integral + +import numpy as np +from scipy import sparse + +from ..base import BaseEstimator, OneToOneFeatureMixin, TransformerMixin, _fit_context +from ..utils import _safe_indexing, check_array, is_scalar_nan +from ..utils._encode import _check_unknown, _encode, _get_counts, _unique +from ..utils._mask import _get_mask +from ..utils._param_validation import Interval, RealNotInt, StrOptions +from ..utils._set_output import _get_output_config +from ..utils.validation import _check_feature_names_in, check_is_fitted + +__all__ = ["OneHotEncoder", "OrdinalEncoder"] + + +class _BaseEncoder(TransformerMixin, BaseEstimator): + """ + Base class for encoders that includes the code to categorize and + transform the input features. + + """ + + def _check_X(self, X, force_all_finite=True): + """ + Perform custom check_array: + - convert list of strings to object dtype + - check for missing values for object dtype data (check_array does + not do that) + - return list of features (arrays): this list of features is + constructed feature by feature to preserve the data types + of pandas DataFrame columns, as otherwise information is lost + and cannot be used, e.g. for the `categories_` attribute. + + """ + if not (hasattr(X, "iloc") and getattr(X, "ndim", 0) == 2): + # if not a dataframe, do normal check_array validation + X_temp = check_array(X, dtype=None, force_all_finite=force_all_finite) + if not hasattr(X, "dtype") and np.issubdtype(X_temp.dtype, np.str_): + X = check_array(X, dtype=object, force_all_finite=force_all_finite) + else: + X = X_temp + needs_validation = False + else: + # pandas dataframe, do validation later column by column, in order + # to keep the dtype information to be used in the encoder. + needs_validation = force_all_finite + + n_samples, n_features = X.shape + X_columns = [] + + for i in range(n_features): + Xi = _safe_indexing(X, indices=i, axis=1) + Xi = check_array( + Xi, ensure_2d=False, dtype=None, force_all_finite=needs_validation + ) + X_columns.append(Xi) + + return X_columns, n_samples, n_features + + def _fit( + self, + X, + handle_unknown="error", + force_all_finite=True, + return_counts=False, + return_and_ignore_missing_for_infrequent=False, + ): + self._check_infrequent_enabled() + self._check_n_features(X, reset=True) + self._check_feature_names(X, reset=True) + X_list, n_samples, n_features = self._check_X( + X, force_all_finite=force_all_finite + ) + self.n_features_in_ = n_features + + if self.categories != "auto": + if len(self.categories) != n_features: + raise ValueError( + "Shape mismatch: if categories is an array," + " it has to be of shape (n_features,)." + ) + + self.categories_ = [] + category_counts = [] + compute_counts = return_counts or self._infrequent_enabled + + for i in range(n_features): + Xi = X_list[i] + + if self.categories == "auto": + result = _unique(Xi, return_counts=compute_counts) + if compute_counts: + cats, counts = result + category_counts.append(counts) + else: + cats = result + else: + if np.issubdtype(Xi.dtype, np.str_): + # Always convert string categories to objects to avoid + # unexpected string truncation for longer category labels + # passed in the constructor. + Xi_dtype = object + else: + Xi_dtype = Xi.dtype + + cats = np.array(self.categories[i], dtype=Xi_dtype) + if ( + cats.dtype == object + and isinstance(cats[0], bytes) + and Xi.dtype.kind != "S" + ): + msg = ( + f"In column {i}, the predefined categories have type 'bytes'" + " which is incompatible with values of type" + f" '{type(Xi[0]).__name__}'." + ) + raise ValueError(msg) + + # `nan` must be the last stated category + for category in cats[:-1]: + if is_scalar_nan(category): + raise ValueError( + "Nan should be the last element in user" + f" provided categories, see categories {cats}" + f" in column #{i}" + ) + + if cats.size != len(_unique(cats)): + msg = ( + f"In column {i}, the predefined categories" + " contain duplicate elements." + ) + raise ValueError(msg) + + if Xi.dtype.kind not in "OUS": + sorted_cats = np.sort(cats) + error_msg = ( + "Unsorted categories are not supported for numerical categories" + ) + # if there are nans, nan should be the last element + stop_idx = -1 if np.isnan(sorted_cats[-1]) else None + if np.any(sorted_cats[:stop_idx] != cats[:stop_idx]): + raise ValueError(error_msg) + + if handle_unknown == "error": + diff = _check_unknown(Xi, cats) + if diff: + msg = ( + "Found unknown categories {0} in column {1}" + " during fit".format(diff, i) + ) + raise ValueError(msg) + if compute_counts: + category_counts.append(_get_counts(Xi, cats)) + + self.categories_.append(cats) + + output = {"n_samples": n_samples} + if return_counts: + output["category_counts"] = category_counts + + missing_indices = {} + if return_and_ignore_missing_for_infrequent: + for feature_idx, categories_for_idx in enumerate(self.categories_): + if is_scalar_nan(categories_for_idx[-1]): + # `nan` values can only be placed in the latest position + missing_indices[feature_idx] = categories_for_idx.size - 1 + output["missing_indices"] = missing_indices + + if self._infrequent_enabled: + self._fit_infrequent_category_mapping( + n_samples, + category_counts, + missing_indices, + ) + return output + + def _transform( + self, + X, + handle_unknown="error", + force_all_finite=True, + warn_on_unknown=False, + ignore_category_indices=None, + ): + X_list, n_samples, n_features = self._check_X( + X, force_all_finite=force_all_finite + ) + self._check_feature_names(X, reset=False) + self._check_n_features(X, reset=False) + + X_int = np.zeros((n_samples, n_features), dtype=int) + X_mask = np.ones((n_samples, n_features), dtype=bool) + + columns_with_unknown = [] + for i in range(n_features): + Xi = X_list[i] + diff, valid_mask = _check_unknown(Xi, self.categories_[i], return_mask=True) + + if not np.all(valid_mask): + if handle_unknown == "error": + msg = ( + "Found unknown categories {0} in column {1}" + " during transform".format(diff, i) + ) + raise ValueError(msg) + else: + if warn_on_unknown: + columns_with_unknown.append(i) + # Set the problematic rows to an acceptable value and + # continue `The rows are marked `X_mask` and will be + # removed later. + X_mask[:, i] = valid_mask + # cast Xi into the largest string type necessary + # to handle different lengths of numpy strings + if ( + self.categories_[i].dtype.kind in ("U", "S") + and self.categories_[i].itemsize > Xi.itemsize + ): + Xi = Xi.astype(self.categories_[i].dtype) + elif self.categories_[i].dtype.kind == "O" and Xi.dtype.kind == "U": + # categories are objects and Xi are numpy strings. + # Cast Xi to an object dtype to prevent truncation + # when setting invalid values. + Xi = Xi.astype("O") + else: + Xi = Xi.copy() + + Xi[~valid_mask] = self.categories_[i][0] + # We use check_unknown=False, since _check_unknown was + # already called above. + X_int[:, i] = _encode(Xi, uniques=self.categories_[i], check_unknown=False) + if columns_with_unknown: + warnings.warn( + ( + "Found unknown categories in columns " + f"{columns_with_unknown} during transform. These " + "unknown categories will be encoded as all zeros" + ), + UserWarning, + ) + + self._map_infrequent_categories(X_int, X_mask, ignore_category_indices) + return X_int, X_mask + + @property + def infrequent_categories_(self): + """Infrequent categories for each feature.""" + # raises an AttributeError if `_infrequent_indices` is not defined + infrequent_indices = self._infrequent_indices + return [ + None if indices is None else category[indices] + for category, indices in zip(self.categories_, infrequent_indices) + ] + + def _check_infrequent_enabled(self): + """ + This functions checks whether _infrequent_enabled is True or False. + This has to be called after parameter validation in the fit function. + """ + max_categories = getattr(self, "max_categories", None) + min_frequency = getattr(self, "min_frequency", None) + self._infrequent_enabled = ( + max_categories is not None and max_categories >= 1 + ) or min_frequency is not None + + def _identify_infrequent(self, category_count, n_samples, col_idx): + """Compute the infrequent indices. + + Parameters + ---------- + category_count : ndarray of shape (n_cardinality,) + Category counts. + + n_samples : int + Number of samples. + + col_idx : int + Index of the current category. Only used for the error message. + + Returns + ------- + output : ndarray of shape (n_infrequent_categories,) or None + If there are infrequent categories, indices of infrequent + categories. Otherwise None. + """ + if isinstance(self.min_frequency, numbers.Integral): + infrequent_mask = category_count < self.min_frequency + elif isinstance(self.min_frequency, numbers.Real): + min_frequency_abs = n_samples * self.min_frequency + infrequent_mask = category_count < min_frequency_abs + else: + infrequent_mask = np.zeros(category_count.shape[0], dtype=bool) + + n_current_features = category_count.size - infrequent_mask.sum() + 1 + if self.max_categories is not None and self.max_categories < n_current_features: + # max_categories includes the one infrequent category + frequent_category_count = self.max_categories - 1 + if frequent_category_count == 0: + # All categories are infrequent + infrequent_mask[:] = True + else: + # stable sort to preserve original count order + smallest_levels = np.argsort(category_count, kind="mergesort")[ + :-frequent_category_count + ] + infrequent_mask[smallest_levels] = True + + output = np.flatnonzero(infrequent_mask) + return output if output.size > 0 else None + + def _fit_infrequent_category_mapping( + self, n_samples, category_counts, missing_indices + ): + """Fit infrequent categories. + + Defines the private attribute: `_default_to_infrequent_mappings`. For + feature `i`, `_default_to_infrequent_mappings[i]` defines the mapping + from the integer encoding returned by `super().transform()` into + infrequent categories. If `_default_to_infrequent_mappings[i]` is None, + there were no infrequent categories in the training set. + + For example if categories 0, 2 and 4 were frequent, while categories + 1, 3, 5 were infrequent for feature 7, then these categories are mapped + to a single output: + `_default_to_infrequent_mappings[7] = array([0, 3, 1, 3, 2, 3])` + + Defines private attribute: `_infrequent_indices`. `_infrequent_indices[i]` + is an array of indices such that + `categories_[i][_infrequent_indices[i]]` are all the infrequent category + labels. If the feature `i` has no infrequent categories + `_infrequent_indices[i]` is None. + + .. versionadded:: 1.1 + + Parameters + ---------- + n_samples : int + Number of samples in training set. + category_counts: list of ndarray + `category_counts[i]` is the category counts corresponding to + `self.categories_[i]`. + missing_indices : dict + Dict mapping from feature_idx to category index with a missing value. + """ + # Remove missing value from counts, so it is not considered as infrequent + if missing_indices: + category_counts_ = [] + for feature_idx, count in enumerate(category_counts): + if feature_idx in missing_indices: + category_counts_.append( + np.delete(count, missing_indices[feature_idx]) + ) + else: + category_counts_.append(count) + else: + category_counts_ = category_counts + + self._infrequent_indices = [ + self._identify_infrequent(category_count, n_samples, col_idx) + for col_idx, category_count in enumerate(category_counts_) + ] + + # compute mapping from default mapping to infrequent mapping + self._default_to_infrequent_mappings = [] + + for feature_idx, infreq_idx in enumerate(self._infrequent_indices): + cats = self.categories_[feature_idx] + # no infrequent categories + if infreq_idx is None: + self._default_to_infrequent_mappings.append(None) + continue + + n_cats = len(cats) + if feature_idx in missing_indices: + # Missing index was removed from this category when computing + # infrequent indices, thus we need to decrease the number of + # total categories when considering the infrequent mapping. + n_cats -= 1 + + # infrequent indices exist + mapping = np.empty(n_cats, dtype=np.int64) + n_infrequent_cats = infreq_idx.size + + # infrequent categories are mapped to the last element. + n_frequent_cats = n_cats - n_infrequent_cats + mapping[infreq_idx] = n_frequent_cats + + frequent_indices = np.setdiff1d(np.arange(n_cats), infreq_idx) + mapping[frequent_indices] = np.arange(n_frequent_cats) + + self._default_to_infrequent_mappings.append(mapping) + + def _map_infrequent_categories(self, X_int, X_mask, ignore_category_indices): + """Map infrequent categories to integer representing the infrequent category. + + This modifies X_int in-place. Values that were invalid based on `X_mask` + are mapped to the infrequent category if there was an infrequent + category for that feature. + + Parameters + ---------- + X_int: ndarray of shape (n_samples, n_features) + Integer encoded categories. + + X_mask: ndarray of shape (n_samples, n_features) + Bool mask for valid values in `X_int`. + + ignore_category_indices : dict + Dictionary mapping from feature_idx to category index to ignore. + Ignored indexes will not be grouped and the original ordinal encoding + will remain. + """ + if not self._infrequent_enabled: + return + + ignore_category_indices = ignore_category_indices or {} + + for col_idx in range(X_int.shape[1]): + infrequent_idx = self._infrequent_indices[col_idx] + if infrequent_idx is None: + continue + + X_int[~X_mask[:, col_idx], col_idx] = infrequent_idx[0] + if self.handle_unknown == "infrequent_if_exist": + # All the unknown values are now mapped to the + # infrequent_idx[0], which makes the unknown values valid + # This is needed in `transform` when the encoding is formed + # using `X_mask`. + X_mask[:, col_idx] = True + + # Remaps encoding in `X_int` where the infrequent categories are + # grouped together. + for i, mapping in enumerate(self._default_to_infrequent_mappings): + if mapping is None: + continue + + if i in ignore_category_indices: + # Update rows that are **not** ignored + rows_to_update = X_int[:, i] != ignore_category_indices[i] + else: + rows_to_update = slice(None) + + X_int[rows_to_update, i] = np.take(mapping, X_int[rows_to_update, i]) + + def _more_tags(self): + return {"X_types": ["2darray", "categorical"], "allow_nan": True} + + +class OneHotEncoder(_BaseEncoder): + """ + Encode categorical features as a one-hot numeric array. + + The input to this transformer should be an array-like of integers or + strings, denoting the values taken on by categorical (discrete) features. + The features are encoded using a one-hot (aka 'one-of-K' or 'dummy') + encoding scheme. This creates a binary column for each category and + returns a sparse matrix or dense array (depending on the ``sparse_output`` + parameter). + + By default, the encoder derives the categories based on the unique values + in each feature. Alternatively, you can also specify the `categories` + manually. + + This encoding is needed for feeding categorical data to many scikit-learn + estimators, notably linear models and SVMs with the standard kernels. + + Note: a one-hot encoding of y labels should use a LabelBinarizer + instead. + + Read more in the :ref:`User Guide `. + For a comparison of different encoders, refer to: + :ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder.py`. + + Parameters + ---------- + categories : 'auto' or a list of array-like, default='auto' + Categories (unique values) per feature: + + - 'auto' : Determine categories automatically from the training data. + - list : ``categories[i]`` holds the categories expected in the ith + column. The passed categories should not mix strings and numeric + values within a single feature, and should be sorted in case of + numeric values. + + The used categories can be found in the ``categories_`` attribute. + + .. versionadded:: 0.20 + + drop : {'first', 'if_binary'} or an array-like of shape (n_features,), \ + default=None + Specifies a methodology to use to drop one of the categories per + feature. This is useful in situations where perfectly collinear + features cause problems, such as when feeding the resulting data + into an unregularized linear regression model. + + However, dropping one category breaks the symmetry of the original + representation and can therefore induce a bias in downstream models, + for instance for penalized linear classification or regression models. + + - None : retain all features (the default). + - 'first' : drop the first category in each feature. If only one + category is present, the feature will be dropped entirely. + - 'if_binary' : drop the first category in each feature with two + categories. Features with 1 or more than 2 categories are + left intact. + - array : ``drop[i]`` is the category in feature ``X[:, i]`` that + should be dropped. + + When `max_categories` or `min_frequency` is configured to group + infrequent categories, the dropping behavior is handled after the + grouping. + + .. versionadded:: 0.21 + The parameter `drop` was added in 0.21. + + .. versionchanged:: 0.23 + The option `drop='if_binary'` was added in 0.23. + + .. versionchanged:: 1.1 + Support for dropping infrequent categories. + + sparse_output : bool, default=True + When ``True``, it returns a :class:`scipy.sparse.csr_matrix`, + i.e. a sparse matrix in "Compressed Sparse Row" (CSR) format. + + .. versionadded:: 1.2 + `sparse` was renamed to `sparse_output` + + dtype : number type, default=np.float64 + Desired dtype of output. + + handle_unknown : {'error', 'ignore', 'infrequent_if_exist'}, \ + default='error' + Specifies the way unknown categories are handled during :meth:`transform`. + + - 'error' : Raise an error if an unknown category is present during transform. + - 'ignore' : When an unknown category is encountered during + transform, the resulting one-hot encoded columns for this feature + will be all zeros. In the inverse transform, an unknown category + will be denoted as None. + - 'infrequent_if_exist' : When an unknown category is encountered + during transform, the resulting one-hot encoded columns for this + feature will map to the infrequent category if it exists. The + infrequent category will be mapped to the last position in the + encoding. During inverse transform, an unknown category will be + mapped to the category denoted `'infrequent'` if it exists. If the + `'infrequent'` category does not exist, then :meth:`transform` and + :meth:`inverse_transform` will handle an unknown category as with + `handle_unknown='ignore'`. Infrequent categories exist based on + `min_frequency` and `max_categories`. Read more in the + :ref:`User Guide `. + + .. versionchanged:: 1.1 + `'infrequent_if_exist'` was added to automatically handle unknown + categories and infrequent categories. + + min_frequency : int or float, default=None + Specifies the minimum frequency below which a category will be + considered infrequent. + + - If `int`, categories with a smaller cardinality will be considered + infrequent. + + - If `float`, categories with a smaller cardinality than + `min_frequency * n_samples` will be considered infrequent. + + .. versionadded:: 1.1 + Read more in the :ref:`User Guide `. + + max_categories : int, default=None + Specifies an upper limit to the number of output features for each input + feature when considering infrequent categories. If there are infrequent + categories, `max_categories` includes the category representing the + infrequent categories along with the frequent categories. If `None`, + there is no limit to the number of output features. + + .. versionadded:: 1.1 + Read more in the :ref:`User Guide `. + + feature_name_combiner : "concat" or callable, default="concat" + Callable with signature `def callable(input_feature, category)` that returns a + string. This is used to create feature names to be returned by + :meth:`get_feature_names_out`. + + `"concat"` concatenates encoded feature name and category with + `feature + "_" + str(category)`.E.g. feature X with values 1, 6, 7 create + feature names `X_1, X_6, X_7`. + + .. versionadded:: 1.3 + + Attributes + ---------- + categories_ : list of arrays + The categories of each feature determined during fitting + (in order of the features in X and corresponding with the output + of ``transform``). This includes the category specified in ``drop`` + (if any). + + drop_idx_ : array of shape (n_features,) + - ``drop_idx_[i]`` is the index in ``categories_[i]`` of the category + to be dropped for each feature. + - ``drop_idx_[i] = None`` if no category is to be dropped from the + feature with index ``i``, e.g. when `drop='if_binary'` and the + feature isn't binary. + - ``drop_idx_ = None`` if all the transformed features will be + retained. + + If infrequent categories are enabled by setting `min_frequency` or + `max_categories` to a non-default value and `drop_idx[i]` corresponds + to a infrequent category, then the entire infrequent category is + dropped. + + .. versionchanged:: 0.23 + Added the possibility to contain `None` values. + + infrequent_categories_ : list of ndarray + Defined only if infrequent categories are enabled by setting + `min_frequency` or `max_categories` to a non-default value. + `infrequent_categories_[i]` are the infrequent categories for feature + `i`. If the feature `i` has no infrequent categories + `infrequent_categories_[i]` is None. + + .. versionadded:: 1.1 + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 1.0 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + feature_name_combiner : callable or None + Callable with signature `def callable(input_feature, category)` that returns a + string. This is used to create feature names to be returned by + :meth:`get_feature_names_out`. + + .. versionadded:: 1.3 + + See Also + -------- + OrdinalEncoder : Performs an ordinal (integer) + encoding of the categorical features. + TargetEncoder : Encodes categorical features using the target. + sklearn.feature_extraction.DictVectorizer : Performs a one-hot encoding of + dictionary items (also handles string-valued features). + sklearn.feature_extraction.FeatureHasher : Performs an approximate one-hot + encoding of dictionary items or strings. + LabelBinarizer : Binarizes labels in a one-vs-all + fashion. + MultiLabelBinarizer : Transforms between iterable of + iterables and a multilabel format, e.g. a (samples x classes) binary + matrix indicating the presence of a class label. + + Examples + -------- + Given a dataset with two features, we let the encoder find the unique + values per feature and transform the data to a binary one-hot encoding. + + >>> from sklearn.preprocessing import OneHotEncoder + + One can discard categories not seen during `fit`: + + >>> enc = OneHotEncoder(handle_unknown='ignore') + >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] + >>> enc.fit(X) + OneHotEncoder(handle_unknown='ignore') + >>> enc.categories_ + [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] + >>> enc.transform([['Female', 1], ['Male', 4]]).toarray() + array([[1., 0., 1., 0., 0.], + [0., 1., 0., 0., 0.]]) + >>> enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]]) + array([['Male', 1], + [None, 2]], dtype=object) + >>> enc.get_feature_names_out(['gender', 'group']) + array(['gender_Female', 'gender_Male', 'group_1', 'group_2', 'group_3'], ...) + + One can always drop the first column for each feature: + + >>> drop_enc = OneHotEncoder(drop='first').fit(X) + >>> drop_enc.categories_ + [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] + >>> drop_enc.transform([['Female', 1], ['Male', 2]]).toarray() + array([[0., 0., 0.], + [1., 1., 0.]]) + + Or drop a column for feature only having 2 categories: + + >>> drop_binary_enc = OneHotEncoder(drop='if_binary').fit(X) + >>> drop_binary_enc.transform([['Female', 1], ['Male', 2]]).toarray() + array([[0., 1., 0., 0.], + [1., 0., 1., 0.]]) + + One can change the way feature names are created. + + >>> def custom_combiner(feature, category): + ... return str(feature) + "_" + type(category).__name__ + "_" + str(category) + >>> custom_fnames_enc = OneHotEncoder(feature_name_combiner=custom_combiner).fit(X) + >>> custom_fnames_enc.get_feature_names_out() + array(['x0_str_Female', 'x0_str_Male', 'x1_int_1', 'x1_int_2', 'x1_int_3'], + dtype=object) + + Infrequent categories are enabled by setting `max_categories` or `min_frequency`. + + >>> import numpy as np + >>> X = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object).T + >>> ohe = OneHotEncoder(max_categories=3, sparse_output=False).fit(X) + >>> ohe.infrequent_categories_ + [array(['a', 'd'], dtype=object)] + >>> ohe.transform([["a"], ["b"]]) + array([[0., 0., 1.], + [1., 0., 0.]]) + """ + + _parameter_constraints: dict = { + "categories": [StrOptions({"auto"}), list], + "drop": [StrOptions({"first", "if_binary"}), "array-like", None], + "dtype": "no_validation", # validation delegated to numpy + "handle_unknown": [StrOptions({"error", "ignore", "infrequent_if_exist"})], + "max_categories": [Interval(Integral, 1, None, closed="left"), None], + "min_frequency": [ + Interval(Integral, 1, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="neither"), + None, + ], + "sparse_output": ["boolean"], + "feature_name_combiner": [StrOptions({"concat"}), callable], + } + + def __init__( + self, + *, + categories="auto", + drop=None, + sparse_output=True, + dtype=np.float64, + handle_unknown="error", + min_frequency=None, + max_categories=None, + feature_name_combiner="concat", + ): + self.categories = categories + self.sparse_output = sparse_output + self.dtype = dtype + self.handle_unknown = handle_unknown + self.drop = drop + self.min_frequency = min_frequency + self.max_categories = max_categories + self.feature_name_combiner = feature_name_combiner + + def _map_drop_idx_to_infrequent(self, feature_idx, drop_idx): + """Convert `drop_idx` into the index for infrequent categories. + + If there are no infrequent categories, then `drop_idx` is + returned. This method is called in `_set_drop_idx` when the `drop` + parameter is an array-like. + """ + if not self._infrequent_enabled: + return drop_idx + + default_to_infrequent = self._default_to_infrequent_mappings[feature_idx] + if default_to_infrequent is None: + return drop_idx + + # Raise error when explicitly dropping a category that is infrequent + infrequent_indices = self._infrequent_indices[feature_idx] + if infrequent_indices is not None and drop_idx in infrequent_indices: + categories = self.categories_[feature_idx] + raise ValueError( + f"Unable to drop category {categories[drop_idx].item()!r} from" + f" feature {feature_idx} because it is infrequent" + ) + return default_to_infrequent[drop_idx] + + def _set_drop_idx(self): + """Compute the drop indices associated with `self.categories_`. + + If `self.drop` is: + - `None`, No categories have been dropped. + - `'first'`, All zeros to drop the first category. + - `'if_binary'`, All zeros if the category is binary and `None` + otherwise. + - array-like, The indices of the categories that match the + categories in `self.drop`. If the dropped category is an infrequent + category, then the index for the infrequent category is used. This + means that the entire infrequent category is dropped. + + This methods defines a public `drop_idx_` and a private + `_drop_idx_after_grouping`. + + - `drop_idx_`: Public facing API that references the drop category in + `self.categories_`. + - `_drop_idx_after_grouping`: Used internally to drop categories *after* the + infrequent categories are grouped together. + + If there are no infrequent categories or drop is `None`, then + `drop_idx_=_drop_idx_after_grouping`. + """ + if self.drop is None: + drop_idx_after_grouping = None + elif isinstance(self.drop, str): + if self.drop == "first": + drop_idx_after_grouping = np.zeros(len(self.categories_), dtype=object) + elif self.drop == "if_binary": + n_features_out_no_drop = [len(cat) for cat in self.categories_] + if self._infrequent_enabled: + for i, infreq_idx in enumerate(self._infrequent_indices): + if infreq_idx is None: + continue + n_features_out_no_drop[i] -= infreq_idx.size - 1 + + drop_idx_after_grouping = np.array( + [ + 0 if n_features_out == 2 else None + for n_features_out in n_features_out_no_drop + ], + dtype=object, + ) + + else: + drop_array = np.asarray(self.drop, dtype=object) + droplen = len(drop_array) + + if droplen != len(self.categories_): + msg = ( + "`drop` should have length equal to the number " + "of features ({}), got {}" + ) + raise ValueError(msg.format(len(self.categories_), droplen)) + missing_drops = [] + drop_indices = [] + for feature_idx, (drop_val, cat_list) in enumerate( + zip(drop_array, self.categories_) + ): + if not is_scalar_nan(drop_val): + drop_idx = np.where(cat_list == drop_val)[0] + if drop_idx.size: # found drop idx + drop_indices.append( + self._map_drop_idx_to_infrequent(feature_idx, drop_idx[0]) + ) + else: + missing_drops.append((feature_idx, drop_val)) + continue + + # drop_val is nan, find nan in categories manually + if is_scalar_nan(cat_list[-1]): + drop_indices.append( + self._map_drop_idx_to_infrequent(feature_idx, cat_list.size - 1) + ) + else: # nan is missing + missing_drops.append((feature_idx, drop_val)) + + if any(missing_drops): + msg = ( + "The following categories were supposed to be " + "dropped, but were not found in the training " + "data.\n{}".format( + "\n".join( + [ + "Category: {}, Feature: {}".format(c, v) + for c, v in missing_drops + ] + ) + ) + ) + raise ValueError(msg) + drop_idx_after_grouping = np.array(drop_indices, dtype=object) + + # `_drop_idx_after_grouping` are the categories to drop *after* the infrequent + # categories are grouped together. If needed, we remap `drop_idx` back + # to the categories seen in `self.categories_`. + self._drop_idx_after_grouping = drop_idx_after_grouping + + if not self._infrequent_enabled or drop_idx_after_grouping is None: + self.drop_idx_ = self._drop_idx_after_grouping + else: + drop_idx_ = [] + for feature_idx, drop_idx in enumerate(drop_idx_after_grouping): + default_to_infrequent = self._default_to_infrequent_mappings[ + feature_idx + ] + if drop_idx is None or default_to_infrequent is None: + orig_drop_idx = drop_idx + else: + orig_drop_idx = np.flatnonzero(default_to_infrequent == drop_idx)[0] + + drop_idx_.append(orig_drop_idx) + + self.drop_idx_ = np.asarray(drop_idx_, dtype=object) + + def _compute_transformed_categories(self, i, remove_dropped=True): + """Compute the transformed categories used for column `i`. + + 1. If there are infrequent categories, the category is named + 'infrequent_sklearn'. + 2. Dropped columns are removed when remove_dropped=True. + """ + cats = self.categories_[i] + + if self._infrequent_enabled: + infreq_map = self._default_to_infrequent_mappings[i] + if infreq_map is not None: + frequent_mask = infreq_map < infreq_map.max() + infrequent_cat = "infrequent_sklearn" + # infrequent category is always at the end + cats = np.concatenate( + (cats[frequent_mask], np.array([infrequent_cat], dtype=object)) + ) + + if remove_dropped: + cats = self._remove_dropped_categories(cats, i) + return cats + + def _remove_dropped_categories(self, categories, i): + """Remove dropped categories.""" + if ( + self._drop_idx_after_grouping is not None + and self._drop_idx_after_grouping[i] is not None + ): + return np.delete(categories, self._drop_idx_after_grouping[i]) + return categories + + def _compute_n_features_outs(self): + """Compute the n_features_out for each input feature.""" + output = [len(cats) for cats in self.categories_] + + if self._drop_idx_after_grouping is not None: + for i, drop_idx in enumerate(self._drop_idx_after_grouping): + if drop_idx is not None: + output[i] -= 1 + + if not self._infrequent_enabled: + return output + + # infrequent is enabled, the number of features out are reduced + # because the infrequent categories are grouped together + for i, infreq_idx in enumerate(self._infrequent_indices): + if infreq_idx is None: + continue + output[i] -= infreq_idx.size - 1 + + return output + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """ + Fit OneHotEncoder to X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data to determine the categories of each feature. + + y : None + Ignored. This parameter exists only for compatibility with + :class:`~sklearn.pipeline.Pipeline`. + + Returns + ------- + self + Fitted encoder. + """ + self._fit( + X, + handle_unknown=self.handle_unknown, + force_all_finite="allow-nan", + ) + self._set_drop_idx() + self._n_features_outs = self._compute_n_features_outs() + return self + + def transform(self, X): + """ + Transform X using one-hot encoding. + + If `sparse_output=True` (default), it returns an instance of + :class:`scipy.sparse._csr.csr_matrix` (CSR format). + + If there are infrequent categories for a feature, set by specifying + `max_categories` or `min_frequency`, the infrequent categories are + grouped into a single category. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data to encode. + + Returns + ------- + X_out : {ndarray, sparse matrix} of shape \ + (n_samples, n_encoded_features) + Transformed input. If `sparse_output=True`, a sparse matrix will be + returned. + """ + check_is_fitted(self) + transform_output = _get_output_config("transform", estimator=self)["dense"] + if transform_output != "default" and self.sparse_output: + capitalize_transform_output = transform_output.capitalize() + raise ValueError( + f"{capitalize_transform_output} output does not support sparse data." + f" Set sparse_output=False to output {transform_output} dataframes or" + f" disable {capitalize_transform_output} output via" + '` ohe.set_output(transform="default").' + ) + + # validation of X happens in _check_X called by _transform + warn_on_unknown = self.drop is not None and self.handle_unknown in { + "ignore", + "infrequent_if_exist", + } + X_int, X_mask = self._transform( + X, + handle_unknown=self.handle_unknown, + force_all_finite="allow-nan", + warn_on_unknown=warn_on_unknown, + ) + + n_samples, n_features = X_int.shape + + if self._drop_idx_after_grouping is not None: + to_drop = self._drop_idx_after_grouping.copy() + # We remove all the dropped categories from mask, and decrement all + # categories that occur after them to avoid an empty column. + keep_cells = X_int != to_drop + for i, cats in enumerate(self.categories_): + # drop='if_binary' but feature isn't binary + if to_drop[i] is None: + # set to cardinality to not drop from X_int + to_drop[i] = len(cats) + + to_drop = to_drop.reshape(1, -1) + X_int[X_int > to_drop] -= 1 + X_mask &= keep_cells + + mask = X_mask.ravel() + feature_indices = np.cumsum([0] + self._n_features_outs) + indices = (X_int + feature_indices[:-1]).ravel()[mask] + + indptr = np.empty(n_samples + 1, dtype=int) + indptr[0] = 0 + np.sum(X_mask, axis=1, out=indptr[1:], dtype=indptr.dtype) + np.cumsum(indptr[1:], out=indptr[1:]) + data = np.ones(indptr[-1]) + + out = sparse.csr_matrix( + (data, indices, indptr), + shape=(n_samples, feature_indices[-1]), + dtype=self.dtype, + ) + if not self.sparse_output: + return out.toarray() + else: + return out + + def inverse_transform(self, X): + """ + Convert the data back to the original representation. + + When unknown categories are encountered (all zeros in the + one-hot encoding), ``None`` is used to represent this category. If the + feature with the unknown category has a dropped category, the dropped + category will be its inverse. + + For a given input feature, if there is an infrequent category, + 'infrequent_sklearn' will be used to represent the infrequent category. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape \ + (n_samples, n_encoded_features) + The transformed data. + + Returns + ------- + X_tr : ndarray of shape (n_samples, n_features) + Inverse transformed array. + """ + check_is_fitted(self) + X = check_array(X, accept_sparse="csr") + + n_samples, _ = X.shape + n_features = len(self.categories_) + + n_features_out = np.sum(self._n_features_outs) + + # validate shape of passed X + msg = ( + "Shape of the passed X data is not correct. Expected {0} columns, got {1}." + ) + if X.shape[1] != n_features_out: + raise ValueError(msg.format(n_features_out, X.shape[1])) + + transformed_features = [ + self._compute_transformed_categories(i, remove_dropped=False) + for i, _ in enumerate(self.categories_) + ] + + # create resulting array of appropriate dtype + dt = np.result_type(*[cat.dtype for cat in transformed_features]) + X_tr = np.empty((n_samples, n_features), dtype=dt) + + j = 0 + found_unknown = {} + + if self._infrequent_enabled: + infrequent_indices = self._infrequent_indices + else: + infrequent_indices = [None] * n_features + + for i in range(n_features): + cats_wo_dropped = self._remove_dropped_categories( + transformed_features[i], i + ) + n_categories = cats_wo_dropped.shape[0] + + # Only happens if there was a column with a unique + # category. In this case we just fill the column with this + # unique category value. + if n_categories == 0: + X_tr[:, i] = self.categories_[i][self._drop_idx_after_grouping[i]] + j += n_categories + continue + sub = X[:, j : j + n_categories] + # for sparse X argmax returns 2D matrix, ensure 1D array + labels = np.asarray(sub.argmax(axis=1)).flatten() + X_tr[:, i] = cats_wo_dropped[labels] + + if self.handle_unknown == "ignore" or ( + self.handle_unknown == "infrequent_if_exist" + and infrequent_indices[i] is None + ): + unknown = np.asarray(sub.sum(axis=1) == 0).flatten() + # ignored unknown categories: we have a row of all zero + if unknown.any(): + # if categories were dropped then unknown categories will + # be mapped to the dropped category + if ( + self._drop_idx_after_grouping is None + or self._drop_idx_after_grouping[i] is None + ): + found_unknown[i] = unknown + else: + X_tr[unknown, i] = self.categories_[i][ + self._drop_idx_after_grouping[i] + ] + else: + dropped = np.asarray(sub.sum(axis=1) == 0).flatten() + if dropped.any(): + if self._drop_idx_after_grouping is None: + all_zero_samples = np.flatnonzero(dropped) + raise ValueError( + f"Samples {all_zero_samples} can not be inverted " + "when drop=None and handle_unknown='error' " + "because they contain all zeros" + ) + # we can safely assume that all of the nulls in each column + # are the dropped value + drop_idx = self._drop_idx_after_grouping[i] + X_tr[dropped, i] = transformed_features[i][drop_idx] + + j += n_categories + + # if ignored are found: potentially need to upcast result to + # insert None values + if found_unknown: + if X_tr.dtype != object: + X_tr = X_tr.astype(object) + + for idx, mask in found_unknown.items(): + X_tr[mask, idx] = None + + return X_tr + + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input features. + + - If `input_features` is `None`, then `feature_names_in_` is + used as feature names in. If `feature_names_in_` is not defined, + then the following input feature names are generated: + `["x0", "x1", ..., "x(n_features_in_ - 1)"]`. + - If `input_features` is an array-like, then `input_features` must + match `feature_names_in_` if `feature_names_in_` is defined. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + check_is_fitted(self) + input_features = _check_feature_names_in(self, input_features) + cats = [ + self._compute_transformed_categories(i) + for i, _ in enumerate(self.categories_) + ] + + name_combiner = self._check_get_feature_name_combiner() + feature_names = [] + for i in range(len(cats)): + names = [name_combiner(input_features[i], t) for t in cats[i]] + feature_names.extend(names) + + return np.array(feature_names, dtype=object) + + def _check_get_feature_name_combiner(self): + if self.feature_name_combiner == "concat": + return lambda feature, category: feature + "_" + str(category) + else: # callable + dry_run_combiner = self.feature_name_combiner("feature", "category") + if not isinstance(dry_run_combiner, str): + raise TypeError( + "When `feature_name_combiner` is a callable, it should return a " + f"Python string. Got {type(dry_run_combiner)} instead." + ) + return self.feature_name_combiner + + +class OrdinalEncoder(OneToOneFeatureMixin, _BaseEncoder): + """ + Encode categorical features as an integer array. + + The input to this transformer should be an array-like of integers or + strings, denoting the values taken on by categorical (discrete) features. + The features are converted to ordinal integers. This results in + a single column of integers (0 to n_categories - 1) per feature. + + Read more in the :ref:`User Guide `. + For a comparison of different encoders, refer to: + :ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder.py`. + + .. versionadded:: 0.20 + + Parameters + ---------- + categories : 'auto' or a list of array-like, default='auto' + Categories (unique values) per feature: + + - 'auto' : Determine categories automatically from the training data. + - list : ``categories[i]`` holds the categories expected in the ith + column. The passed categories should not mix strings and numeric + values, and should be sorted in case of numeric values. + + The used categories can be found in the ``categories_`` attribute. + + dtype : number type, default=np.float64 + Desired dtype of output. + + handle_unknown : {'error', 'use_encoded_value'}, default='error' + When set to 'error' an error will be raised in case an unknown + categorical feature is present during transform. When set to + 'use_encoded_value', the encoded value of unknown categories will be + set to the value given for the parameter `unknown_value`. In + :meth:`inverse_transform`, an unknown category will be denoted as None. + + .. versionadded:: 0.24 + + unknown_value : int or np.nan, default=None + When the parameter handle_unknown is set to 'use_encoded_value', this + parameter is required and will set the encoded value of unknown + categories. It has to be distinct from the values used to encode any of + the categories in `fit`. If set to np.nan, the `dtype` parameter must + be a float dtype. + + .. versionadded:: 0.24 + + encoded_missing_value : int or np.nan, default=np.nan + Encoded value of missing categories. If set to `np.nan`, then the `dtype` + parameter must be a float dtype. + + .. versionadded:: 1.1 + + min_frequency : int or float, default=None + Specifies the minimum frequency below which a category will be + considered infrequent. + + - If `int`, categories with a smaller cardinality will be considered + infrequent. + + - If `float`, categories with a smaller cardinality than + `min_frequency * n_samples` will be considered infrequent. + + .. versionadded:: 1.3 + Read more in the :ref:`User Guide `. + + max_categories : int, default=None + Specifies an upper limit to the number of output categories for each input + feature when considering infrequent categories. If there are infrequent + categories, `max_categories` includes the category representing the + infrequent categories along with the frequent categories. If `None`, + there is no limit to the number of output features. + + `max_categories` do **not** take into account missing or unknown + categories. Setting `unknown_value` or `encoded_missing_value` to an + integer will increase the number of unique integer codes by one each. + This can result in up to `max_categories + 2` integer codes. + + .. versionadded:: 1.3 + Read more in the :ref:`User Guide `. + + Attributes + ---------- + categories_ : list of arrays + The categories of each feature determined during ``fit`` (in order of + the features in X and corresponding with the output of ``transform``). + This does not include categories that weren't seen during ``fit``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 1.0 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + infrequent_categories_ : list of ndarray + Defined only if infrequent categories are enabled by setting + `min_frequency` or `max_categories` to a non-default value. + `infrequent_categories_[i]` are the infrequent categories for feature + `i`. If the feature `i` has no infrequent categories + `infrequent_categories_[i]` is None. + + .. versionadded:: 1.3 + + See Also + -------- + OneHotEncoder : Performs a one-hot encoding of categorical features. This encoding + is suitable for low to medium cardinality categorical variables, both in + supervised and unsupervised settings. + TargetEncoder : Encodes categorical features using supervised signal + in a classification or regression pipeline. This encoding is typically + suitable for high cardinality categorical variables. + LabelEncoder : Encodes target labels with values between 0 and + ``n_classes-1``. + + Notes + ----- + With a high proportion of `nan` values, inferring categories becomes slow with + Python versions before 3.10. The handling of `nan` values was improved + from Python 3.10 onwards, (c.f. + `bpo-43475 `_). + + Examples + -------- + Given a dataset with two features, we let the encoder find the unique + values per feature and transform the data to an ordinal encoding. + + >>> from sklearn.preprocessing import OrdinalEncoder + >>> enc = OrdinalEncoder() + >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] + >>> enc.fit(X) + OrdinalEncoder() + >>> enc.categories_ + [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] + >>> enc.transform([['Female', 3], ['Male', 1]]) + array([[0., 2.], + [1., 0.]]) + + >>> enc.inverse_transform([[1, 0], [0, 1]]) + array([['Male', 1], + ['Female', 2]], dtype=object) + + By default, :class:`OrdinalEncoder` is lenient towards missing values by + propagating them. + + >>> import numpy as np + >>> X = [['Male', 1], ['Female', 3], ['Female', np.nan]] + >>> enc.fit_transform(X) + array([[ 1., 0.], + [ 0., 1.], + [ 0., nan]]) + + You can use the parameter `encoded_missing_value` to encode missing values. + + >>> enc.set_params(encoded_missing_value=-1).fit_transform(X) + array([[ 1., 0.], + [ 0., 1.], + [ 0., -1.]]) + + Infrequent categories are enabled by setting `max_categories` or `min_frequency`. + In the following example, "a" and "d" are considered infrequent and grouped + together into a single category, "b" and "c" are their own categories, unknown + values are encoded as 3 and missing values are encoded as 4. + + >>> X_train = np.array( + ... [["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3 + [np.nan]], + ... dtype=object).T + >>> enc = OrdinalEncoder( + ... handle_unknown="use_encoded_value", unknown_value=3, + ... max_categories=3, encoded_missing_value=4) + >>> _ = enc.fit(X_train) + >>> X_test = np.array([["a"], ["b"], ["c"], ["d"], ["e"], [np.nan]], dtype=object) + >>> enc.transform(X_test) + array([[2.], + [0.], + [1.], + [2.], + [3.], + [4.]]) + """ + + _parameter_constraints: dict = { + "categories": [StrOptions({"auto"}), list], + "dtype": "no_validation", # validation delegated to numpy + "encoded_missing_value": [Integral, type(np.nan)], + "handle_unknown": [StrOptions({"error", "use_encoded_value"})], + "unknown_value": [Integral, type(np.nan), None], + "max_categories": [Interval(Integral, 1, None, closed="left"), None], + "min_frequency": [ + Interval(Integral, 1, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="neither"), + None, + ], + } + + def __init__( + self, + *, + categories="auto", + dtype=np.float64, + handle_unknown="error", + unknown_value=None, + encoded_missing_value=np.nan, + min_frequency=None, + max_categories=None, + ): + self.categories = categories + self.dtype = dtype + self.handle_unknown = handle_unknown + self.unknown_value = unknown_value + self.encoded_missing_value = encoded_missing_value + self.min_frequency = min_frequency + self.max_categories = max_categories + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """ + Fit the OrdinalEncoder to X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data to determine the categories of each feature. + + y : None + Ignored. This parameter exists only for compatibility with + :class:`~sklearn.pipeline.Pipeline`. + + Returns + ------- + self : object + Fitted encoder. + """ + if self.handle_unknown == "use_encoded_value": + if is_scalar_nan(self.unknown_value): + if np.dtype(self.dtype).kind != "f": + raise ValueError( + "When unknown_value is np.nan, the dtype " + "parameter should be " + f"a float dtype. Got {self.dtype}." + ) + elif not isinstance(self.unknown_value, numbers.Integral): + raise TypeError( + "unknown_value should be an integer or " + "np.nan when " + "handle_unknown is 'use_encoded_value', " + f"got {self.unknown_value}." + ) + elif self.unknown_value is not None: + raise TypeError( + "unknown_value should only be set when " + "handle_unknown is 'use_encoded_value', " + f"got {self.unknown_value}." + ) + + # `_fit` will only raise an error when `self.handle_unknown="error"` + fit_results = self._fit( + X, + handle_unknown=self.handle_unknown, + force_all_finite="allow-nan", + return_and_ignore_missing_for_infrequent=True, + ) + self._missing_indices = fit_results["missing_indices"] + + cardinalities = [len(categories) for categories in self.categories_] + if self._infrequent_enabled: + # Cardinality decreases because the infrequent categories are grouped + # together + for feature_idx, infrequent in enumerate(self.infrequent_categories_): + if infrequent is not None: + cardinalities[feature_idx] -= len(infrequent) + + # missing values are not considered part of the cardinality + # when considering unknown categories or encoded_missing_value + for cat_idx, categories_for_idx in enumerate(self.categories_): + if is_scalar_nan(categories_for_idx[-1]): + cardinalities[cat_idx] -= 1 + + if self.handle_unknown == "use_encoded_value": + for cardinality in cardinalities: + if 0 <= self.unknown_value < cardinality: + raise ValueError( + "The used value for unknown_value " + f"{self.unknown_value} is one of the " + "values already used for encoding the " + "seen categories." + ) + + if self._missing_indices: + if np.dtype(self.dtype).kind != "f" and is_scalar_nan( + self.encoded_missing_value + ): + raise ValueError( + "There are missing values in features " + f"{list(self._missing_indices)}. For OrdinalEncoder to " + f"encode missing values with dtype: {self.dtype}, set " + "encoded_missing_value to a non-nan value, or " + "set dtype to a float" + ) + + if not is_scalar_nan(self.encoded_missing_value): + # Features are invalid when they contain a missing category + # and encoded_missing_value was already used to encode a + # known category + invalid_features = [ + cat_idx + for cat_idx, cardinality in enumerate(cardinalities) + if cat_idx in self._missing_indices + and 0 <= self.encoded_missing_value < cardinality + ] + + if invalid_features: + # Use feature names if they are available + if hasattr(self, "feature_names_in_"): + invalid_features = self.feature_names_in_[invalid_features] + raise ValueError( + f"encoded_missing_value ({self.encoded_missing_value}) " + "is already used to encode a known category in features: " + f"{invalid_features}" + ) + + return self + + def transform(self, X): + """ + Transform X to ordinal codes. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data to encode. + + Returns + ------- + X_out : ndarray of shape (n_samples, n_features) + Transformed input. + """ + check_is_fitted(self, "categories_") + X_int, X_mask = self._transform( + X, + handle_unknown=self.handle_unknown, + force_all_finite="allow-nan", + ignore_category_indices=self._missing_indices, + ) + X_trans = X_int.astype(self.dtype, copy=False) + + for cat_idx, missing_idx in self._missing_indices.items(): + X_missing_mask = X_int[:, cat_idx] == missing_idx + X_trans[X_missing_mask, cat_idx] = self.encoded_missing_value + + # create separate category for unknown values + if self.handle_unknown == "use_encoded_value": + X_trans[~X_mask] = self.unknown_value + return X_trans + + def inverse_transform(self, X): + """ + Convert the data back to the original representation. + + Parameters + ---------- + X : array-like of shape (n_samples, n_encoded_features) + The transformed data. + + Returns + ------- + X_tr : ndarray of shape (n_samples, n_features) + Inverse transformed array. + """ + check_is_fitted(self) + X = check_array(X, force_all_finite="allow-nan") + + n_samples, _ = X.shape + n_features = len(self.categories_) + + # validate shape of passed X + msg = ( + "Shape of the passed X data is not correct. Expected {0} columns, got {1}." + ) + if X.shape[1] != n_features: + raise ValueError(msg.format(n_features, X.shape[1])) + + # create resulting array of appropriate dtype + dt = np.result_type(*[cat.dtype for cat in self.categories_]) + X_tr = np.empty((n_samples, n_features), dtype=dt) + + found_unknown = {} + infrequent_masks = {} + + infrequent_indices = getattr(self, "_infrequent_indices", None) + + for i in range(n_features): + labels = X[:, i] + + # replace values of X[:, i] that were nan with actual indices + if i in self._missing_indices: + X_i_mask = _get_mask(labels, self.encoded_missing_value) + labels[X_i_mask] = self._missing_indices[i] + + rows_to_update = slice(None) + categories = self.categories_[i] + + if infrequent_indices is not None and infrequent_indices[i] is not None: + # Compute mask for frequent categories + infrequent_encoding_value = len(categories) - len(infrequent_indices[i]) + infrequent_masks[i] = labels == infrequent_encoding_value + rows_to_update = ~infrequent_masks[i] + + # Remap categories to be only frequent categories. The infrequent + # categories will be mapped to "infrequent_sklearn" later + frequent_categories_mask = np.ones_like(categories, dtype=bool) + frequent_categories_mask[infrequent_indices[i]] = False + categories = categories[frequent_categories_mask] + + if self.handle_unknown == "use_encoded_value": + unknown_labels = _get_mask(labels, self.unknown_value) + found_unknown[i] = unknown_labels + + known_labels = ~unknown_labels + if isinstance(rows_to_update, np.ndarray): + rows_to_update &= known_labels + else: + rows_to_update = known_labels + + labels_int = labels[rows_to_update].astype("int64", copy=False) + X_tr[rows_to_update, i] = categories[labels_int] + + if found_unknown or infrequent_masks: + X_tr = X_tr.astype(object, copy=False) + + # insert None values for unknown values + if found_unknown: + for idx, mask in found_unknown.items(): + X_tr[mask, idx] = None + + if infrequent_masks: + for idx, mask in infrequent_masks.items(): + X_tr[mask, idx] = "infrequent_sklearn" + + return X_tr diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_function_transformer.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_function_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..921bd6a01fb713e9452fd7a934f48b22295ed1b1 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_function_transformer.py @@ -0,0 +1,431 @@ +import warnings + +import numpy as np + +from ..base import BaseEstimator, TransformerMixin, _fit_context +from ..utils._param_validation import StrOptions +from ..utils._set_output import ADAPTERS_MANAGER, _get_output_config +from ..utils.metaestimators import available_if +from ..utils.validation import ( + _allclose_dense_sparse, + _check_feature_names_in, + _get_feature_names, + _is_pandas_df, + _is_polars_df, + check_array, +) + + +def _get_adapter_from_container(container): + """Get the adapter that nows 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 + + +def _identity(X): + """The identity function.""" + return X + + +class FunctionTransformer(TransformerMixin, BaseEstimator): + """Constructs a transformer from an arbitrary callable. + + A FunctionTransformer forwards its X (and optionally y) arguments to a + user-defined function or function object and returns the result of this + function. This is useful for stateless transformations such as taking the + log of frequencies, doing custom scaling, etc. + + Note: If a lambda is used as the function, then the resulting + transformer will not be pickleable. + + .. versionadded:: 0.17 + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + func : callable, default=None + The callable to use for the transformation. This will be passed + the same arguments as transform, with args and kwargs forwarded. + If func is None, then func will be the identity function. + + inverse_func : callable, default=None + The callable to use for the inverse transformation. This will be + passed the same arguments as inverse transform, with args and + kwargs forwarded. If inverse_func is None, then inverse_func + will be the identity function. + + validate : bool, default=False + Indicate that the input X array should be checked before calling + ``func``. The possibilities are: + + - If False, there is no input validation. + - If True, then X will be converted to a 2-dimensional NumPy array or + sparse matrix. If the conversion is not possible an exception is + raised. + + .. versionchanged:: 0.22 + The default of ``validate`` changed from True to False. + + accept_sparse : bool, default=False + Indicate that func accepts a sparse matrix as input. If validate is + False, this has no effect. Otherwise, if accept_sparse is false, + sparse matrix inputs will cause an exception to be raised. + + check_inverse : bool, default=True + Whether to check that or ``func`` followed by ``inverse_func`` leads to + the original inputs. It can be used for a sanity check, raising a + warning when the condition is not fulfilled. + + .. versionadded:: 0.20 + + feature_names_out : callable, 'one-to-one' or None, default=None + Determines the list of feature names that will be returned by the + `get_feature_names_out` method. If it is 'one-to-one', then the output + feature names will be equal to the input feature names. If it is a + callable, then it must take two positional arguments: this + `FunctionTransformer` (`self`) and an array-like of input feature names + (`input_features`). It must return an array-like of output feature + names. The `get_feature_names_out` method is only defined if + `feature_names_out` is not None. + + See ``get_feature_names_out`` for more details. + + .. versionadded:: 1.1 + + kw_args : dict, default=None + Dictionary of additional keyword arguments to pass to func. + + .. versionadded:: 0.18 + + inv_kw_args : dict, default=None + Dictionary of additional keyword arguments to pass to inverse_func. + + .. versionadded:: 0.18 + + Attributes + ---------- + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` has feature + names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + MaxAbsScaler : Scale each feature by its maximum absolute value. + StandardScaler : Standardize features by removing the mean and + scaling to unit variance. + LabelBinarizer : Binarize labels in a one-vs-all fashion. + MultiLabelBinarizer : Transform between iterable of iterables + and a multilabel format. + + Notes + ----- + If `func` returns an output with a `columns` attribute, then the columns is enforced + to be consistent with the output of `get_feature_names_out`. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.preprocessing import FunctionTransformer + >>> transformer = FunctionTransformer(np.log1p) + >>> X = np.array([[0, 1], [2, 3]]) + >>> transformer.transform(X) + array([[0. , 0.6931...], + [1.0986..., 1.3862...]]) + """ + + _parameter_constraints: dict = { + "func": [callable, None], + "inverse_func": [callable, None], + "validate": ["boolean"], + "accept_sparse": ["boolean"], + "check_inverse": ["boolean"], + "feature_names_out": [callable, StrOptions({"one-to-one"}), None], + "kw_args": [dict, None], + "inv_kw_args": [dict, None], + } + + def __init__( + self, + func=None, + inverse_func=None, + *, + validate=False, + accept_sparse=False, + check_inverse=True, + feature_names_out=None, + kw_args=None, + inv_kw_args=None, + ): + self.func = func + self.inverse_func = inverse_func + self.validate = validate + self.accept_sparse = accept_sparse + self.check_inverse = check_inverse + self.feature_names_out = feature_names_out + self.kw_args = kw_args + self.inv_kw_args = inv_kw_args + + def _check_input(self, X, *, reset): + if self.validate: + return self._validate_data(X, accept_sparse=self.accept_sparse, reset=reset) + elif reset: + # Set feature_names_in_ and n_features_in_ even if validate=False + # We run this only when reset==True to store the attributes but not + # validate them, because validate=False + self._check_n_features(X, reset=reset) + self._check_feature_names(X, reset=reset) + return X + + def _check_inverse_transform(self, X): + """Check that func and inverse_func are the inverse.""" + idx_selected = slice(None, None, max(1, X.shape[0] // 100)) + X_round_trip = self.inverse_transform(self.transform(X[idx_selected])) + + if hasattr(X, "dtype"): + dtypes = [X.dtype] + elif hasattr(X, "dtypes"): + # Dataframes can have multiple dtypes + dtypes = X.dtypes + + if not all(np.issubdtype(d, np.number) for d in dtypes): + raise ValueError( + "'check_inverse' is only supported when all the elements in `X` is" + " numerical." + ) + + if not _allclose_dense_sparse(X[idx_selected], X_round_trip): + warnings.warn( + ( + "The provided functions are not strictly" + " inverse of each other. If you are sure you" + " want to proceed regardless, set" + " 'check_inverse=False'." + ), + UserWarning, + ) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit transformer by checking X. + + If ``validate`` is ``True``, ``X`` will be checked. + + Parameters + ---------- + X : {array-like, sparse-matrix} of shape (n_samples, n_features) \ + if `validate=True` else any object that `func` can handle + Input array. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + FunctionTransformer class instance. + """ + X = self._check_input(X, reset=True) + if self.check_inverse and not (self.func is None or self.inverse_func is None): + self._check_inverse_transform(X) + return self + + def transform(self, X): + """Transform X using the forward function. + + Parameters + ---------- + X : {array-like, sparse-matrix} of shape (n_samples, n_features) \ + if `validate=True` else any object that `func` can handle + Input array. + + Returns + ------- + X_out : array-like, shape (n_samples, n_features) + Transformed input. + """ + X = self._check_input(X, reset=False) + out = self._transform(X, func=self.func, kw_args=self.kw_args) + output_config = _get_output_config("transform", self)["dense"] + + if hasattr(out, "columns") and self.feature_names_out is not None: + # check the consistency between the column provided by `transform` and + # the the column names provided by `get_feature_names_out`. + feature_names_out = self.get_feature_names_out() + if list(out.columns) != list(feature_names_out): + # we can override the column names of the output if it is inconsistent + # with the column names provided by `get_feature_names_out` in the + # following cases: + # * `func` preserved the column names between the input and the output + # * the input column names are all numbers + # * the output is requested to be a DataFrame (pandas or polars) + feature_names_in = getattr( + X, "feature_names_in_", _get_feature_names(X) + ) + same_feature_names_in_out = feature_names_in is not None and list( + feature_names_in + ) == list(out.columns) + not_all_str_columns = not all( + isinstance(col, str) for col in out.columns + ) + if same_feature_names_in_out or not_all_str_columns: + adapter = _get_adapter_from_container(out) + out = adapter.create_container( + X_output=out, + X_original=out, + columns=feature_names_out, + inplace=False, + ) + else: + raise ValueError( + "The output generated by `func` have different column names " + "than the ones provided by `get_feature_names_out`. " + f"Got output with columns names: {list(out.columns)} and " + "`get_feature_names_out` returned: " + f"{list(self.get_feature_names_out())}. " + "The column names can be overridden by setting " + "`set_output(transform='pandas')` or " + "`set_output(transform='polars')` such that the column names " + "are set to the names provided by `get_feature_names_out`." + ) + + if self.feature_names_out is None: + warn_msg = ( + "When `set_output` is configured to be '{0}', `func` should return " + "a {0} DataFrame to follow the `set_output` API or `feature_names_out`" + " should be defined." + ) + if output_config == "pandas" and not _is_pandas_df(out): + warnings.warn(warn_msg.format("pandas")) + elif output_config == "polars" and not _is_polars_df(out): + warnings.warn(warn_msg.format("polars")) + + return out + + def inverse_transform(self, X): + """Transform X using the inverse function. + + Parameters + ---------- + X : {array-like, sparse-matrix} of shape (n_samples, n_features) \ + if `validate=True` else any object that `inverse_func` can handle + Input array. + + Returns + ------- + X_out : array-like, shape (n_samples, n_features) + Transformed input. + """ + if self.validate: + X = check_array(X, accept_sparse=self.accept_sparse) + return self._transform(X, func=self.inverse_func, kw_args=self.inv_kw_args) + + @available_if(lambda self: self.feature_names_out is not None) + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + This method is only defined if `feature_names_out` is not None. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input feature names. + + - If `input_features` is None, then `feature_names_in_` is + used as the input feature names. If `feature_names_in_` is not + defined, then names are generated: + `[x0, x1, ..., x(n_features_in_ - 1)]`. + - If `input_features` is array-like, then `input_features` must + match `feature_names_in_` if `feature_names_in_` is defined. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + + - If `feature_names_out` is 'one-to-one', the input feature names + are returned (see `input_features` above). This requires + `feature_names_in_` and/or `n_features_in_` to be defined, which + is done automatically if `validate=True`. Alternatively, you can + set them in `func`. + - If `feature_names_out` is a callable, then it is called with two + arguments, `self` and `input_features`, and its return value is + returned by this method. + """ + if hasattr(self, "n_features_in_") or input_features is not None: + input_features = _check_feature_names_in(self, input_features) + if self.feature_names_out == "one-to-one": + names_out = input_features + elif callable(self.feature_names_out): + names_out = self.feature_names_out(self, input_features) + else: + raise ValueError( + f"feature_names_out={self.feature_names_out!r} is invalid. " + 'It must either be "one-to-one" or a callable with two ' + "arguments: the function transformer and an array-like of " + "input feature names. The callable must return an array-like " + "of output feature names." + ) + return np.asarray(names_out, dtype=object) + + def _transform(self, X, func=None, kw_args=None): + if func is None: + func = _identity + + return func(X, **(kw_args if kw_args else {})) + + def __sklearn_is_fitted__(self): + """Return True since FunctionTransfomer is stateless.""" + return True + + def _more_tags(self): + return {"no_validation": not self.validate, "stateless": True} + + 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"}, 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 not hasattr(self, "_sklearn_output_config"): + self._sklearn_output_config = {} + + self._sklearn_output_config["transform"] = transform + return self diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_label.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_label.py new file mode 100644 index 0000000000000000000000000000000000000000..bd009d52a685398c6f94fe1019c8437e95b98313 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_label.py @@ -0,0 +1,951 @@ +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Olivier Grisel +# Andreas Mueller +# Joel Nothman +# Hamzeh Alsalhi +# License: BSD 3 clause + +import array +import itertools +import warnings +from collections import defaultdict +from numbers import Integral + +import numpy as np +import scipy.sparse as sp + +from ..base import BaseEstimator, TransformerMixin, _fit_context +from ..utils import column_or_1d +from ..utils._encode import _encode, _unique +from ..utils._param_validation import Interval, validate_params +from ..utils.multiclass import type_of_target, unique_labels +from ..utils.sparsefuncs import min_max_axis +from ..utils.validation import _num_samples, check_array, check_is_fitted + +__all__ = [ + "label_binarize", + "LabelBinarizer", + "LabelEncoder", + "MultiLabelBinarizer", +] + + +class LabelEncoder(TransformerMixin, BaseEstimator, auto_wrap_output_keys=None): + """Encode target labels with value between 0 and n_classes-1. + + This transformer should be used to encode target values, *i.e.* `y`, and + not the input `X`. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.12 + + Attributes + ---------- + classes_ : ndarray of shape (n_classes,) + Holds the label for each class. + + See Also + -------- + OrdinalEncoder : Encode categorical features using an ordinal encoding + scheme. + OneHotEncoder : Encode categorical features as a one-hot numeric array. + + Examples + -------- + `LabelEncoder` can be used to normalize labels. + + >>> from sklearn.preprocessing import LabelEncoder + >>> le = LabelEncoder() + >>> le.fit([1, 2, 2, 6]) + LabelEncoder() + >>> le.classes_ + array([1, 2, 6]) + >>> le.transform([1, 1, 2, 6]) + array([0, 0, 1, 2]...) + >>> le.inverse_transform([0, 0, 1, 2]) + array([1, 1, 2, 6]) + + It can also be used to transform non-numerical labels (as long as they are + hashable and comparable) to numerical labels. + + >>> le = LabelEncoder() + >>> le.fit(["paris", "paris", "tokyo", "amsterdam"]) + LabelEncoder() + >>> list(le.classes_) + ['amsterdam', 'paris', 'tokyo'] + >>> le.transform(["tokyo", "tokyo", "paris"]) + array([2, 2, 1]...) + >>> list(le.inverse_transform([2, 2, 1])) + ['tokyo', 'tokyo', 'paris'] + """ + + def fit(self, y): + """Fit label encoder. + + Parameters + ---------- + y : array-like of shape (n_samples,) + Target values. + + Returns + ------- + self : returns an instance of self. + Fitted label encoder. + """ + y = column_or_1d(y, warn=True) + self.classes_ = _unique(y) + return self + + def fit_transform(self, y): + """Fit label encoder and return encoded labels. + + Parameters + ---------- + y : array-like of shape (n_samples,) + Target values. + + Returns + ------- + y : array-like of shape (n_samples,) + Encoded labels. + """ + y = column_or_1d(y, warn=True) + self.classes_, y = _unique(y, return_inverse=True) + return y + + def transform(self, y): + """Transform labels to normalized encoding. + + Parameters + ---------- + y : array-like of shape (n_samples,) + Target values. + + Returns + ------- + y : array-like of shape (n_samples,) + Labels as normalized encodings. + """ + check_is_fitted(self) + y = column_or_1d(y, dtype=self.classes_.dtype, warn=True) + # transform of empty array is empty array + if _num_samples(y) == 0: + return np.array([]) + + return _encode(y, uniques=self.classes_) + + def inverse_transform(self, y): + """Transform labels back to original encoding. + + Parameters + ---------- + y : ndarray of shape (n_samples,) + Target values. + + Returns + ------- + y : ndarray of shape (n_samples,) + Original encoding. + """ + check_is_fitted(self) + y = column_or_1d(y, warn=True) + # inverse transform of empty array is empty array + if _num_samples(y) == 0: + return np.array([]) + + diff = np.setdiff1d(y, np.arange(len(self.classes_))) + if len(diff): + raise ValueError("y contains previously unseen labels: %s" % str(diff)) + y = np.asarray(y) + return self.classes_[y] + + def _more_tags(self): + return {"X_types": ["1dlabels"]} + + +class LabelBinarizer(TransformerMixin, BaseEstimator, auto_wrap_output_keys=None): + """Binarize labels in a one-vs-all fashion. + + Several regression and binary classification algorithms are + available in scikit-learn. A simple way to extend these algorithms + to the multi-class classification case is to use the so-called + one-vs-all scheme. + + At learning time, this simply consists in learning one regressor + or binary classifier per class. In doing so, one needs to convert + multi-class labels to binary labels (belong or does not belong + to the class). `LabelBinarizer` makes this process easy with the + transform method. + + At prediction time, one assigns the class for which the corresponding + model gave the greatest confidence. `LabelBinarizer` makes this easy + with the :meth:`inverse_transform` method. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + neg_label : int, default=0 + Value with which negative labels must be encoded. + + pos_label : int, default=1 + Value with which positive labels must be encoded. + + sparse_output : bool, default=False + True if the returned array from transform is desired to be in sparse + CSR format. + + Attributes + ---------- + classes_ : ndarray of shape (n_classes,) + Holds the label for each class. + + y_type_ : str + Represents the type of the target data as evaluated by + :func:`~sklearn.utils.multiclass.type_of_target`. Possible type are + 'continuous', 'continuous-multioutput', 'binary', 'multiclass', + 'multiclass-multioutput', 'multilabel-indicator', and 'unknown'. + + sparse_input_ : bool + `True` if the input data to transform is given as a sparse matrix, + `False` otherwise. + + See Also + -------- + label_binarize : Function to perform the transform operation of + LabelBinarizer with fixed classes. + OneHotEncoder : Encode categorical features using a one-hot aka one-of-K + scheme. + + Examples + -------- + >>> from sklearn.preprocessing import LabelBinarizer + >>> lb = LabelBinarizer() + >>> lb.fit([1, 2, 6, 4, 2]) + LabelBinarizer() + >>> lb.classes_ + array([1, 2, 4, 6]) + >>> lb.transform([1, 6]) + array([[1, 0, 0, 0], + [0, 0, 0, 1]]) + + Binary targets transform to a column vector + + >>> lb = LabelBinarizer() + >>> lb.fit_transform(['yes', 'no', 'no', 'yes']) + array([[1], + [0], + [0], + [1]]) + + Passing a 2D matrix for multilabel classification + + >>> import numpy as np + >>> lb.fit(np.array([[0, 1, 1], [1, 0, 0]])) + LabelBinarizer() + >>> lb.classes_ + array([0, 1, 2]) + >>> lb.transform([0, 1, 2, 1]) + array([[1, 0, 0], + [0, 1, 0], + [0, 0, 1], + [0, 1, 0]]) + """ + + _parameter_constraints: dict = { + "neg_label": [Integral], + "pos_label": [Integral], + "sparse_output": ["boolean"], + } + + def __init__(self, *, neg_label=0, pos_label=1, sparse_output=False): + self.neg_label = neg_label + self.pos_label = pos_label + self.sparse_output = sparse_output + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, y): + """Fit label binarizer. + + Parameters + ---------- + y : ndarray of shape (n_samples,) or (n_samples, n_classes) + Target values. The 2-d matrix should only contain 0 and 1, + represents multilabel classification. + + Returns + ------- + self : object + Returns the instance itself. + """ + if self.neg_label >= self.pos_label: + raise ValueError( + f"neg_label={self.neg_label} must be strictly less than " + f"pos_label={self.pos_label}." + ) + + if self.sparse_output and (self.pos_label == 0 or self.neg_label != 0): + raise ValueError( + "Sparse binarization is only supported with non " + "zero pos_label and zero neg_label, got " + f"pos_label={self.pos_label} and neg_label={self.neg_label}" + ) + + self.y_type_ = type_of_target(y, input_name="y") + + if "multioutput" in self.y_type_: + raise ValueError( + "Multioutput target data is not supported with label binarization" + ) + if _num_samples(y) == 0: + raise ValueError("y has 0 samples: %r" % y) + + self.sparse_input_ = sp.issparse(y) + self.classes_ = unique_labels(y) + return self + + def fit_transform(self, y): + """Fit label binarizer/transform multi-class labels to binary labels. + + The output of transform is sometimes referred to as + the 1-of-K coding scheme. + + Parameters + ---------- + y : {ndarray, sparse matrix} of shape (n_samples,) or \ + (n_samples, n_classes) + Target values. The 2-d matrix should only contain 0 and 1, + represents multilabel classification. Sparse matrix can be + CSR, CSC, COO, DOK, or LIL. + + Returns + ------- + Y : {ndarray, sparse matrix} of shape (n_samples, n_classes) + Shape will be (n_samples, 1) for binary problems. Sparse matrix + will be of CSR format. + """ + return self.fit(y).transform(y) + + def transform(self, y): + """Transform multi-class labels to binary labels. + + The output of transform is sometimes referred to by some authors as + the 1-of-K coding scheme. + + Parameters + ---------- + y : {array, sparse matrix} of shape (n_samples,) or \ + (n_samples, n_classes) + Target values. The 2-d matrix should only contain 0 and 1, + represents multilabel classification. Sparse matrix can be + CSR, CSC, COO, DOK, or LIL. + + Returns + ------- + Y : {ndarray, sparse matrix} of shape (n_samples, n_classes) + Shape will be (n_samples, 1) for binary problems. Sparse matrix + will be of CSR format. + """ + check_is_fitted(self) + + y_is_multilabel = type_of_target(y).startswith("multilabel") + if y_is_multilabel and not self.y_type_.startswith("multilabel"): + raise ValueError("The object was not fitted with multilabel input.") + + return label_binarize( + y, + classes=self.classes_, + pos_label=self.pos_label, + neg_label=self.neg_label, + sparse_output=self.sparse_output, + ) + + def inverse_transform(self, Y, threshold=None): + """Transform binary labels back to multi-class labels. + + Parameters + ---------- + Y : {ndarray, sparse matrix} of shape (n_samples, n_classes) + Target values. All sparse matrices are converted to CSR before + inverse transformation. + + threshold : float, default=None + Threshold used in the binary and multi-label cases. + + Use 0 when ``Y`` contains the output of :term:`decision_function` + (classifier). + Use 0.5 when ``Y`` contains the output of :term:`predict_proba`. + + If None, the threshold is assumed to be half way between + neg_label and pos_label. + + Returns + ------- + y : {ndarray, sparse matrix} of shape (n_samples,) + Target values. Sparse matrix will be of CSR format. + + Notes + ----- + In the case when the binary labels are fractional + (probabilistic), :meth:`inverse_transform` chooses the class with the + greatest value. Typically, this allows to use the output of a + linear model's :term:`decision_function` method directly as the input + of :meth:`inverse_transform`. + """ + check_is_fitted(self) + + if threshold is None: + threshold = (self.pos_label + self.neg_label) / 2.0 + + if self.y_type_ == "multiclass": + y_inv = _inverse_binarize_multiclass(Y, self.classes_) + else: + y_inv = _inverse_binarize_thresholding( + Y, self.y_type_, self.classes_, threshold + ) + + if self.sparse_input_: + y_inv = sp.csr_matrix(y_inv) + elif sp.issparse(y_inv): + y_inv = y_inv.toarray() + + return y_inv + + def _more_tags(self): + return {"X_types": ["1dlabels"]} + + +@validate_params( + { + "y": ["array-like"], + "classes": ["array-like"], + "neg_label": [Interval(Integral, None, None, closed="neither")], + "pos_label": [Interval(Integral, None, None, closed="neither")], + "sparse_output": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def label_binarize(y, *, classes, neg_label=0, pos_label=1, sparse_output=False): + """Binarize labels in a one-vs-all fashion. + + Several regression and binary classification algorithms are + available in scikit-learn. A simple way to extend these algorithms + to the multi-class classification case is to use the so-called + one-vs-all scheme. + + This function makes it possible to compute this transformation for a + fixed set of class labels known ahead of time. + + Parameters + ---------- + y : array-like + Sequence of integer labels or multilabel data to encode. + + classes : array-like of shape (n_classes,) + Uniquely holds the label for each class. + + neg_label : int, default=0 + Value with which negative labels must be encoded. + + pos_label : int, default=1 + Value with which positive labels must be encoded. + + sparse_output : bool, default=False, + Set to true if output binary array is desired in CSR sparse format. + + Returns + ------- + Y : {ndarray, sparse matrix} of shape (n_samples, n_classes) + Shape will be (n_samples, 1) for binary problems. Sparse matrix will + be of CSR format. + + See Also + -------- + LabelBinarizer : Class used to wrap the functionality of label_binarize and + allow for fitting to classes independently of the transform operation. + + Examples + -------- + >>> from sklearn.preprocessing import label_binarize + >>> label_binarize([1, 6], classes=[1, 2, 4, 6]) + array([[1, 0, 0, 0], + [0, 0, 0, 1]]) + + The class ordering is preserved: + + >>> label_binarize([1, 6], classes=[1, 6, 4, 2]) + array([[1, 0, 0, 0], + [0, 1, 0, 0]]) + + Binary targets transform to a column vector + + >>> label_binarize(['yes', 'no', 'no', 'yes'], classes=['no', 'yes']) + array([[1], + [0], + [0], + [1]]) + """ + if not isinstance(y, list): + # XXX Workaround that will be removed when list of list format is + # dropped + y = check_array( + y, input_name="y", accept_sparse="csr", ensure_2d=False, dtype=None + ) + else: + if _num_samples(y) == 0: + raise ValueError("y has 0 samples: %r" % y) + if neg_label >= pos_label: + raise ValueError( + "neg_label={0} must be strictly less than pos_label={1}.".format( + neg_label, pos_label + ) + ) + + if sparse_output and (pos_label == 0 or neg_label != 0): + raise ValueError( + "Sparse binarization is only supported with non " + "zero pos_label and zero neg_label, got " + "pos_label={0} and neg_label={1}" + "".format(pos_label, neg_label) + ) + + # To account for pos_label == 0 in the dense case + pos_switch = pos_label == 0 + if pos_switch: + pos_label = -neg_label + + y_type = type_of_target(y) + if "multioutput" in y_type: + raise ValueError( + "Multioutput target data is not supported with label binarization" + ) + if y_type == "unknown": + raise ValueError("The type of target data is not known") + + n_samples = y.shape[0] if sp.issparse(y) else len(y) + n_classes = len(classes) + classes = np.asarray(classes) + + if y_type == "binary": + if n_classes == 1: + if sparse_output: + return sp.csr_matrix((n_samples, 1), dtype=int) + else: + Y = np.zeros((len(y), 1), dtype=int) + Y += neg_label + return Y + elif len(classes) >= 3: + y_type = "multiclass" + + sorted_class = np.sort(classes) + if y_type == "multilabel-indicator": + y_n_classes = y.shape[1] if hasattr(y, "shape") else len(y[0]) + if classes.size != y_n_classes: + raise ValueError( + "classes {0} mismatch with the labels {1} found in the data".format( + classes, unique_labels(y) + ) + ) + + if y_type in ("binary", "multiclass"): + y = column_or_1d(y) + + # pick out the known labels from y + y_in_classes = np.isin(y, classes) + y_seen = y[y_in_classes] + indices = np.searchsorted(sorted_class, y_seen) + indptr = np.hstack((0, np.cumsum(y_in_classes))) + + data = np.empty_like(indices) + data.fill(pos_label) + Y = sp.csr_matrix((data, indices, indptr), shape=(n_samples, n_classes)) + elif y_type == "multilabel-indicator": + Y = sp.csr_matrix(y) + if pos_label != 1: + data = np.empty_like(Y.data) + data.fill(pos_label) + Y.data = data + else: + raise ValueError( + "%s target data is not supported with label binarization" % y_type + ) + + if not sparse_output: + Y = Y.toarray() + Y = Y.astype(int, copy=False) + + if neg_label != 0: + Y[Y == 0] = neg_label + + if pos_switch: + Y[Y == pos_label] = 0 + else: + Y.data = Y.data.astype(int, copy=False) + + # preserve label ordering + if np.any(classes != sorted_class): + indices = np.searchsorted(sorted_class, classes) + Y = Y[:, indices] + + if y_type == "binary": + if sparse_output: + Y = Y.getcol(-1) + else: + Y = Y[:, -1].reshape((-1, 1)) + + return Y + + +def _inverse_binarize_multiclass(y, classes): + """Inverse label binarization transformation for multiclass. + + Multiclass uses the maximal score instead of a threshold. + """ + classes = np.asarray(classes) + + if sp.issparse(y): + # Find the argmax for each row in y where y is a CSR matrix + + y = y.tocsr() + n_samples, n_outputs = y.shape + outputs = np.arange(n_outputs) + row_max = min_max_axis(y, 1)[1] + row_nnz = np.diff(y.indptr) + + y_data_repeated_max = np.repeat(row_max, row_nnz) + # picks out all indices obtaining the maximum per row + y_i_all_argmax = np.flatnonzero(y_data_repeated_max == y.data) + + # For corner case where last row has a max of 0 + if row_max[-1] == 0: + y_i_all_argmax = np.append(y_i_all_argmax, [len(y.data)]) + + # Gets the index of the first argmax in each row from y_i_all_argmax + index_first_argmax = np.searchsorted(y_i_all_argmax, y.indptr[:-1]) + # first argmax of each row + y_ind_ext = np.append(y.indices, [0]) + y_i_argmax = y_ind_ext[y_i_all_argmax[index_first_argmax]] + # Handle rows of all 0 + y_i_argmax[np.where(row_nnz == 0)[0]] = 0 + + # Handles rows with max of 0 that contain negative numbers + samples = np.arange(n_samples)[(row_nnz > 0) & (row_max.ravel() == 0)] + for i in samples: + ind = y.indices[y.indptr[i] : y.indptr[i + 1]] + y_i_argmax[i] = classes[np.setdiff1d(outputs, ind)][0] + + return classes[y_i_argmax] + else: + return classes.take(y.argmax(axis=1), mode="clip") + + +def _inverse_binarize_thresholding(y, output_type, classes, threshold): + """Inverse label binarization transformation using thresholding.""" + + if output_type == "binary" and y.ndim == 2 and y.shape[1] > 2: + raise ValueError("output_type='binary', but y.shape = {0}".format(y.shape)) + + if output_type != "binary" and y.shape[1] != len(classes): + raise ValueError( + "The number of class is not equal to the number of dimension of y." + ) + + classes = np.asarray(classes) + + # Perform thresholding + if sp.issparse(y): + if threshold > 0: + if y.format not in ("csr", "csc"): + y = y.tocsr() + y.data = np.array(y.data > threshold, dtype=int) + y.eliminate_zeros() + else: + y = np.array(y.toarray() > threshold, dtype=int) + else: + y = np.array(y > threshold, dtype=int) + + # Inverse transform data + if output_type == "binary": + if sp.issparse(y): + y = y.toarray() + if y.ndim == 2 and y.shape[1] == 2: + return classes[y[:, 1]] + else: + if len(classes) == 1: + return np.repeat(classes[0], len(y)) + else: + return classes[y.ravel()] + + elif output_type == "multilabel-indicator": + return y + + else: + raise ValueError("{0} format is not supported".format(output_type)) + + +class MultiLabelBinarizer(TransformerMixin, BaseEstimator, auto_wrap_output_keys=None): + """Transform between iterable of iterables and a multilabel format. + + Although a list of sets or tuples is a very intuitive format for multilabel + data, it is unwieldy to process. This transformer converts between this + intuitive format and the supported multilabel format: a (samples x classes) + binary matrix indicating the presence of a class label. + + Parameters + ---------- + classes : array-like of shape (n_classes,), default=None + Indicates an ordering for the class labels. + All entries should be unique (cannot contain duplicate classes). + + sparse_output : bool, default=False + Set to True if output binary array is desired in CSR sparse format. + + Attributes + ---------- + classes_ : ndarray of shape (n_classes,) + A copy of the `classes` parameter when provided. + Otherwise it corresponds to the sorted set of classes found + when fitting. + + See Also + -------- + OneHotEncoder : Encode categorical features using a one-hot aka one-of-K + scheme. + + Examples + -------- + >>> from sklearn.preprocessing import MultiLabelBinarizer + >>> mlb = MultiLabelBinarizer() + >>> mlb.fit_transform([(1, 2), (3,)]) + array([[1, 1, 0], + [0, 0, 1]]) + >>> mlb.classes_ + array([1, 2, 3]) + + >>> mlb.fit_transform([{'sci-fi', 'thriller'}, {'comedy'}]) + array([[0, 1, 1], + [1, 0, 0]]) + >>> list(mlb.classes_) + ['comedy', 'sci-fi', 'thriller'] + + A common mistake is to pass in a list, which leads to the following issue: + + >>> mlb = MultiLabelBinarizer() + >>> mlb.fit(['sci-fi', 'thriller', 'comedy']) + MultiLabelBinarizer() + >>> mlb.classes_ + array(['-', 'c', 'd', 'e', 'f', 'h', 'i', 'l', 'm', 'o', 'r', 's', 't', + 'y'], dtype=object) + + To correct this, the list of labels should be passed in as: + + >>> mlb = MultiLabelBinarizer() + >>> mlb.fit([['sci-fi', 'thriller', 'comedy']]) + MultiLabelBinarizer() + >>> mlb.classes_ + array(['comedy', 'sci-fi', 'thriller'], dtype=object) + """ + + _parameter_constraints: dict = { + "classes": ["array-like", None], + "sparse_output": ["boolean"], + } + + def __init__(self, *, classes=None, sparse_output=False): + self.classes = classes + self.sparse_output = sparse_output + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, y): + """Fit the label sets binarizer, storing :term:`classes_`. + + Parameters + ---------- + y : iterable of iterables + A set of labels (any orderable and hashable object) for each + sample. If the `classes` parameter is set, `y` will not be + iterated. + + Returns + ------- + self : object + Fitted estimator. + """ + self._cached_dict = None + + if self.classes is None: + classes = sorted(set(itertools.chain.from_iterable(y))) + elif len(set(self.classes)) < len(self.classes): + raise ValueError( + "The classes argument contains duplicate " + "classes. Remove these duplicates before passing " + "them to MultiLabelBinarizer." + ) + else: + classes = self.classes + dtype = int if all(isinstance(c, int) for c in classes) else object + self.classes_ = np.empty(len(classes), dtype=dtype) + self.classes_[:] = classes + return self + + @_fit_context(prefer_skip_nested_validation=True) + def fit_transform(self, y): + """Fit the label sets binarizer and transform the given label sets. + + Parameters + ---------- + y : iterable of iterables + A set of labels (any orderable and hashable object) for each + sample. If the `classes` parameter is set, `y` will not be + iterated. + + Returns + ------- + y_indicator : {ndarray, sparse matrix} of shape (n_samples, n_classes) + A matrix such that `y_indicator[i, j] = 1` iff `classes_[j]` + is in `y[i]`, and 0 otherwise. Sparse matrix will be of CSR + format. + """ + if self.classes is not None: + return self.fit(y).transform(y) + + self._cached_dict = None + + # Automatically increment on new class + class_mapping = defaultdict(int) + class_mapping.default_factory = class_mapping.__len__ + yt = self._transform(y, class_mapping) + + # sort classes and reorder columns + tmp = sorted(class_mapping, key=class_mapping.get) + + # (make safe for tuples) + dtype = int if all(isinstance(c, int) for c in tmp) else object + class_mapping = np.empty(len(tmp), dtype=dtype) + class_mapping[:] = tmp + self.classes_, inverse = np.unique(class_mapping, return_inverse=True) + # ensure yt.indices keeps its current dtype + yt.indices = np.asarray(inverse[yt.indices], dtype=yt.indices.dtype) + + if not self.sparse_output: + yt = yt.toarray() + + return yt + + def transform(self, y): + """Transform the given label sets. + + Parameters + ---------- + y : iterable of iterables + A set of labels (any orderable and hashable object) for each + sample. If the `classes` parameter is set, `y` will not be + iterated. + + Returns + ------- + y_indicator : array or CSR matrix, shape (n_samples, n_classes) + A matrix such that `y_indicator[i, j] = 1` iff `classes_[j]` is in + `y[i]`, and 0 otherwise. + """ + check_is_fitted(self) + + class_to_index = self._build_cache() + yt = self._transform(y, class_to_index) + + if not self.sparse_output: + yt = yt.toarray() + + return yt + + def _build_cache(self): + if self._cached_dict is None: + self._cached_dict = dict(zip(self.classes_, range(len(self.classes_)))) + + return self._cached_dict + + def _transform(self, y, class_mapping): + """Transforms the label sets with a given mapping. + + Parameters + ---------- + y : iterable of iterables + A set of labels (any orderable and hashable object) for each + sample. If the `classes` parameter is set, `y` will not be + iterated. + + class_mapping : Mapping + Maps from label to column index in label indicator matrix. + + Returns + ------- + y_indicator : sparse matrix of shape (n_samples, n_classes) + Label indicator matrix. Will be of CSR format. + """ + indices = array.array("i") + indptr = array.array("i", [0]) + unknown = set() + for labels in y: + index = set() + for label in labels: + try: + index.add(class_mapping[label]) + except KeyError: + unknown.add(label) + indices.extend(index) + indptr.append(len(indices)) + if unknown: + warnings.warn( + "unknown class(es) {0} will be ignored".format(sorted(unknown, key=str)) + ) + data = np.ones(len(indices), dtype=int) + + return sp.csr_matrix( + (data, indices, indptr), shape=(len(indptr) - 1, len(class_mapping)) + ) + + def inverse_transform(self, yt): + """Transform the given indicator matrix into label sets. + + Parameters + ---------- + yt : {ndarray, sparse matrix} of shape (n_samples, n_classes) + A matrix containing only 1s ands 0s. + + Returns + ------- + y : list of tuples + The set of labels for each sample such that `y[i]` consists of + `classes_[j]` for each `yt[i, j] == 1`. + """ + check_is_fitted(self) + + if yt.shape[1] != len(self.classes_): + raise ValueError( + "Expected indicator for {0} classes, but got {1}".format( + len(self.classes_), yt.shape[1] + ) + ) + + if sp.issparse(yt): + yt = yt.tocsr() + if len(yt.data) != 0 and len(np.setdiff1d(yt.data, [0, 1])) > 0: + raise ValueError("Expected only 0s and 1s in label indicator.") + return [ + tuple(self.classes_.take(yt.indices[start:end])) + for start, end in zip(yt.indptr[:-1], yt.indptr[1:]) + ] + else: + unexpected = np.setdiff1d(yt, [0, 1]) + if len(unexpected) > 0: + raise ValueError( + "Expected only 0s and 1s in label indicator. Also got {0}".format( + unexpected + ) + ) + return [tuple(self.classes_.compress(indicators)) for indicators in yt] + + def _more_tags(self): + return {"X_types": ["2dlabels"]} diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_polynomial.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_polynomial.py new file mode 100644 index 0000000000000000000000000000000000000000..2512f411a5a9c20cb3c182b258b54e7e716496e3 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_polynomial.py @@ -0,0 +1,1172 @@ +""" +This file contains preprocessing tools based on polynomials. +""" +import collections +from itertools import chain, combinations +from itertools import combinations_with_replacement as combinations_w_r +from numbers import Integral + +import numpy as np +from scipy import sparse +from scipy.interpolate import BSpline +from scipy.special import comb + +from ..base import BaseEstimator, TransformerMixin, _fit_context +from ..utils import check_array +from ..utils._param_validation import Interval, StrOptions +from ..utils.fixes import parse_version, sp_version +from ..utils.stats import _weighted_percentile +from ..utils.validation import ( + FLOAT_DTYPES, + _check_feature_names_in, + _check_sample_weight, + check_is_fitted, +) +from ._csr_polynomial_expansion import ( + _calc_expanded_nnz, + _calc_total_nnz, + _csr_polynomial_expansion, +) + +__all__ = [ + "PolynomialFeatures", + "SplineTransformer", +] + + +def _create_expansion(X, interaction_only, deg, n_features, cumulative_size=0): + """Helper function for creating and appending sparse expansion matrices""" + + total_nnz = _calc_total_nnz(X.indptr, interaction_only, deg) + expanded_col = _calc_expanded_nnz(n_features, interaction_only, deg) + + if expanded_col == 0: + return None + # This only checks whether each block needs 64bit integers upon + # expansion. We prefer to keep int32 indexing where we can, + # since currently SciPy's CSR construction downcasts when possible, + # so we prefer to avoid an unnecessary cast. The dtype may still + # change in the concatenation process if needed. + # See: https://github.com/scipy/scipy/issues/16569 + max_indices = expanded_col - 1 + max_indptr = total_nnz + max_int32 = np.iinfo(np.int32).max + needs_int64 = max(max_indices, max_indptr) > max_int32 + index_dtype = np.int64 if needs_int64 else np.int32 + + # This is a pretty specific bug that is hard to work around by a user, + # hence we do not detail the entire bug and all possible avoidance + # mechnasisms. Instead we recommend upgrading scipy or shrinking their data. + cumulative_size += expanded_col + if ( + sp_version < parse_version("1.8.0") + and cumulative_size - 1 > max_int32 + and not needs_int64 + ): + raise ValueError( + "In scipy versions `<1.8.0`, the function `scipy.sparse.hstack`" + " sometimes produces negative columns when the output shape contains" + " `n_cols` too large to be represented by a 32bit signed" + " integer. To avoid this error, either use a version" + " of scipy `>=1.8.0` or alter the `PolynomialFeatures`" + " transformer to produce fewer than 2^31 output features." + ) + + # Result of the expansion, modified in place by the + # `_csr_polynomial_expansion` routine. + expanded_data = np.empty(shape=total_nnz, dtype=X.data.dtype) + expanded_indices = np.empty(shape=total_nnz, dtype=index_dtype) + expanded_indptr = np.empty(shape=X.indptr.shape[0], dtype=index_dtype) + _csr_polynomial_expansion( + X.data, + X.indices, + X.indptr, + X.shape[1], + expanded_data, + expanded_indices, + expanded_indptr, + interaction_only, + deg, + ) + return sparse.csr_matrix( + (expanded_data, expanded_indices, expanded_indptr), + shape=(X.indptr.shape[0] - 1, expanded_col), + dtype=X.dtype, + ) + + +class PolynomialFeatures(TransformerMixin, BaseEstimator): + """Generate polynomial and interaction features. + + Generate a new feature matrix consisting of all polynomial combinations + of the features with degree less than or equal to the specified degree. + For example, if an input sample is two dimensional and of the form + [a, b], the degree-2 polynomial features are [1, a, b, a^2, ab, b^2]. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + degree : int or tuple (min_degree, max_degree), default=2 + If a single int is given, it specifies the maximal degree of the + polynomial features. If a tuple `(min_degree, max_degree)` is passed, + then `min_degree` is the minimum and `max_degree` is the maximum + polynomial degree of the generated features. Note that `min_degree=0` + and `min_degree=1` are equivalent as outputting the degree zero term is + determined by `include_bias`. + + interaction_only : bool, default=False + If `True`, only interaction features are produced: features that are + products of at most `degree` *distinct* input features, i.e. terms with + power of 2 or higher of the same input feature are excluded: + + - included: `x[0]`, `x[1]`, `x[0] * x[1]`, etc. + - excluded: `x[0] ** 2`, `x[0] ** 2 * x[1]`, etc. + + include_bias : bool, default=True + If `True` (default), then include a bias column, the feature in which + all polynomial powers are zero (i.e. a column of ones - acts as an + intercept term in a linear model). + + order : {'C', 'F'}, default='C' + Order of output array in the dense case. `'F'` order is faster to + compute, but may slow down subsequent estimators. + + .. versionadded:: 0.21 + + Attributes + ---------- + powers_ : ndarray of shape (`n_output_features_`, `n_features_in_`) + `powers_[i, j]` is the exponent of the jth input in the ith output. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_output_features_ : int + The total number of polynomial output features. The number of output + features is computed by iterating over all suitably sized combinations + of input features. + + See Also + -------- + SplineTransformer : Transformer that generates univariate B-spline bases + for features. + + Notes + ----- + Be aware that the number of features in the output array scales + polynomially in the number of features of the input array, and + exponentially in the degree. High degrees can cause overfitting. + + See :ref:`examples/linear_model/plot_polynomial_interpolation.py + ` + + Examples + -------- + >>> import numpy as np + >>> from sklearn.preprocessing import PolynomialFeatures + >>> X = np.arange(6).reshape(3, 2) + >>> X + array([[0, 1], + [2, 3], + [4, 5]]) + >>> poly = PolynomialFeatures(2) + >>> poly.fit_transform(X) + array([[ 1., 0., 1., 0., 0., 1.], + [ 1., 2., 3., 4., 6., 9.], + [ 1., 4., 5., 16., 20., 25.]]) + >>> poly = PolynomialFeatures(interaction_only=True) + >>> poly.fit_transform(X) + array([[ 1., 0., 1., 0.], + [ 1., 2., 3., 6.], + [ 1., 4., 5., 20.]]) + """ + + _parameter_constraints: dict = { + "degree": [Interval(Integral, 0, None, closed="left"), "array-like"], + "interaction_only": ["boolean"], + "include_bias": ["boolean"], + "order": [StrOptions({"C", "F"})], + } + + def __init__( + self, degree=2, *, interaction_only=False, include_bias=True, order="C" + ): + self.degree = degree + self.interaction_only = interaction_only + self.include_bias = include_bias + self.order = order + + @staticmethod + def _combinations( + n_features, min_degree, max_degree, interaction_only, include_bias + ): + comb = combinations if interaction_only else combinations_w_r + start = max(1, min_degree) + iter = chain.from_iterable( + comb(range(n_features), i) for i in range(start, max_degree + 1) + ) + if include_bias: + iter = chain(comb(range(n_features), 0), iter) + return iter + + @staticmethod + def _num_combinations( + n_features, min_degree, max_degree, interaction_only, include_bias + ): + """Calculate number of terms in polynomial expansion + + This should be equivalent to counting the number of terms returned by + _combinations(...) but much faster. + """ + + if interaction_only: + combinations = sum( + [ + comb(n_features, i, exact=True) + for i in range(max(1, min_degree), min(max_degree, n_features) + 1) + ] + ) + else: + combinations = comb(n_features + max_degree, max_degree, exact=True) - 1 + if min_degree > 0: + d = min_degree - 1 + combinations -= comb(n_features + d, d, exact=True) - 1 + + if include_bias: + combinations += 1 + + return combinations + + @property + def powers_(self): + """Exponent for each of the inputs in the output.""" + check_is_fitted(self) + + combinations = self._combinations( + n_features=self.n_features_in_, + min_degree=self._min_degree, + max_degree=self._max_degree, + interaction_only=self.interaction_only, + include_bias=self.include_bias, + ) + return np.vstack( + [np.bincount(c, minlength=self.n_features_in_) for c in combinations] + ) + + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input features. + + - If `input_features is None`, then `feature_names_in_` is + used as feature names in. If `feature_names_in_` is not defined, + then the following input feature names are generated: + `["x0", "x1", ..., "x(n_features_in_ - 1)"]`. + - If `input_features` is an array-like, then `input_features` must + match `feature_names_in_` if `feature_names_in_` is defined. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + powers = self.powers_ + input_features = _check_feature_names_in(self, input_features) + feature_names = [] + for row in powers: + inds = np.where(row)[0] + if len(inds): + name = " ".join( + ( + "%s^%d" % (input_features[ind], exp) + if exp != 1 + else input_features[ind] + ) + for ind, exp in zip(inds, row[inds]) + ) + else: + name = "1" + feature_names.append(name) + return np.asarray(feature_names, dtype=object) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """ + Compute number of output features. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + Fitted transformer. + """ + _, n_features = self._validate_data(X, accept_sparse=True).shape + + if isinstance(self.degree, Integral): + if self.degree == 0 and not self.include_bias: + raise ValueError( + "Setting degree to zero and include_bias to False would result in" + " an empty output array." + ) + + self._min_degree = 0 + self._max_degree = self.degree + elif ( + isinstance(self.degree, collections.abc.Iterable) and len(self.degree) == 2 + ): + self._min_degree, self._max_degree = self.degree + if not ( + isinstance(self._min_degree, Integral) + and isinstance(self._max_degree, Integral) + and self._min_degree >= 0 + and self._min_degree <= self._max_degree + ): + raise ValueError( + "degree=(min_degree, max_degree) must " + "be non-negative integers that fulfil " + "min_degree <= max_degree, got " + f"{self.degree}." + ) + elif self._max_degree == 0 and not self.include_bias: + raise ValueError( + "Setting both min_degree and max_degree to zero and include_bias to" + " False would result in an empty output array." + ) + else: + raise ValueError( + "degree must be a non-negative int or tuple " + "(min_degree, max_degree), got " + f"{self.degree}." + ) + + self.n_output_features_ = self._num_combinations( + n_features=n_features, + min_degree=self._min_degree, + max_degree=self._max_degree, + interaction_only=self.interaction_only, + include_bias=self.include_bias, + ) + if self.n_output_features_ > np.iinfo(np.intp).max: + msg = ( + "The output that would result from the current configuration would" + f" have {self.n_output_features_} features which is too large to be" + f" indexed by {np.intp().dtype.name}. Please change some or all of the" + " following:\n- The number of features in the input, currently" + f" {n_features=}\n- The range of degrees to calculate, currently" + f" [{self._min_degree}, {self._max_degree}]\n- Whether to include only" + f" interaction terms, currently {self.interaction_only}\n- Whether to" + f" include a bias term, currently {self.include_bias}." + ) + if ( + np.intp == np.int32 + and self.n_output_features_ <= np.iinfo(np.int64).max + ): # pragma: nocover + msg += ( + "\nNote that the current Python runtime has a limited 32 bit " + "address space and that this configuration would have been " + "admissible if run on a 64 bit Python runtime." + ) + raise ValueError(msg) + # We also record the number of output features for + # _max_degree = 0 + self._n_out_full = self._num_combinations( + n_features=n_features, + min_degree=0, + max_degree=self._max_degree, + interaction_only=self.interaction_only, + include_bias=self.include_bias, + ) + + return self + + def transform(self, X): + """Transform data to polynomial features. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to transform, row by row. + + Prefer CSR over CSC for sparse input (for speed), but CSC is + required if the degree is 4 or higher. If the degree is less than + 4 and the input format is CSC, it will be converted to CSR, have + its polynomial features generated, then converted back to CSC. + + If the degree is 2 or 3, the method described in "Leveraging + Sparsity to Speed Up Polynomial Feature Expansions of CSR Matrices + Using K-Simplex Numbers" by Andrew Nystrom and John Hughes is + used, which is much faster than the method used on CSC input. For + this reason, a CSC input will be converted to CSR, and the output + will be converted back to CSC prior to being returned, hence the + preference of CSR. + + Returns + ------- + XP : {ndarray, sparse matrix} of shape (n_samples, NP) + The matrix of features, where `NP` is the number of polynomial + features generated from the combination of inputs. If a sparse + matrix is provided, it will be converted into a sparse + `csr_matrix`. + """ + check_is_fitted(self) + + X = self._validate_data( + X, order="F", dtype=FLOAT_DTYPES, reset=False, accept_sparse=("csr", "csc") + ) + + n_samples, n_features = X.shape + max_int32 = np.iinfo(np.int32).max + if sparse.issparse(X) and X.format == "csr": + if self._max_degree > 3: + return self.transform(X.tocsc()).tocsr() + to_stack = [] + if self.include_bias: + to_stack.append( + sparse.csr_matrix(np.ones(shape=(n_samples, 1), dtype=X.dtype)) + ) + if self._min_degree <= 1 and self._max_degree > 0: + to_stack.append(X) + + cumulative_size = sum(mat.shape[1] for mat in to_stack) + for deg in range(max(2, self._min_degree), self._max_degree + 1): + expanded = _create_expansion( + X=X, + interaction_only=self.interaction_only, + deg=deg, + n_features=n_features, + cumulative_size=cumulative_size, + ) + if expanded is not None: + to_stack.append(expanded) + cumulative_size += expanded.shape[1] + if len(to_stack) == 0: + # edge case: deal with empty matrix + XP = sparse.csr_matrix((n_samples, 0), dtype=X.dtype) + else: + # `scipy.sparse.hstack` breaks in scipy<1.9.2 + # when `n_output_features_ > max_int32` + all_int32 = all(mat.indices.dtype == np.int32 for mat in to_stack) + if ( + sp_version < parse_version("1.9.2") + and self.n_output_features_ > max_int32 + and all_int32 + ): + raise ValueError( # pragma: no cover + "In scipy versions `<1.9.2`, the function `scipy.sparse.hstack`" + " produces negative columns when:\n1. The output shape contains" + " `n_cols` too large to be represented by a 32bit signed" + " integer.\n2. All sub-matrices to be stacked have indices of" + " dtype `np.int32`.\nTo avoid this error, either use a version" + " of scipy `>=1.9.2` or alter the `PolynomialFeatures`" + " transformer to produce fewer than 2^31 output features" + ) + XP = sparse.hstack(to_stack, dtype=X.dtype, format="csr") + elif sparse.issparse(X) and X.format == "csc" and self._max_degree < 4: + return self.transform(X.tocsr()).tocsc() + elif sparse.issparse(X): + combinations = self._combinations( + n_features=n_features, + min_degree=self._min_degree, + max_degree=self._max_degree, + interaction_only=self.interaction_only, + include_bias=self.include_bias, + ) + columns = [] + for combi in combinations: + if combi: + out_col = 1 + for col_idx in combi: + out_col = X[:, [col_idx]].multiply(out_col) + columns.append(out_col) + else: + bias = sparse.csc_matrix(np.ones((X.shape[0], 1))) + columns.append(bias) + XP = sparse.hstack(columns, dtype=X.dtype).tocsc() + else: + # Do as if _min_degree = 0 and cut down array after the + # computation, i.e. use _n_out_full instead of n_output_features_. + XP = np.empty( + shape=(n_samples, self._n_out_full), dtype=X.dtype, order=self.order + ) + + # What follows is a faster implementation of: + # for i, comb in enumerate(combinations): + # XP[:, i] = X[:, comb].prod(1) + # This implementation uses two optimisations. + # First one is broadcasting, + # multiply ([X1, ..., Xn], X1) -> [X1 X1, ..., Xn X1] + # multiply ([X2, ..., Xn], X2) -> [X2 X2, ..., Xn X2] + # ... + # multiply ([X[:, start:end], X[:, start]) -> ... + # Second optimisation happens for degrees >= 3. + # Xi^3 is computed reusing previous computation: + # Xi^3 = Xi^2 * Xi. + + # degree 0 term + if self.include_bias: + XP[:, 0] = 1 + current_col = 1 + else: + current_col = 0 + + if self._max_degree == 0: + return XP + + # degree 1 term + XP[:, current_col : current_col + n_features] = X + index = list(range(current_col, current_col + n_features)) + current_col += n_features + index.append(current_col) + + # loop over degree >= 2 terms + for _ in range(2, self._max_degree + 1): + new_index = [] + end = index[-1] + for feature_idx in range(n_features): + start = index[feature_idx] + new_index.append(current_col) + if self.interaction_only: + start += index[feature_idx + 1] - index[feature_idx] + next_col = current_col + end - start + if next_col <= current_col: + break + # XP[:, start:end] are terms of degree d - 1 + # that exclude feature #feature_idx. + np.multiply( + XP[:, start:end], + X[:, feature_idx : feature_idx + 1], + out=XP[:, current_col:next_col], + casting="no", + ) + current_col = next_col + + new_index.append(current_col) + index = new_index + + if self._min_degree > 1: + n_XP, n_Xout = self._n_out_full, self.n_output_features_ + if self.include_bias: + Xout = np.empty( + shape=(n_samples, n_Xout), dtype=XP.dtype, order=self.order + ) + Xout[:, 0] = 1 + Xout[:, 1:] = XP[:, n_XP - n_Xout + 1 :] + else: + Xout = XP[:, n_XP - n_Xout :].copy() + XP = Xout + return XP + + +class SplineTransformer(TransformerMixin, BaseEstimator): + """Generate univariate B-spline bases for features. + + Generate a new feature matrix consisting of + `n_splines=n_knots + degree - 1` (`n_knots - 1` for + `extrapolation="periodic"`) spline basis functions + (B-splines) of polynomial order=`degree` for each feature. + + In order to learn more about the SplineTransformer class go to: + :ref:`sphx_glr_auto_examples_applications_plot_cyclical_feature_engineering.py` + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + n_knots : int, default=5 + Number of knots of the splines if `knots` equals one of + {'uniform', 'quantile'}. Must be larger or equal 2. Ignored if `knots` + is array-like. + + degree : int, default=3 + The polynomial degree of the spline basis. Must be a non-negative + integer. + + knots : {'uniform', 'quantile'} or array-like of shape \ + (n_knots, n_features), default='uniform' + Set knot positions such that first knot <= features <= last knot. + + - If 'uniform', `n_knots` number of knots are distributed uniformly + from min to max values of the features. + - If 'quantile', they are distributed uniformly along the quantiles of + the features. + - If an array-like is given, it directly specifies the sorted knot + positions including the boundary knots. Note that, internally, + `degree` number of knots are added before the first knot, the same + after the last knot. + + extrapolation : {'error', 'constant', 'linear', 'continue', 'periodic'}, \ + default='constant' + If 'error', values outside the min and max values of the training + features raises a `ValueError`. If 'constant', the value of the + splines at minimum and maximum value of the features is used as + constant extrapolation. If 'linear', a linear extrapolation is used. + If 'continue', the splines are extrapolated as is, i.e. option + `extrapolate=True` in :class:`scipy.interpolate.BSpline`. If + 'periodic', periodic splines with a periodicity equal to the distance + between the first and last knot are used. Periodic splines enforce + equal function values and derivatives at the first and last knot. + For example, this makes it possible to avoid introducing an arbitrary + jump between Dec 31st and Jan 1st in spline features derived from a + naturally periodic "day-of-year" input feature. In this case it is + recommended to manually set the knot values to control the period. + + include_bias : bool, default=True + If False, then the last spline element inside the data range + of a feature is dropped. As B-splines sum to one over the spline basis + functions for each data point, they implicitly include a bias term, + i.e. a column of ones. It acts as an intercept term in a linear models. + + order : {'C', 'F'}, default='C' + Order of output array in the dense case. `'F'` order is faster to compute, but + may slow down subsequent estimators. + + sparse_output : bool, default=False + Will return sparse CSR matrix if set True else will return an array. This + option is only available with `scipy>=1.8`. + + .. versionadded:: 1.2 + + Attributes + ---------- + bsplines_ : list of shape (n_features,) + List of BSplines objects, one for each feature. + + n_features_in_ : int + The total number of input features. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_features_out_ : int + The total number of output features, which is computed as + `n_features * n_splines`, where `n_splines` is + the number of bases elements of the B-splines, + `n_knots + degree - 1` for non-periodic splines and + `n_knots - 1` for periodic ones. + If `include_bias=False`, then it is only + `n_features * (n_splines - 1)`. + + See Also + -------- + KBinsDiscretizer : Transformer that bins continuous data into intervals. + + PolynomialFeatures : Transformer that generates polynomial and interaction + features. + + Notes + ----- + High degrees and a high number of knots can cause overfitting. + + See :ref:`examples/linear_model/plot_polynomial_interpolation.py + `. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.preprocessing import SplineTransformer + >>> X = np.arange(6).reshape(6, 1) + >>> spline = SplineTransformer(degree=2, n_knots=3) + >>> spline.fit_transform(X) + array([[0.5 , 0.5 , 0. , 0. ], + [0.18, 0.74, 0.08, 0. ], + [0.02, 0.66, 0.32, 0. ], + [0. , 0.32, 0.66, 0.02], + [0. , 0.08, 0.74, 0.18], + [0. , 0. , 0.5 , 0.5 ]]) + """ + + _parameter_constraints: dict = { + "n_knots": [Interval(Integral, 2, None, closed="left")], + "degree": [Interval(Integral, 0, None, closed="left")], + "knots": [StrOptions({"uniform", "quantile"}), "array-like"], + "extrapolation": [ + StrOptions({"error", "constant", "linear", "continue", "periodic"}) + ], + "include_bias": ["boolean"], + "order": [StrOptions({"C", "F"})], + "sparse_output": ["boolean"], + } + + def __init__( + self, + n_knots=5, + degree=3, + *, + knots="uniform", + extrapolation="constant", + include_bias=True, + order="C", + sparse_output=False, + ): + self.n_knots = n_knots + self.degree = degree + self.knots = knots + self.extrapolation = extrapolation + self.include_bias = include_bias + self.order = order + self.sparse_output = sparse_output + + @staticmethod + def _get_base_knot_positions(X, n_knots=10, knots="uniform", sample_weight=None): + """Calculate base knot positions. + + Base knots such that first knot <= feature <= last knot. For the + B-spline construction with scipy.interpolate.BSpline, 2*degree knots + beyond the base interval are added. + + Returns + ------- + knots : ndarray of shape (n_knots, n_features), dtype=np.float64 + Knot positions (points) of base interval. + """ + if knots == "quantile": + percentiles = 100 * np.linspace( + start=0, stop=1, num=n_knots, dtype=np.float64 + ) + + if sample_weight is None: + knots = np.percentile(X, percentiles, axis=0) + else: + knots = np.array( + [ + _weighted_percentile(X, sample_weight, percentile) + for percentile in percentiles + ] + ) + + else: + # knots == 'uniform': + # Note that the variable `knots` has already been validated and + # `else` is therefore safe. + # Disregard observations with zero weight. + mask = slice(None, None, 1) if sample_weight is None else sample_weight > 0 + x_min = np.amin(X[mask], axis=0) + x_max = np.amax(X[mask], axis=0) + + knots = np.linspace( + start=x_min, + stop=x_max, + num=n_knots, + endpoint=True, + dtype=np.float64, + ) + + return knots + + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Input features. + + - If `input_features` is `None`, then `feature_names_in_` is + used as feature names in. If `feature_names_in_` is not defined, + then the following input feature names are generated: + `["x0", "x1", ..., "x(n_features_in_ - 1)"]`. + - If `input_features` is an array-like, then `input_features` must + match `feature_names_in_` if `feature_names_in_` is defined. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. + """ + check_is_fitted(self, "n_features_in_") + n_splines = self.bsplines_[0].c.shape[1] + + input_features = _check_feature_names_in(self, input_features) + feature_names = [] + for i in range(self.n_features_in_): + for j in range(n_splines - 1 + self.include_bias): + feature_names.append(f"{input_features[i]}_sp_{j}") + return np.asarray(feature_names, dtype=object) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None, sample_weight=None): + """Compute knot positions of splines. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data. + + y : None + Ignored. + + sample_weight : array-like of shape (n_samples,), default = None + Individual weights for each sample. Used to calculate quantiles if + `knots="quantile"`. For `knots="uniform"`, zero weighted + observations are ignored for finding the min and max of `X`. + + Returns + ------- + self : object + Fitted transformer. + """ + X = self._validate_data( + X, + reset=True, + accept_sparse=False, + ensure_min_samples=2, + ensure_2d=True, + ) + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + _, n_features = X.shape + + if isinstance(self.knots, str): + base_knots = self._get_base_knot_positions( + X, n_knots=self.n_knots, knots=self.knots, sample_weight=sample_weight + ) + else: + base_knots = check_array(self.knots, dtype=np.float64) + if base_knots.shape[0] < 2: + raise ValueError("Number of knots, knots.shape[0], must be >= 2.") + elif base_knots.shape[1] != n_features: + raise ValueError("knots.shape[1] == n_features is violated.") + elif not np.all(np.diff(base_knots, axis=0) > 0): + raise ValueError("knots must be sorted without duplicates.") + + if self.sparse_output and sp_version < parse_version("1.8.0"): + raise ValueError( + "Option sparse_output=True is only available with scipy>=1.8.0, " + f"but here scipy=={sp_version} is used." + ) + + # number of knots for base interval + n_knots = base_knots.shape[0] + + if self.extrapolation == "periodic" and n_knots <= self.degree: + raise ValueError( + "Periodic splines require degree < n_knots. Got n_knots=" + f"{n_knots} and degree={self.degree}." + ) + + # number of splines basis functions + if self.extrapolation != "periodic": + n_splines = n_knots + self.degree - 1 + else: + # periodic splines have self.degree less degrees of freedom + n_splines = n_knots - 1 + + degree = self.degree + n_out = n_features * n_splines + # We have to add degree number of knots below, and degree number knots + # above the base knots in order to make the spline basis complete. + if self.extrapolation == "periodic": + # For periodic splines the spacing of the first / last degree knots + # needs to be a continuation of the spacing of the last / first + # base knots. + period = base_knots[-1] - base_knots[0] + knots = np.r_[ + base_knots[-(degree + 1) : -1] - period, + base_knots, + base_knots[1 : (degree + 1)] + period, + ] + + else: + # Eilers & Marx in "Flexible smoothing with B-splines and + # penalties" https://doi.org/10.1214/ss/1038425655 advice + # against repeating first and last knot several times, which + # would have inferior behaviour at boundaries if combined with + # a penalty (hence P-Spline). We follow this advice even if our + # splines are unpenalized. Meaning we do not: + # knots = np.r_[ + # np.tile(base_knots.min(axis=0), reps=[degree, 1]), + # base_knots, + # np.tile(base_knots.max(axis=0), reps=[degree, 1]) + # ] + # Instead, we reuse the distance of the 2 fist/last knots. + dist_min = base_knots[1] - base_knots[0] + dist_max = base_knots[-1] - base_knots[-2] + + knots = np.r_[ + np.linspace( + base_knots[0] - degree * dist_min, + base_knots[0] - dist_min, + num=degree, + ), + base_knots, + np.linspace( + base_knots[-1] + dist_max, + base_knots[-1] + degree * dist_max, + num=degree, + ), + ] + + # With a diagonal coefficient matrix, we get back the spline basis + # elements, i.e. the design matrix of the spline. + # Note, BSpline appreciates C-contiguous float64 arrays as c=coef. + coef = np.eye(n_splines, dtype=np.float64) + if self.extrapolation == "periodic": + coef = np.concatenate((coef, coef[:degree, :])) + + extrapolate = self.extrapolation in ["periodic", "continue"] + + bsplines = [ + BSpline.construct_fast( + knots[:, i], coef, self.degree, extrapolate=extrapolate + ) + for i in range(n_features) + ] + self.bsplines_ = bsplines + + self.n_features_out_ = n_out - n_features * (1 - self.include_bias) + return self + + def transform(self, X): + """Transform each feature data to B-splines. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data to transform. + + Returns + ------- + XBS : {ndarray, sparse matrix} of shape (n_samples, n_features * n_splines) + The matrix of features, where n_splines is the number of bases + elements of the B-splines, n_knots + degree - 1. + """ + check_is_fitted(self) + + X = self._validate_data(X, reset=False, accept_sparse=False, ensure_2d=True) + + n_samples, n_features = X.shape + n_splines = self.bsplines_[0].c.shape[1] + degree = self.degree + + # TODO: Remove this condition, once scipy 1.10 is the minimum version. + # Only scipy => 1.10 supports design_matrix(.., extrapolate=..). + # The default (implicit in scipy < 1.10) is extrapolate=False. + scipy_1_10 = sp_version >= parse_version("1.10.0") + # Note: self.bsplines_[0].extrapolate is True for extrapolation in + # ["periodic", "continue"] + if scipy_1_10: + use_sparse = self.sparse_output + kwargs_extrapolate = {"extrapolate": self.bsplines_[0].extrapolate} + else: + use_sparse = self.sparse_output and not self.bsplines_[0].extrapolate + kwargs_extrapolate = dict() + + # Note that scipy BSpline returns float64 arrays and converts input + # x=X[:, i] to c-contiguous float64. + n_out = self.n_features_out_ + n_features * (1 - self.include_bias) + if X.dtype in FLOAT_DTYPES: + dtype = X.dtype + else: + dtype = np.float64 + if use_sparse: + output_list = [] + else: + XBS = np.zeros((n_samples, n_out), dtype=dtype, order=self.order) + + for i in range(n_features): + spl = self.bsplines_[i] + + if self.extrapolation in ("continue", "error", "periodic"): + if self.extrapolation == "periodic": + # With periodic extrapolation we map x to the segment + # [spl.t[k], spl.t[n]]. + # This is equivalent to BSpline(.., extrapolate="periodic") + # for scipy>=1.0.0. + n = spl.t.size - spl.k - 1 + # Assign to new array to avoid inplace operation + x = spl.t[spl.k] + (X[:, i] - spl.t[spl.k]) % ( + spl.t[n] - spl.t[spl.k] + ) + else: + x = X[:, i] + + if use_sparse: + XBS_sparse = BSpline.design_matrix( + x, spl.t, spl.k, **kwargs_extrapolate + ) + if self.extrapolation == "periodic": + # See the construction of coef in fit. We need to add the last + # degree spline basis function to the first degree ones and + # then drop the last ones. + # Note: See comment about SparseEfficiencyWarning below. + XBS_sparse = XBS_sparse.tolil() + XBS_sparse[:, :degree] += XBS_sparse[:, -degree:] + XBS_sparse = XBS_sparse[:, :-degree] + else: + XBS[:, (i * n_splines) : ((i + 1) * n_splines)] = spl(x) + else: # extrapolation in ("constant", "linear") + xmin, xmax = spl.t[degree], spl.t[-degree - 1] + # spline values at boundaries + f_min, f_max = spl(xmin), spl(xmax) + mask = (xmin <= X[:, i]) & (X[:, i] <= xmax) + if use_sparse: + mask_inv = ~mask + x = X[:, i].copy() + # Set some arbitrary values outside boundary that will be reassigned + # later. + x[mask_inv] = spl.t[self.degree] + XBS_sparse = BSpline.design_matrix(x, spl.t, spl.k) + # Note: Without converting to lil_matrix we would get: + # scipy.sparse._base.SparseEfficiencyWarning: Changing the sparsity + # structure of a csr_matrix is expensive. lil_matrix is more + # efficient. + if np.any(mask_inv): + XBS_sparse = XBS_sparse.tolil() + XBS_sparse[mask_inv, :] = 0 + else: + XBS[mask, (i * n_splines) : ((i + 1) * n_splines)] = spl(X[mask, i]) + + # Note for extrapolation: + # 'continue' is already returned as is by scipy BSplines + if self.extrapolation == "error": + # BSpline with extrapolate=False does not raise an error, but + # outputs np.nan. + if (use_sparse and np.any(np.isnan(XBS_sparse.data))) or ( + not use_sparse + and np.any( + np.isnan(XBS[:, (i * n_splines) : ((i + 1) * n_splines)]) + ) + ): + raise ValueError( + "X contains values beyond the limits of the knots." + ) + elif self.extrapolation == "constant": + # Set all values beyond xmin and xmax to the value of the + # spline basis functions at those two positions. + # Only the first degree and last degree number of splines + # have non-zero values at the boundaries. + + mask = X[:, i] < xmin + if np.any(mask): + if use_sparse: + # Note: See comment about SparseEfficiencyWarning above. + XBS_sparse = XBS_sparse.tolil() + XBS_sparse[mask, :degree] = f_min[:degree] + + else: + XBS[mask, (i * n_splines) : (i * n_splines + degree)] = f_min[ + :degree + ] + + mask = X[:, i] > xmax + if np.any(mask): + if use_sparse: + # Note: See comment about SparseEfficiencyWarning above. + XBS_sparse = XBS_sparse.tolil() + XBS_sparse[mask, -degree:] = f_max[-degree:] + else: + XBS[ + mask, + ((i + 1) * n_splines - degree) : ((i + 1) * n_splines), + ] = f_max[-degree:] + + elif self.extrapolation == "linear": + # Continue the degree first and degree last spline bases + # linearly beyond the boundaries, with slope = derivative at + # the boundary. + # Note that all others have derivative = value = 0 at the + # boundaries. + + # spline derivatives = slopes at boundaries + fp_min, fp_max = spl(xmin, nu=1), spl(xmax, nu=1) + # Compute the linear continuation. + if degree <= 1: + # For degree=1, the derivative of 2nd spline is not zero at + # boundary. For degree=0 it is the same as 'constant'. + degree += 1 + for j in range(degree): + mask = X[:, i] < xmin + if np.any(mask): + linear_extr = f_min[j] + (X[mask, i] - xmin) * fp_min[j] + if use_sparse: + # Note: See comment about SparseEfficiencyWarning above. + XBS_sparse = XBS_sparse.tolil() + XBS_sparse[mask, j] = linear_extr + else: + XBS[mask, i * n_splines + j] = linear_extr + + mask = X[:, i] > xmax + if np.any(mask): + k = n_splines - 1 - j + linear_extr = f_max[k] + (X[mask, i] - xmax) * fp_max[k] + if use_sparse: + # Note: See comment about SparseEfficiencyWarning above. + XBS_sparse = XBS_sparse.tolil() + XBS_sparse[mask, k : k + 1] = linear_extr[:, None] + else: + XBS[mask, i * n_splines + k] = linear_extr + + if use_sparse: + XBS_sparse = XBS_sparse.tocsr() + output_list.append(XBS_sparse) + + if use_sparse: + # TODO: Remove this conditional error when the minimum supported version of + # SciPy is 1.9.2 + # `scipy.sparse.hstack` breaks in scipy<1.9.2 + # when `n_features_out_ > max_int32` + max_int32 = np.iinfo(np.int32).max + all_int32 = True + for mat in output_list: + all_int32 &= mat.indices.dtype == np.int32 + if ( + sp_version < parse_version("1.9.2") + and self.n_features_out_ > max_int32 + and all_int32 + ): + raise ValueError( + "In scipy versions `<1.9.2`, the function `scipy.sparse.hstack`" + " produces negative columns when:\n1. The output shape contains" + " `n_cols` too large to be represented by a 32bit signed" + " integer.\n. All sub-matrices to be stacked have indices of" + " dtype `np.int32`.\nTo avoid this error, either use a version" + " of scipy `>=1.9.2` or alter the `SplineTransformer`" + " transformer to produce fewer than 2^31 output features" + ) + XBS = sparse.hstack(output_list, format="csr") + elif self.sparse_output: + # TODO: Remove ones scipy 1.10 is the minimum version. See comments above. + XBS = sparse.csr_matrix(XBS) + + if self.include_bias: + return XBS + else: + # We throw away one spline basis per feature. + # We chose the last one. + indices = [j for j in range(XBS.shape[1]) if (j + 1) % n_splines != 0] + return XBS[:, indices] + + def _more_tags(self): + return { + "_xfail_checks": { + "check_estimators_pickle": ( + "Current Scipy implementation of _bsplines does not" + "support const memory views." + ), + } + } diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_target_encoder.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_target_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..b3b7c3d5e7bd911153d9e9724c05cc673c9f3cfd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_target_encoder.py @@ -0,0 +1,531 @@ +from numbers import Integral, Real + +import numpy as np + +from ..base import OneToOneFeatureMixin, _fit_context +from ..utils._param_validation import Interval, StrOptions +from ..utils.multiclass import type_of_target +from ..utils.validation import ( + _check_feature_names_in, + _check_y, + check_consistent_length, + check_is_fitted, +) +from ._encoders import _BaseEncoder +from ._target_encoder_fast import _fit_encoding_fast, _fit_encoding_fast_auto_smooth + + +class TargetEncoder(OneToOneFeatureMixin, _BaseEncoder): + """Target Encoder for regression and classification targets. + + Each category is encoded based on a shrunk estimate of the average target + values for observations belonging to the category. The encoding scheme mixes + the global target mean with the target mean conditioned on the value of the + category (see [MIC]_). + + When the target type is "multiclass", encodings are based + on the conditional probability estimate for each class. The target is first + binarized using the "one-vs-all" scheme via + :class:`~sklearn.preprocessing.LabelBinarizer`, then the average target + value for each class and each category is used for encoding, resulting in + `n_features` * `n_classes` encoded output features. + + :class:`TargetEncoder` considers missing values, such as `np.nan` or `None`, + as another category and encodes them like any other category. Categories + that are not seen during :meth:`fit` are encoded with the target mean, i.e. + `target_mean_`. + + For a demo on the importance of the `TargetEncoder` internal cross-fitting, + see + :ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder_cross_val.py`. + For a comparison of different encoders, refer to + :ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder.py`. Read + more in the :ref:`User Guide `. + + .. note:: + `fit(X, y).transform(X)` does not equal `fit_transform(X, y)` because a + :term:`cross fitting` scheme is used in `fit_transform` for encoding. + See the :ref:`User Guide ` for details. + + .. versionadded:: 1.3 + + Parameters + ---------- + categories : "auto" or list of shape (n_features,) of array-like, default="auto" + Categories (unique values) per feature: + + - `"auto"` : Determine categories automatically from the training data. + - list : `categories[i]` holds the categories expected in the i-th column. The + passed categories should not mix strings and numeric values within a single + feature, and should be sorted in case of numeric values. + + The used categories are stored in the `categories_` fitted attribute. + + target_type : {"auto", "continuous", "binary", "multiclass"}, default="auto" + Type of target. + + - `"auto"` : Type of target is inferred with + :func:`~sklearn.utils.multiclass.type_of_target`. + - `"continuous"` : Continuous target + - `"binary"` : Binary target + - `"multiclass"` : Multiclass target + + .. note:: + The type of target inferred with `"auto"` may not be the desired target + type used for modeling. For example, if the target consisted of integers + between 0 and 100, then :func:`~sklearn.utils.multiclass.type_of_target` + will infer the target as `"multiclass"`. In this case, setting + `target_type="continuous"` will specify the target as a regression + problem. The `target_type_` attribute gives the target type used by the + encoder. + + .. versionchanged:: 1.4 + Added the option 'multiclass'. + + smooth : "auto" or float, default="auto" + The amount of mixing of the target mean conditioned on the value of the + category with the global target mean. A larger `smooth` value will put + more weight on the global target mean. + If `"auto"`, then `smooth` is set to an empirical Bayes estimate. + + cv : int, default=5 + Determines the number of folds in the :term:`cross fitting` strategy used in + :meth:`fit_transform`. For classification targets, `StratifiedKFold` is used + and for continuous targets, `KFold` is used. + + shuffle : bool, default=True + Whether to shuffle the data in :meth:`fit_transform` before splitting into + folds. Note that the samples within each split will not be shuffled. + + random_state : int, RandomState instance or None, default=None + When `shuffle` is True, `random_state` affects the ordering of the + indices, which controls the randomness of each fold. Otherwise, this + parameter has no effect. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + Attributes + ---------- + encodings_ : list of shape (n_features,) or (n_features * n_classes) of \ + ndarray + Encodings learnt on all of `X`. + For feature `i`, `encodings_[i]` are the encodings matching the + categories listed in `categories_[i]`. When `target_type_` is + "multiclass", the encoding for feature `i` and class `j` is stored in + `encodings_[j + (i * len(classes_))]`. E.g., for 2 features (f) and + 3 classes (c), encodings are ordered: + f0_c0, f0_c1, f0_c2, f1_c0, f1_c1, f1_c2, + + categories_ : list of shape (n_features,) of ndarray + The categories of each input feature determined during fitting or + specified in `categories` + (in order of the features in `X` and corresponding with the output + of :meth:`transform`). + + target_type_ : str + Type of target. + + target_mean_ : float + The overall mean of the target. This value is only used in :meth:`transform` + to encode categories. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + classes_ : ndarray or None + If `target_type_` is 'binary' or 'multiclass', holds the label for each class, + otherwise `None`. + + See Also + -------- + OrdinalEncoder : Performs an ordinal (integer) encoding of the categorical features. + Contrary to TargetEncoder, this encoding is not supervised. Treating the + resulting encoding as a numerical features therefore lead arbitrarily + ordered values and therefore typically lead to lower predictive performance + when used as preprocessing for a classifier or regressor. + OneHotEncoder : Performs a one-hot encoding of categorical features. This + unsupervised encoding is better suited for low cardinality categorical + variables as it generate one new feature per unique category. + + References + ---------- + .. [MIC] :doi:`Micci-Barreca, Daniele. "A preprocessing scheme for high-cardinality + categorical attributes in classification and prediction problems" + SIGKDD Explor. Newsl. 3, 1 (July 2001), 27–32. <10.1145/507533.507538>` + + Examples + -------- + With `smooth="auto"`, the smoothing parameter is set to an empirical Bayes estimate: + + >>> import numpy as np + >>> from sklearn.preprocessing import TargetEncoder + >>> X = np.array([["dog"] * 20 + ["cat"] * 30 + ["snake"] * 38], dtype=object).T + >>> y = [90.3] * 5 + [80.1] * 15 + [20.4] * 5 + [20.1] * 25 + [21.2] * 8 + [49] * 30 + >>> enc_auto = TargetEncoder(smooth="auto") + >>> X_trans = enc_auto.fit_transform(X, y) + + >>> # A high `smooth` parameter puts more weight on global mean on the categorical + >>> # encodings: + >>> enc_high_smooth = TargetEncoder(smooth=5000.0).fit(X, y) + >>> enc_high_smooth.target_mean_ + 44... + >>> enc_high_smooth.encodings_ + [array([44..., 44..., 44...])] + + >>> # On the other hand, a low `smooth` parameter puts more weight on target + >>> # conditioned on the value of the categorical: + >>> enc_low_smooth = TargetEncoder(smooth=1.0).fit(X, y) + >>> enc_low_smooth.encodings_ + [array([20..., 80..., 43...])] + """ + + _parameter_constraints: dict = { + "categories": [StrOptions({"auto"}), list], + "target_type": [StrOptions({"auto", "continuous", "binary", "multiclass"})], + "smooth": [StrOptions({"auto"}), Interval(Real, 0, None, closed="left")], + "cv": [Interval(Integral, 2, None, closed="left")], + "shuffle": ["boolean"], + "random_state": ["random_state"], + } + + def __init__( + self, + categories="auto", + target_type="auto", + smooth="auto", + cv=5, + shuffle=True, + random_state=None, + ): + self.categories = categories + self.smooth = smooth + self.target_type = target_type + self.cv = cv + self.shuffle = shuffle + self.random_state = random_state + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y): + """Fit the :class:`TargetEncoder` to X and y. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data to determine the categories of each feature. + + y : array-like of shape (n_samples,) + The target data used to encode the categories. + + Returns + ------- + self : object + Fitted encoder. + """ + self._fit_encodings_all(X, y) + return self + + @_fit_context(prefer_skip_nested_validation=True) + def fit_transform(self, X, y): + """Fit :class:`TargetEncoder` and transform X with the target encoding. + + .. note:: + `fit(X, y).transform(X)` does not equal `fit_transform(X, y)` because a + :term:`cross fitting` scheme is used in `fit_transform` for encoding. + See the :ref:`User Guide `. for details. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data to determine the categories of each feature. + + y : array-like of shape (n_samples,) + The target data used to encode the categories. + + Returns + ------- + X_trans : ndarray of shape (n_samples, n_features) or \ + (n_samples, (n_features * n_classes)) + Transformed input. + """ + from ..model_selection import KFold, StratifiedKFold # avoid circular import + + X_ordinal, X_known_mask, y_encoded, n_categories = self._fit_encodings_all(X, y) + + # The cv splitter is voluntarily restricted to *KFold to enforce non + # overlapping validation folds, otherwise the fit_transform output will + # not be well-specified. + if self.target_type_ == "continuous": + cv = KFold(self.cv, shuffle=self.shuffle, random_state=self.random_state) + else: + cv = StratifiedKFold( + self.cv, shuffle=self.shuffle, random_state=self.random_state + ) + + # If 'multiclass' multiply axis=1 by num classes else keep shape the same + if self.target_type_ == "multiclass": + X_out = np.empty( + (X_ordinal.shape[0], X_ordinal.shape[1] * len(self.classes_)), + dtype=np.float64, + ) + else: + X_out = np.empty_like(X_ordinal, dtype=np.float64) + + for train_idx, test_idx in cv.split(X, y): + X_train, y_train = X_ordinal[train_idx, :], y_encoded[train_idx] + y_train_mean = np.mean(y_train, axis=0) + + if self.target_type_ == "multiclass": + encodings = self._fit_encoding_multiclass( + X_train, + y_train, + n_categories, + y_train_mean, + ) + else: + encodings = self._fit_encoding_binary_or_continuous( + X_train, + y_train, + n_categories, + y_train_mean, + ) + self._transform_X_ordinal( + X_out, + X_ordinal, + ~X_known_mask, + test_idx, + encodings, + y_train_mean, + ) + return X_out + + def transform(self, X): + """Transform X with the target encoding. + + .. note:: + `fit(X, y).transform(X)` does not equal `fit_transform(X, y)` because a + :term:`cross fitting` scheme is used in `fit_transform` for encoding. + See the :ref:`User Guide `. for details. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data to determine the categories of each feature. + + Returns + ------- + X_trans : ndarray of shape (n_samples, n_features) or \ + (n_samples, (n_features * n_classes)) + Transformed input. + """ + X_ordinal, X_known_mask = self._transform( + X, handle_unknown="ignore", force_all_finite="allow-nan" + ) + + # If 'multiclass' multiply axis=1 by num of classes else keep shape the same + if self.target_type_ == "multiclass": + X_out = np.empty( + (X_ordinal.shape[0], X_ordinal.shape[1] * len(self.classes_)), + dtype=np.float64, + ) + else: + X_out = np.empty_like(X_ordinal, dtype=np.float64) + + self._transform_X_ordinal( + X_out, + X_ordinal, + ~X_known_mask, + slice(None), + self.encodings_, + self.target_mean_, + ) + return X_out + + def _fit_encodings_all(self, X, y): + """Fit a target encoding with all the data.""" + # avoid circular import + from ..preprocessing import ( + LabelBinarizer, + LabelEncoder, + ) + + check_consistent_length(X, y) + self._fit(X, handle_unknown="ignore", force_all_finite="allow-nan") + + if self.target_type == "auto": + accepted_target_types = ("binary", "multiclass", "continuous") + inferred_type_of_target = type_of_target(y, input_name="y") + if inferred_type_of_target not in accepted_target_types: + raise ValueError( + "Unknown label type: Target type was inferred to be " + f"{inferred_type_of_target!r}. Only {accepted_target_types} are " + "supported." + ) + self.target_type_ = inferred_type_of_target + else: + self.target_type_ = self.target_type + + self.classes_ = None + if self.target_type_ == "binary": + label_encoder = LabelEncoder() + y = label_encoder.fit_transform(y) + self.classes_ = label_encoder.classes_ + elif self.target_type_ == "multiclass": + label_binarizer = LabelBinarizer() + y = label_binarizer.fit_transform(y) + self.classes_ = label_binarizer.classes_ + else: # continuous + y = _check_y(y, y_numeric=True, estimator=self) + + self.target_mean_ = np.mean(y, axis=0) + + X_ordinal, X_known_mask = self._transform( + X, handle_unknown="ignore", force_all_finite="allow-nan" + ) + n_categories = np.fromiter( + (len(category_for_feature) for category_for_feature in self.categories_), + dtype=np.int64, + count=len(self.categories_), + ) + if self.target_type_ == "multiclass": + encodings = self._fit_encoding_multiclass( + X_ordinal, + y, + n_categories, + self.target_mean_, + ) + else: + encodings = self._fit_encoding_binary_or_continuous( + X_ordinal, + y, + n_categories, + self.target_mean_, + ) + self.encodings_ = encodings + + return X_ordinal, X_known_mask, y, n_categories + + def _fit_encoding_binary_or_continuous( + self, X_ordinal, y, n_categories, target_mean + ): + """Learn target encodings.""" + if self.smooth == "auto": + y_variance = np.var(y) + encodings = _fit_encoding_fast_auto_smooth( + X_ordinal, + y, + n_categories, + target_mean, + y_variance, + ) + else: + encodings = _fit_encoding_fast( + X_ordinal, + y, + n_categories, + self.smooth, + target_mean, + ) + return encodings + + def _fit_encoding_multiclass(self, X_ordinal, y, n_categories, target_mean): + """Learn multiclass encodings. + + Learn encodings for each class (c) then reorder encodings such that + the same features (f) are grouped together. `reorder_index` enables + converting from: + f0_c0, f1_c0, f0_c1, f1_c1, f0_c2, f1_c2 + to: + f0_c0, f0_c1, f0_c2, f1_c0, f1_c1, f1_c2 + """ + n_features = self.n_features_in_ + n_classes = len(self.classes_) + + encodings = [] + for i in range(n_classes): + y_class = y[:, i] + encoding = self._fit_encoding_binary_or_continuous( + X_ordinal, + y_class, + n_categories, + target_mean[i], + ) + encodings.extend(encoding) + + reorder_index = ( + idx + for start in range(n_features) + for idx in range(start, (n_classes * n_features), n_features) + ) + return [encodings[idx] for idx in reorder_index] + + def _transform_X_ordinal( + self, + X_out, + X_ordinal, + X_unknown_mask, + row_indices, + encodings, + target_mean, + ): + """Transform X_ordinal using encodings. + + In the multiclass case, `X_ordinal` and `X_unknown_mask` have column + (axis=1) size `n_features`, while `encodings` has length of size + `n_features * n_classes`. `feat_idx` deals with this by repeating + feature indices by `n_classes` E.g., for 3 features, 2 classes: + 0,0,1,1,2,2 + + Additionally, `target_mean` is of shape (`n_classes`,) so `mean_idx` + cycles through 0 to `n_classes` - 1, `n_features` times. + """ + if self.target_type_ == "multiclass": + n_classes = len(self.classes_) + for e_idx, encoding in enumerate(encodings): + # Repeat feature indices by n_classes + feat_idx = e_idx // n_classes + # Cycle through each class + mean_idx = e_idx % n_classes + X_out[row_indices, e_idx] = encoding[X_ordinal[row_indices, feat_idx]] + X_out[X_unknown_mask[:, feat_idx], e_idx] = target_mean[mean_idx] + else: + for e_idx, encoding in enumerate(encodings): + X_out[row_indices, e_idx] = encoding[X_ordinal[row_indices, e_idx]] + X_out[X_unknown_mask[:, e_idx], e_idx] = target_mean + + def get_feature_names_out(self, input_features=None): + """Get output feature names for transformation. + + Parameters + ---------- + input_features : array-like of str or None, default=None + Not used, present here for API consistency by convention. + + Returns + ------- + feature_names_out : ndarray of str objects + Transformed feature names. `feature_names_in_` is used unless it is + not defined, in which case the following input feature names are + generated: `["x0", "x1", ..., "x(n_features_in_ - 1)"]`. + When `type_of_target_` is "multiclass" the names are of the format + '_'. + """ + check_is_fitted(self, "n_features_in_") + feature_names = _check_feature_names_in(self, input_features) + if self.target_type_ == "multiclass": + feature_names = [ + f"{feature_name}_{class_name}" + for feature_name in feature_names + for class_name in self.classes_ + ] + return np.asarray(feature_names, dtype=object) + else: + return feature_names + + def _more_tags(self): + return { + "requires_y": True, + } diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_target_encoder_fast.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_target_encoder_fast.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..13734c9ef32d972fbf5777bede89232bf5a5d141 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/_target_encoder_fast.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/__init__.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_data.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..24d8ab2a36c3ac5d98e8b0ac373cc185b48eb810 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_data.py @@ -0,0 +1,2593 @@ +# Authors: +# +# Giorgio Patrini +# +# License: BSD 3 clause + +import re +import warnings + +import numpy as np +import numpy.linalg as la +import pytest +from scipy import sparse, stats + +from sklearn import datasets +from sklearn.base import clone +from sklearn.exceptions import NotFittedError +from sklearn.metrics.pairwise import linear_kernel +from sklearn.model_selection import cross_val_predict +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import ( + Binarizer, + KernelCenterer, + MaxAbsScaler, + MinMaxScaler, + Normalizer, + PowerTransformer, + QuantileTransformer, + RobustScaler, + StandardScaler, + add_dummy_feature, + maxabs_scale, + minmax_scale, + normalize, + power_transform, + quantile_transform, + robust_scale, + scale, +) +from sklearn.preprocessing._data import BOUNDS_THRESHOLD, _handle_zeros_in_scale +from sklearn.svm import SVR +from sklearn.utils import gen_batches, shuffle +from sklearn.utils._array_api import ( + yield_namespace_device_dtype_combinations, +) +from sklearn.utils._testing import ( + _convert_container, + assert_allclose, + assert_allclose_dense_sparse, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, + assert_array_less, + skip_if_32bit, +) +from sklearn.utils.estimator_checks import ( + _get_check_estimator_ids, + check_array_api_input_and_values, +) +from sklearn.utils.fixes import ( + COO_CONTAINERS, + CSC_CONTAINERS, + CSR_CONTAINERS, + LIL_CONTAINERS, +) +from sklearn.utils.sparsefuncs import mean_variance_axis + +iris = datasets.load_iris() + +# Make some data to be used many times +rng = np.random.RandomState(0) +n_features = 30 +n_samples = 1000 +offsets = rng.uniform(-1, 1, size=n_features) +scales = rng.uniform(1, 10, size=n_features) +X_2d = rng.randn(n_samples, n_features) * scales + offsets +X_1row = X_2d[0, :].reshape(1, n_features) +X_1col = X_2d[:, 0].reshape(n_samples, 1) +X_list_1row = X_1row.tolist() +X_list_1col = X_1col.tolist() + + +def toarray(a): + if hasattr(a, "toarray"): + a = a.toarray() + return a + + +def _check_dim_1axis(a): + return np.asarray(a).shape[0] + + +def assert_correct_incr(i, batch_start, batch_stop, n, chunk_size, n_samples_seen): + if batch_stop != n: + assert (i + 1) * chunk_size == n_samples_seen + else: + assert i * chunk_size + (batch_stop - batch_start) == n_samples_seen + + +def test_raises_value_error_if_sample_weights_greater_than_1d(): + # Sample weights must be either scalar or 1D + + n_sampless = [2, 3] + n_featuress = [3, 2] + + for n_samples, n_features in zip(n_sampless, n_featuress): + X = rng.randn(n_samples, n_features) + y = rng.randn(n_samples) + + scaler = StandardScaler() + + # make sure Error is raised the sample weights greater than 1d + sample_weight_notOK = rng.randn(n_samples, 1) ** 2 + with pytest.raises(ValueError): + scaler.fit(X, y, sample_weight=sample_weight_notOK) + + +@pytest.mark.parametrize( + ["Xw", "X", "sample_weight"], + [ + ([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [1, 2, 3], [4, 5, 6]], [2.0, 1.0]), + ( + [[1, 0, 1], [0, 0, 1]], + [[1, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]], + np.array([1, 3]), + ), + ( + [[1, np.nan, 1], [np.nan, np.nan, 1]], + [ + [1, np.nan, 1], + [np.nan, np.nan, 1], + [np.nan, np.nan, 1], + [np.nan, np.nan, 1], + ], + np.array([1, 3]), + ), + ], +) +@pytest.mark.parametrize("array_constructor", ["array", "sparse_csr", "sparse_csc"]) +def test_standard_scaler_sample_weight(Xw, X, sample_weight, array_constructor): + with_mean = not array_constructor.startswith("sparse") + X = _convert_container(X, array_constructor) + Xw = _convert_container(Xw, array_constructor) + + # weighted StandardScaler + yw = np.ones(Xw.shape[0]) + scaler_w = StandardScaler(with_mean=with_mean) + scaler_w.fit(Xw, yw, sample_weight=sample_weight) + + # unweighted, but with repeated samples + y = np.ones(X.shape[0]) + scaler = StandardScaler(with_mean=with_mean) + scaler.fit(X, y) + + X_test = [[1.5, 2.5, 3.5], [3.5, 4.5, 5.5]] + + assert_almost_equal(scaler.mean_, scaler_w.mean_) + assert_almost_equal(scaler.var_, scaler_w.var_) + assert_almost_equal(scaler.transform(X_test), scaler_w.transform(X_test)) + + +def test_standard_scaler_1d(): + # Test scaling of dataset along single axis + for X in [X_1row, X_1col, X_list_1row, X_list_1row]: + scaler = StandardScaler() + X_scaled = scaler.fit(X).transform(X, copy=True) + + if isinstance(X, list): + X = np.array(X) # cast only after scaling done + + if _check_dim_1axis(X) == 1: + assert_almost_equal(scaler.mean_, X.ravel()) + assert_almost_equal(scaler.scale_, np.ones(n_features)) + assert_array_almost_equal(X_scaled.mean(axis=0), np.zeros_like(n_features)) + assert_array_almost_equal(X_scaled.std(axis=0), np.zeros_like(n_features)) + else: + assert_almost_equal(scaler.mean_, X.mean()) + assert_almost_equal(scaler.scale_, X.std()) + assert_array_almost_equal(X_scaled.mean(axis=0), np.zeros_like(n_features)) + assert_array_almost_equal(X_scaled.mean(axis=0), 0.0) + assert_array_almost_equal(X_scaled.std(axis=0), 1.0) + assert scaler.n_samples_seen_ == X.shape[0] + + # check inverse transform + X_scaled_back = scaler.inverse_transform(X_scaled) + assert_array_almost_equal(X_scaled_back, X) + + # Constant feature + X = np.ones((5, 1)) + scaler = StandardScaler() + X_scaled = scaler.fit(X).transform(X, copy=True) + assert_almost_equal(scaler.mean_, 1.0) + assert_almost_equal(scaler.scale_, 1.0) + assert_array_almost_equal(X_scaled.mean(axis=0), 0.0) + assert_array_almost_equal(X_scaled.std(axis=0), 0.0) + assert scaler.n_samples_seen_ == X.shape[0] + + +@pytest.mark.parametrize("sparse_container", [None] + CSC_CONTAINERS + CSR_CONTAINERS) +@pytest.mark.parametrize("add_sample_weight", [False, True]) +def test_standard_scaler_dtype(add_sample_weight, sparse_container): + # Ensure scaling does not affect dtype + rng = np.random.RandomState(0) + n_samples = 10 + n_features = 3 + if add_sample_weight: + sample_weight = np.ones(n_samples) + else: + sample_weight = None + with_mean = True + if sparse_container is not None: + # scipy sparse containers do not support float16, see + # https://github.com/scipy/scipy/issues/7408 for more details. + supported_dtype = [np.float64, np.float32] + else: + supported_dtype = [np.float64, np.float32, np.float16] + for dtype in supported_dtype: + X = rng.randn(n_samples, n_features).astype(dtype) + if sparse_container is not None: + X = sparse_container(X) + with_mean = False + + scaler = StandardScaler(with_mean=with_mean) + X_scaled = scaler.fit(X, sample_weight=sample_weight).transform(X) + assert X.dtype == X_scaled.dtype + assert scaler.mean_.dtype == np.float64 + assert scaler.scale_.dtype == np.float64 + + +@pytest.mark.parametrize( + "scaler", + [ + StandardScaler(with_mean=False), + RobustScaler(with_centering=False), + ], +) +@pytest.mark.parametrize("sparse_container", [None] + CSC_CONTAINERS + CSR_CONTAINERS) +@pytest.mark.parametrize("add_sample_weight", [False, True]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("constant", [0, 1.0, 100.0]) +def test_standard_scaler_constant_features( + scaler, add_sample_weight, sparse_container, dtype, constant +): + if isinstance(scaler, RobustScaler) and add_sample_weight: + pytest.skip(f"{scaler.__class__.__name__} does not yet support sample_weight") + + rng = np.random.RandomState(0) + n_samples = 100 + n_features = 1 + if add_sample_weight: + fit_params = dict(sample_weight=rng.uniform(size=n_samples) * 2) + else: + fit_params = {} + X_array = np.full(shape=(n_samples, n_features), fill_value=constant, dtype=dtype) + X = X_array if sparse_container is None else sparse_container(X_array) + X_scaled = scaler.fit(X, **fit_params).transform(X) + + if isinstance(scaler, StandardScaler): + # The variance info should be close to zero for constant features. + assert_allclose(scaler.var_, np.zeros(X.shape[1]), atol=1e-7) + + # Constant features should not be scaled (scale of 1.): + assert_allclose(scaler.scale_, np.ones(X.shape[1])) + + assert X_scaled is not X # make sure we make a copy + assert_allclose_dense_sparse(X_scaled, X) + + if isinstance(scaler, StandardScaler) and not add_sample_weight: + # Also check consistency with the standard scale function. + X_scaled_2 = scale(X, with_mean=scaler.with_mean) + assert X_scaled_2 is not X # make sure we did a copy + assert_allclose_dense_sparse(X_scaled_2, X) + + +@pytest.mark.parametrize("n_samples", [10, 100, 10_000]) +@pytest.mark.parametrize("average", [1e-10, 1, 1e10]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("sparse_container", [None] + CSC_CONTAINERS + CSR_CONTAINERS) +def test_standard_scaler_near_constant_features( + n_samples, sparse_container, average, dtype +): + # Check that when the variance is too small (var << mean**2) the feature + # is considered constant and not scaled. + + scale_min, scale_max = -30, 19 + scales = np.array([10**i for i in range(scale_min, scale_max + 1)], dtype=dtype) + + n_features = scales.shape[0] + X = np.empty((n_samples, n_features), dtype=dtype) + # Make a dataset of known var = scales**2 and mean = average + X[: n_samples // 2, :] = average + scales + X[n_samples // 2 :, :] = average - scales + X_array = X if sparse_container is None else sparse_container(X) + + scaler = StandardScaler(with_mean=False).fit(X_array) + + # StandardScaler uses float64 accumulators even if the data has a float32 + # dtype. + eps = np.finfo(np.float64).eps + + # if var < bound = N.eps.var + N².eps².mean², the feature is considered + # constant and the scale_ attribute is set to 1. + bounds = n_samples * eps * scales**2 + n_samples**2 * eps**2 * average**2 + within_bounds = scales**2 <= bounds + + # Check that scale_min is small enough to have some scales below the + # bound and therefore detected as constant: + assert np.any(within_bounds) + + # Check that such features are actually treated as constant by the scaler: + assert all(scaler.var_[within_bounds] <= bounds[within_bounds]) + assert_allclose(scaler.scale_[within_bounds], 1.0) + + # Depending the on the dtype of X, some features might not actually be + # representable as non constant for small scales (even if above the + # precision bound of the float64 variance estimate). Such feature should + # be correctly detected as constants with 0 variance by StandardScaler. + representable_diff = X[0, :] - X[-1, :] != 0 + assert_allclose(scaler.var_[np.logical_not(representable_diff)], 0) + assert_allclose(scaler.scale_[np.logical_not(representable_diff)], 1) + + # The other features are scaled and scale_ is equal to sqrt(var_) assuming + # that scales are large enough for average + scale and average - scale to + # be distinct in X (depending on X's dtype). + common_mask = np.logical_and(scales**2 > bounds, representable_diff) + assert_allclose(scaler.scale_[common_mask], np.sqrt(scaler.var_)[common_mask]) + + +def test_scale_1d(): + # 1-d inputs + X_list = [1.0, 3.0, 5.0, 0.0] + X_arr = np.array(X_list) + + for X in [X_list, X_arr]: + X_scaled = scale(X) + assert_array_almost_equal(X_scaled.mean(), 0.0) + assert_array_almost_equal(X_scaled.std(), 1.0) + assert_array_equal(scale(X, with_mean=False, with_std=False), X) + + +@skip_if_32bit +def test_standard_scaler_numerical_stability(): + # Test numerical stability of scaling + # np.log(1e-5) is taken because of its floating point representation + # was empirically found to cause numerical problems with np.mean & np.std. + x = np.full(8, np.log(1e-5), dtype=np.float64) + # This does not raise a warning as the number of samples is too low + # to trigger the problem in recent numpy + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + scale(x) + assert_array_almost_equal(scale(x), np.zeros(8)) + + # with 2 more samples, the std computation run into numerical issues: + x = np.full(10, np.log(1e-5), dtype=np.float64) + warning_message = "standard deviation of the data is probably very close to 0" + with pytest.warns(UserWarning, match=warning_message): + x_scaled = scale(x) + assert_array_almost_equal(x_scaled, np.zeros(10)) + + x = np.full(10, 1e-100, dtype=np.float64) + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + x_small_scaled = scale(x) + assert_array_almost_equal(x_small_scaled, np.zeros(10)) + + # Large values can cause (often recoverable) numerical stability issues: + x_big = np.full(10, 1e100, dtype=np.float64) + warning_message = "Dataset may contain too large values" + with pytest.warns(UserWarning, match=warning_message): + x_big_scaled = scale(x_big) + assert_array_almost_equal(x_big_scaled, np.zeros(10)) + assert_array_almost_equal(x_big_scaled, x_small_scaled) + with pytest.warns(UserWarning, match=warning_message): + x_big_centered = scale(x_big, with_std=False) + assert_array_almost_equal(x_big_centered, np.zeros(10)) + assert_array_almost_equal(x_big_centered, x_small_scaled) + + +def test_scaler_2d_arrays(): + # Test scaling of 2d array along first axis + rng = np.random.RandomState(0) + n_features = 5 + n_samples = 4 + X = rng.randn(n_samples, n_features) + X[:, 0] = 0.0 # first feature is always of zero + + scaler = StandardScaler() + X_scaled = scaler.fit(X).transform(X, copy=True) + assert not np.any(np.isnan(X_scaled)) + assert scaler.n_samples_seen_ == n_samples + + assert_array_almost_equal(X_scaled.mean(axis=0), n_features * [0.0]) + assert_array_almost_equal(X_scaled.std(axis=0), [0.0, 1.0, 1.0, 1.0, 1.0]) + # Check that X has been copied + assert X_scaled is not X + + # check inverse transform + X_scaled_back = scaler.inverse_transform(X_scaled) + assert X_scaled_back is not X + assert X_scaled_back is not X_scaled + assert_array_almost_equal(X_scaled_back, X) + + X_scaled = scale(X, axis=1, with_std=False) + assert not np.any(np.isnan(X_scaled)) + assert_array_almost_equal(X_scaled.mean(axis=1), n_samples * [0.0]) + X_scaled = scale(X, axis=1, with_std=True) + assert not np.any(np.isnan(X_scaled)) + assert_array_almost_equal(X_scaled.mean(axis=1), n_samples * [0.0]) + assert_array_almost_equal(X_scaled.std(axis=1), n_samples * [1.0]) + # Check that the data hasn't been modified + assert X_scaled is not X + + X_scaled = scaler.fit(X).transform(X, copy=False) + assert not np.any(np.isnan(X_scaled)) + assert_array_almost_equal(X_scaled.mean(axis=0), n_features * [0.0]) + assert_array_almost_equal(X_scaled.std(axis=0), [0.0, 1.0, 1.0, 1.0, 1.0]) + # Check that X has not been copied + assert X_scaled is X + + X = rng.randn(4, 5) + X[:, 0] = 1.0 # first feature is a constant, non zero feature + scaler = StandardScaler() + X_scaled = scaler.fit(X).transform(X, copy=True) + assert not np.any(np.isnan(X_scaled)) + assert_array_almost_equal(X_scaled.mean(axis=0), n_features * [0.0]) + assert_array_almost_equal(X_scaled.std(axis=0), [0.0, 1.0, 1.0, 1.0, 1.0]) + # Check that X has not been copied + assert X_scaled is not X + + +def test_scaler_float16_overflow(): + # Test if the scaler will not overflow on float16 numpy arrays + rng = np.random.RandomState(0) + # float16 has a maximum of 65500.0. On the worst case 5 * 200000 is 100000 + # which is enough to overflow the data type + X = rng.uniform(5, 10, [200000, 1]).astype(np.float16) + + with np.errstate(over="raise"): + scaler = StandardScaler().fit(X) + X_scaled = scaler.transform(X) + + # Calculate the float64 equivalent to verify result + X_scaled_f64 = StandardScaler().fit_transform(X.astype(np.float64)) + + # Overflow calculations may cause -inf, inf, or nan. Since there is no nan + # input, all of the outputs should be finite. This may be redundant since a + # FloatingPointError exception will be thrown on overflow above. + assert np.all(np.isfinite(X_scaled)) + + # The normal distribution is very unlikely to go above 4. At 4.0-8.0 the + # float16 precision is 2^-8 which is around 0.004. Thus only 2 decimals are + # checked to account for precision differences. + assert_array_almost_equal(X_scaled, X_scaled_f64, decimal=2) + + +def test_handle_zeros_in_scale(): + s1 = np.array([0, 1e-16, 1, 2, 3]) + s2 = _handle_zeros_in_scale(s1, copy=True) + + assert_allclose(s1, np.array([0, 1e-16, 1, 2, 3])) + assert_allclose(s2, np.array([1, 1, 1, 2, 3])) + + +def test_minmax_scaler_partial_fit(): + # Test if partial_fit run over many batches of size 1 and 50 + # gives the same results as fit + X = X_2d + n = X.shape[0] + + for chunk_size in [1, 2, 50, n, n + 42]: + # Test mean at the end of the process + scaler_batch = MinMaxScaler().fit(X) + + scaler_incr = MinMaxScaler() + for batch in gen_batches(n_samples, chunk_size): + scaler_incr = scaler_incr.partial_fit(X[batch]) + + assert_array_almost_equal(scaler_batch.data_min_, scaler_incr.data_min_) + assert_array_almost_equal(scaler_batch.data_max_, scaler_incr.data_max_) + assert scaler_batch.n_samples_seen_ == scaler_incr.n_samples_seen_ + assert_array_almost_equal(scaler_batch.data_range_, scaler_incr.data_range_) + assert_array_almost_equal(scaler_batch.scale_, scaler_incr.scale_) + assert_array_almost_equal(scaler_batch.min_, scaler_incr.min_) + + # Test std after 1 step + batch0 = slice(0, chunk_size) + scaler_batch = MinMaxScaler().fit(X[batch0]) + scaler_incr = MinMaxScaler().partial_fit(X[batch0]) + + assert_array_almost_equal(scaler_batch.data_min_, scaler_incr.data_min_) + assert_array_almost_equal(scaler_batch.data_max_, scaler_incr.data_max_) + assert scaler_batch.n_samples_seen_ == scaler_incr.n_samples_seen_ + assert_array_almost_equal(scaler_batch.data_range_, scaler_incr.data_range_) + assert_array_almost_equal(scaler_batch.scale_, scaler_incr.scale_) + assert_array_almost_equal(scaler_batch.min_, scaler_incr.min_) + + # Test std until the end of partial fits, and + scaler_batch = MinMaxScaler().fit(X) + scaler_incr = MinMaxScaler() # Clean estimator + for i, batch in enumerate(gen_batches(n_samples, chunk_size)): + scaler_incr = scaler_incr.partial_fit(X[batch]) + assert_correct_incr( + i, + batch_start=batch.start, + batch_stop=batch.stop, + n=n, + chunk_size=chunk_size, + n_samples_seen=scaler_incr.n_samples_seen_, + ) + + +def test_standard_scaler_partial_fit(): + # Test if partial_fit run over many batches of size 1 and 50 + # gives the same results as fit + X = X_2d + n = X.shape[0] + + for chunk_size in [1, 2, 50, n, n + 42]: + # Test mean at the end of the process + scaler_batch = StandardScaler(with_std=False).fit(X) + + scaler_incr = StandardScaler(with_std=False) + for batch in gen_batches(n_samples, chunk_size): + scaler_incr = scaler_incr.partial_fit(X[batch]) + assert_array_almost_equal(scaler_batch.mean_, scaler_incr.mean_) + assert scaler_batch.var_ == scaler_incr.var_ # Nones + assert scaler_batch.n_samples_seen_ == scaler_incr.n_samples_seen_ + + # Test std after 1 step + batch0 = slice(0, chunk_size) + scaler_incr = StandardScaler().partial_fit(X[batch0]) + if chunk_size == 1: + assert_array_almost_equal( + np.zeros(n_features, dtype=np.float64), scaler_incr.var_ + ) + assert_array_almost_equal( + np.ones(n_features, dtype=np.float64), scaler_incr.scale_ + ) + else: + assert_array_almost_equal(np.var(X[batch0], axis=0), scaler_incr.var_) + assert_array_almost_equal( + np.std(X[batch0], axis=0), scaler_incr.scale_ + ) # no constants + + # Test std until the end of partial fits, and + scaler_batch = StandardScaler().fit(X) + scaler_incr = StandardScaler() # Clean estimator + for i, batch in enumerate(gen_batches(n_samples, chunk_size)): + scaler_incr = scaler_incr.partial_fit(X[batch]) + assert_correct_incr( + i, + batch_start=batch.start, + batch_stop=batch.stop, + n=n, + chunk_size=chunk_size, + n_samples_seen=scaler_incr.n_samples_seen_, + ) + + assert_array_almost_equal(scaler_batch.var_, scaler_incr.var_) + assert scaler_batch.n_samples_seen_ == scaler_incr.n_samples_seen_ + + +@pytest.mark.parametrize("sparse_container", CSC_CONTAINERS + CSR_CONTAINERS) +def test_standard_scaler_partial_fit_numerical_stability(sparse_container): + # Test if the incremental computation introduces significative errors + # for large datasets with values of large magniture + rng = np.random.RandomState(0) + n_features = 2 + n_samples = 100 + offsets = rng.uniform(-1e15, 1e15, size=n_features) + scales = rng.uniform(1e3, 1e6, size=n_features) + X = rng.randn(n_samples, n_features) * scales + offsets + + scaler_batch = StandardScaler().fit(X) + scaler_incr = StandardScaler() + for chunk in X: + scaler_incr = scaler_incr.partial_fit(chunk.reshape(1, n_features)) + + # Regardless of abs values, they must not be more diff 6 significant digits + tol = 10 ** (-6) + assert_allclose(scaler_incr.mean_, scaler_batch.mean_, rtol=tol) + assert_allclose(scaler_incr.var_, scaler_batch.var_, rtol=tol) + assert_allclose(scaler_incr.scale_, scaler_batch.scale_, rtol=tol) + # NOTE Be aware that for much larger offsets std is very unstable (last + # assert) while mean is OK. + + # Sparse input + size = (100, 3) + scale = 1e20 + X = sparse_container(rng.randint(0, 2, size).astype(np.float64) * scale) + + # with_mean=False is required with sparse input + scaler = StandardScaler(with_mean=False).fit(X) + scaler_incr = StandardScaler(with_mean=False) + + for chunk in X: + scaler_incr = scaler_incr.partial_fit(chunk) + + # Regardless of magnitude, they must not differ more than of 6 digits + tol = 10 ** (-6) + assert scaler.mean_ is not None + assert_allclose(scaler_incr.var_, scaler.var_, rtol=tol) + assert_allclose(scaler_incr.scale_, scaler.scale_, rtol=tol) + + +@pytest.mark.parametrize("sample_weight", [True, None]) +@pytest.mark.parametrize("sparse_container", CSC_CONTAINERS + CSR_CONTAINERS) +def test_partial_fit_sparse_input(sample_weight, sparse_container): + # Check that sparsity is not destroyed + X = sparse_container(np.array([[1.0], [0.0], [0.0], [5.0]])) + + if sample_weight: + sample_weight = rng.rand(X.shape[0]) + + null_transform = StandardScaler(with_mean=False, with_std=False, copy=True) + X_null = null_transform.partial_fit(X, sample_weight=sample_weight).transform(X) + assert_array_equal(X_null.toarray(), X.toarray()) + X_orig = null_transform.inverse_transform(X_null) + assert_array_equal(X_orig.toarray(), X_null.toarray()) + assert_array_equal(X_orig.toarray(), X.toarray()) + + +@pytest.mark.parametrize("sample_weight", [True, None]) +def test_standard_scaler_trasform_with_partial_fit(sample_weight): + # Check some postconditions after applying partial_fit and transform + X = X_2d[:100, :] + + if sample_weight: + sample_weight = rng.rand(X.shape[0]) + + scaler_incr = StandardScaler() + for i, batch in enumerate(gen_batches(X.shape[0], 1)): + X_sofar = X[: (i + 1), :] + chunks_copy = X_sofar.copy() + if sample_weight is None: + scaled_batch = StandardScaler().fit_transform(X_sofar) + scaler_incr = scaler_incr.partial_fit(X[batch]) + else: + scaled_batch = StandardScaler().fit_transform( + X_sofar, sample_weight=sample_weight[: i + 1] + ) + scaler_incr = scaler_incr.partial_fit( + X[batch], sample_weight=sample_weight[batch] + ) + scaled_incr = scaler_incr.transform(X_sofar) + + assert_array_almost_equal(scaled_batch, scaled_incr) + assert_array_almost_equal(X_sofar, chunks_copy) # No change + right_input = scaler_incr.inverse_transform(scaled_incr) + assert_array_almost_equal(X_sofar, right_input) + + zero = np.zeros(X.shape[1]) + epsilon = np.finfo(float).eps + assert_array_less(zero, scaler_incr.var_ + epsilon) # as less or equal + assert_array_less(zero, scaler_incr.scale_ + epsilon) + if sample_weight is None: + # (i+1) because the Scaler has been already fitted + assert (i + 1) == scaler_incr.n_samples_seen_ + else: + assert np.sum(sample_weight[: i + 1]) == pytest.approx( + scaler_incr.n_samples_seen_ + ) + + +def test_standard_check_array_of_inverse_transform(): + # Check if StandardScaler inverse_transform is + # converting the integer array to float + x = np.array( + [ + [1, 1, 1, 0, 1, 0], + [1, 1, 1, 0, 1, 0], + [0, 8, 0, 1, 0, 0], + [1, 4, 1, 1, 0, 0], + [0, 1, 0, 0, 1, 0], + [0, 4, 0, 1, 0, 1], + ], + dtype=np.int32, + ) + + scaler = StandardScaler() + scaler.fit(x) + + # The of inverse_transform should be converted + # to a float array. + # If not X *= self.scale_ will fail. + scaler.inverse_transform(x) + + +@pytest.mark.parametrize( + "array_namespace, device, dtype_name", yield_namespace_device_dtype_combinations() +) +@pytest.mark.parametrize( + "check", + [check_array_api_input_and_values], + ids=_get_check_estimator_ids, +) +@pytest.mark.parametrize( + "estimator", + [ + MaxAbsScaler(), + MinMaxScaler(), + KernelCenterer(), + Normalizer(norm="l1"), + Normalizer(norm="l2"), + Normalizer(norm="max"), + ], + ids=_get_check_estimator_ids, +) +def test_scaler_array_api_compliance( + estimator, check, array_namespace, device, dtype_name +): + name = estimator.__class__.__name__ + check(name, estimator, array_namespace, device=device, dtype_name=dtype_name) + + +def test_min_max_scaler_iris(): + X = iris.data + scaler = MinMaxScaler() + # default params + X_trans = scaler.fit_transform(X) + assert_array_almost_equal(X_trans.min(axis=0), 0) + assert_array_almost_equal(X_trans.max(axis=0), 1) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + + # not default params: min=1, max=2 + scaler = MinMaxScaler(feature_range=(1, 2)) + X_trans = scaler.fit_transform(X) + assert_array_almost_equal(X_trans.min(axis=0), 1) + assert_array_almost_equal(X_trans.max(axis=0), 2) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + + # min=-.5, max=.6 + scaler = MinMaxScaler(feature_range=(-0.5, 0.6)) + X_trans = scaler.fit_transform(X) + assert_array_almost_equal(X_trans.min(axis=0), -0.5) + assert_array_almost_equal(X_trans.max(axis=0), 0.6) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + + # raises on invalid range + scaler = MinMaxScaler(feature_range=(2, 1)) + with pytest.raises(ValueError): + scaler.fit(X) + + +def test_min_max_scaler_zero_variance_features(): + # Check min max scaler on toy data with zero variance features + X = [[0.0, 1.0, +0.5], [0.0, 1.0, -0.1], [0.0, 1.0, +1.1]] + + X_new = [[+0.0, 2.0, 0.5], [-1.0, 1.0, 0.0], [+0.0, 1.0, 1.5]] + + # default params + scaler = MinMaxScaler() + X_trans = scaler.fit_transform(X) + X_expected_0_1 = [[0.0, 0.0, 0.5], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]] + assert_array_almost_equal(X_trans, X_expected_0_1) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + + X_trans_new = scaler.transform(X_new) + X_expected_0_1_new = [[+0.0, 1.0, 0.500], [-1.0, 0.0, 0.083], [+0.0, 0.0, 1.333]] + assert_array_almost_equal(X_trans_new, X_expected_0_1_new, decimal=2) + + # not default params + scaler = MinMaxScaler(feature_range=(1, 2)) + X_trans = scaler.fit_transform(X) + X_expected_1_2 = [[1.0, 1.0, 1.5], [1.0, 1.0, 1.0], [1.0, 1.0, 2.0]] + assert_array_almost_equal(X_trans, X_expected_1_2) + + # function interface + X_trans = minmax_scale(X) + assert_array_almost_equal(X_trans, X_expected_0_1) + X_trans = minmax_scale(X, feature_range=(1, 2)) + assert_array_almost_equal(X_trans, X_expected_1_2) + + +def test_minmax_scale_axis1(): + X = iris.data + X_trans = minmax_scale(X, axis=1) + assert_array_almost_equal(np.min(X_trans, axis=1), 0) + assert_array_almost_equal(np.max(X_trans, axis=1), 1) + + +def test_min_max_scaler_1d(): + # Test scaling of dataset along single axis + for X in [X_1row, X_1col, X_list_1row, X_list_1row]: + scaler = MinMaxScaler(copy=True) + X_scaled = scaler.fit(X).transform(X) + + if isinstance(X, list): + X = np.array(X) # cast only after scaling done + + if _check_dim_1axis(X) == 1: + assert_array_almost_equal(X_scaled.min(axis=0), np.zeros(n_features)) + assert_array_almost_equal(X_scaled.max(axis=0), np.zeros(n_features)) + else: + assert_array_almost_equal(X_scaled.min(axis=0), 0.0) + assert_array_almost_equal(X_scaled.max(axis=0), 1.0) + assert scaler.n_samples_seen_ == X.shape[0] + + # check inverse transform + X_scaled_back = scaler.inverse_transform(X_scaled) + assert_array_almost_equal(X_scaled_back, X) + + # Constant feature + X = np.ones((5, 1)) + scaler = MinMaxScaler() + X_scaled = scaler.fit(X).transform(X) + assert X_scaled.min() >= 0.0 + assert X_scaled.max() <= 1.0 + assert scaler.n_samples_seen_ == X.shape[0] + + # Function interface + X_1d = X_1row.ravel() + min_ = X_1d.min() + max_ = X_1d.max() + assert_array_almost_equal( + (X_1d - min_) / (max_ - min_), minmax_scale(X_1d, copy=True) + ) + + +@pytest.mark.parametrize("sample_weight", [True, None]) +@pytest.mark.parametrize("sparse_container", CSC_CONTAINERS + CSR_CONTAINERS) +def test_scaler_without_centering(sample_weight, sparse_container): + rng = np.random.RandomState(42) + X = rng.randn(4, 5) + X[:, 0] = 0.0 # first feature is always of zero + X_sparse = sparse_container(X) + + if sample_weight: + sample_weight = rng.rand(X.shape[0]) + + with pytest.raises(ValueError): + StandardScaler().fit(X_sparse) + + scaler = StandardScaler(with_mean=False).fit(X, sample_weight=sample_weight) + X_scaled = scaler.transform(X, copy=True) + assert not np.any(np.isnan(X_scaled)) + + scaler_sparse = StandardScaler(with_mean=False).fit( + X_sparse, sample_weight=sample_weight + ) + X_sparse_scaled = scaler_sparse.transform(X_sparse, copy=True) + assert not np.any(np.isnan(X_sparse_scaled.data)) + + assert_array_almost_equal(scaler.mean_, scaler_sparse.mean_) + assert_array_almost_equal(scaler.var_, scaler_sparse.var_) + assert_array_almost_equal(scaler.scale_, scaler_sparse.scale_) + assert_array_almost_equal(scaler.n_samples_seen_, scaler_sparse.n_samples_seen_) + + if sample_weight is None: + assert_array_almost_equal( + X_scaled.mean(axis=0), [0.0, -0.01, 2.24, -0.35, -0.78], 2 + ) + assert_array_almost_equal(X_scaled.std(axis=0), [0.0, 1.0, 1.0, 1.0, 1.0]) + + X_sparse_scaled_mean, X_sparse_scaled_var = mean_variance_axis(X_sparse_scaled, 0) + assert_array_almost_equal(X_sparse_scaled_mean, X_scaled.mean(axis=0)) + assert_array_almost_equal(X_sparse_scaled_var, X_scaled.var(axis=0)) + + # Check that X has not been modified (copy) + assert X_scaled is not X + assert X_sparse_scaled is not X_sparse + + X_scaled_back = scaler.inverse_transform(X_scaled) + assert X_scaled_back is not X + assert X_scaled_back is not X_scaled + assert_array_almost_equal(X_scaled_back, X) + + X_sparse_scaled_back = scaler_sparse.inverse_transform(X_sparse_scaled) + assert X_sparse_scaled_back is not X_sparse + assert X_sparse_scaled_back is not X_sparse_scaled + assert_array_almost_equal(X_sparse_scaled_back.toarray(), X) + + if sparse_container in CSR_CONTAINERS: + null_transform = StandardScaler(with_mean=False, with_std=False, copy=True) + X_null = null_transform.fit_transform(X_sparse) + assert_array_equal(X_null.data, X_sparse.data) + X_orig = null_transform.inverse_transform(X_null) + assert_array_equal(X_orig.data, X_sparse.data) + + +@pytest.mark.parametrize("with_mean", [True, False]) +@pytest.mark.parametrize("with_std", [True, False]) +@pytest.mark.parametrize("sparse_container", [None] + CSC_CONTAINERS + CSR_CONTAINERS) +def test_scaler_n_samples_seen_with_nan(with_mean, with_std, sparse_container): + X = np.array( + [[0, 1, 3], [np.nan, 6, 10], [5, 4, np.nan], [8, 0, np.nan]], dtype=np.float64 + ) + if sparse_container is not None: + X = sparse_container(X) + + if sparse.issparse(X) and with_mean: + pytest.skip("'with_mean=True' cannot be used with sparse matrix.") + + transformer = StandardScaler(with_mean=with_mean, with_std=with_std) + transformer.fit(X) + + assert_array_equal(transformer.n_samples_seen_, np.array([3, 4, 2])) + + +def _check_identity_scalers_attributes(scaler_1, scaler_2): + assert scaler_1.mean_ is scaler_2.mean_ is None + assert scaler_1.var_ is scaler_2.var_ is None + assert scaler_1.scale_ is scaler_2.scale_ is None + assert scaler_1.n_samples_seen_ == scaler_2.n_samples_seen_ + + +@pytest.mark.parametrize("sparse_container", CSC_CONTAINERS + CSR_CONTAINERS) +def test_scaler_return_identity(sparse_container): + # test that the scaler return identity when with_mean and with_std are + # False + X_dense = np.array([[0, 1, 3], [5, 6, 0], [8, 0, 10]], dtype=np.float64) + X_sparse = sparse_container(X_dense) + + transformer_dense = StandardScaler(with_mean=False, with_std=False) + X_trans_dense = transformer_dense.fit_transform(X_dense) + assert_allclose(X_trans_dense, X_dense) + + transformer_sparse = clone(transformer_dense) + X_trans_sparse = transformer_sparse.fit_transform(X_sparse) + assert_allclose_dense_sparse(X_trans_sparse, X_sparse) + + _check_identity_scalers_attributes(transformer_dense, transformer_sparse) + + transformer_dense.partial_fit(X_dense) + transformer_sparse.partial_fit(X_sparse) + _check_identity_scalers_attributes(transformer_dense, transformer_sparse) + + transformer_dense.fit(X_dense) + transformer_sparse.fit(X_sparse) + _check_identity_scalers_attributes(transformer_dense, transformer_sparse) + + +@pytest.mark.parametrize("sparse_container", CSC_CONTAINERS + CSR_CONTAINERS) +def test_scaler_int(sparse_container): + # test that scaler converts integer input to floating + # for both sparse and dense matrices + rng = np.random.RandomState(42) + X = rng.randint(20, size=(4, 5)) + X[:, 0] = 0 # first feature is always of zero + X_sparse = sparse_container(X) + + with warnings.catch_warnings(record=True): + scaler = StandardScaler(with_mean=False).fit(X) + X_scaled = scaler.transform(X, copy=True) + assert not np.any(np.isnan(X_scaled)) + + with warnings.catch_warnings(record=True): + scaler_sparse = StandardScaler(with_mean=False).fit(X_sparse) + X_sparse_scaled = scaler_sparse.transform(X_sparse, copy=True) + assert not np.any(np.isnan(X_sparse_scaled.data)) + + assert_array_almost_equal(scaler.mean_, scaler_sparse.mean_) + assert_array_almost_equal(scaler.var_, scaler_sparse.var_) + assert_array_almost_equal(scaler.scale_, scaler_sparse.scale_) + + assert_array_almost_equal( + X_scaled.mean(axis=0), [0.0, 1.109, 1.856, 21.0, 1.559], 2 + ) + assert_array_almost_equal(X_scaled.std(axis=0), [0.0, 1.0, 1.0, 1.0, 1.0]) + + X_sparse_scaled_mean, X_sparse_scaled_std = mean_variance_axis( + X_sparse_scaled.astype(float), 0 + ) + assert_array_almost_equal(X_sparse_scaled_mean, X_scaled.mean(axis=0)) + assert_array_almost_equal(X_sparse_scaled_std, X_scaled.std(axis=0)) + + # Check that X has not been modified (copy) + assert X_scaled is not X + assert X_sparse_scaled is not X_sparse + + X_scaled_back = scaler.inverse_transform(X_scaled) + assert X_scaled_back is not X + assert X_scaled_back is not X_scaled + assert_array_almost_equal(X_scaled_back, X) + + X_sparse_scaled_back = scaler_sparse.inverse_transform(X_sparse_scaled) + assert X_sparse_scaled_back is not X_sparse + assert X_sparse_scaled_back is not X_sparse_scaled + assert_array_almost_equal(X_sparse_scaled_back.toarray(), X) + + if sparse_container in CSR_CONTAINERS: + null_transform = StandardScaler(with_mean=False, with_std=False, copy=True) + with warnings.catch_warnings(record=True): + X_null = null_transform.fit_transform(X_sparse) + assert_array_equal(X_null.data, X_sparse.data) + X_orig = null_transform.inverse_transform(X_null) + assert_array_equal(X_orig.data, X_sparse.data) + + +@pytest.mark.parametrize("sparse_container", CSR_CONTAINERS + CSC_CONTAINERS) +def test_scaler_without_copy(sparse_container): + # Check that StandardScaler.fit does not change input + rng = np.random.RandomState(42) + X = rng.randn(4, 5) + X[:, 0] = 0.0 # first feature is always of zero + X_sparse = sparse_container(X) + + X_copy = X.copy() + StandardScaler(copy=False).fit(X) + assert_array_equal(X, X_copy) + + X_sparse_copy = X_sparse.copy() + StandardScaler(with_mean=False, copy=False).fit(X_sparse) + assert_array_equal(X_sparse.toarray(), X_sparse_copy.toarray()) + + +@pytest.mark.parametrize("sparse_container", CSR_CONTAINERS + CSC_CONTAINERS) +def test_scale_sparse_with_mean_raise_exception(sparse_container): + rng = np.random.RandomState(42) + X = rng.randn(4, 5) + X_sparse = sparse_container(X) + + # check scaling and fit with direct calls on sparse data + with pytest.raises(ValueError): + scale(X_sparse, with_mean=True) + with pytest.raises(ValueError): + StandardScaler(with_mean=True).fit(X_sparse) + + # check transform and inverse_transform after a fit on a dense array + scaler = StandardScaler(with_mean=True).fit(X) + with pytest.raises(ValueError): + scaler.transform(X_sparse) + + X_transformed_sparse = sparse_container(scaler.transform(X)) + with pytest.raises(ValueError): + scaler.inverse_transform(X_transformed_sparse) + + +def test_scale_input_finiteness_validation(): + # Check if non finite inputs raise ValueError + X = [[np.inf, 5, 6, 7, 8]] + with pytest.raises( + ValueError, match="Input contains infinity or a value too large" + ): + scale(X) + + +def test_robust_scaler_error_sparse(): + X_sparse = sparse.rand(1000, 10) + scaler = RobustScaler(with_centering=True) + err_msg = "Cannot center sparse matrices" + with pytest.raises(ValueError, match=err_msg): + scaler.fit(X_sparse) + + +@pytest.mark.parametrize("with_centering", [True, False]) +@pytest.mark.parametrize("with_scaling", [True, False]) +@pytest.mark.parametrize("X", [np.random.randn(10, 3), sparse.rand(10, 3, density=0.5)]) +def test_robust_scaler_attributes(X, with_centering, with_scaling): + # check consistent type of attributes + if with_centering and sparse.issparse(X): + pytest.skip("RobustScaler cannot center sparse matrix") + + scaler = RobustScaler(with_centering=with_centering, with_scaling=with_scaling) + scaler.fit(X) + + if with_centering: + assert isinstance(scaler.center_, np.ndarray) + else: + assert scaler.center_ is None + if with_scaling: + assert isinstance(scaler.scale_, np.ndarray) + else: + assert scaler.scale_ is None + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_robust_scaler_col_zero_sparse(csr_container): + # check that the scaler is working when there is not data materialized in a + # column of a sparse matrix + X = np.random.randn(10, 5) + X[:, 0] = 0 + X = csr_container(X) + + scaler = RobustScaler(with_centering=False) + scaler.fit(X) + assert scaler.scale_[0] == pytest.approx(1) + + X_trans = scaler.transform(X) + assert_allclose(X[:, [0]].toarray(), X_trans[:, [0]].toarray()) + + +def test_robust_scaler_2d_arrays(): + # Test robust scaling of 2d array along first axis + rng = np.random.RandomState(0) + X = rng.randn(4, 5) + X[:, 0] = 0.0 # first feature is always of zero + + scaler = RobustScaler() + X_scaled = scaler.fit(X).transform(X) + + assert_array_almost_equal(np.median(X_scaled, axis=0), 5 * [0.0]) + assert_array_almost_equal(X_scaled.std(axis=0)[0], 0) + + +@pytest.mark.parametrize("density", [0, 0.05, 0.1, 0.5, 1]) +@pytest.mark.parametrize("strictly_signed", ["positive", "negative", "zeros", None]) +def test_robust_scaler_equivalence_dense_sparse(density, strictly_signed): + # Check the equivalence of the fitting with dense and sparse matrices + X_sparse = sparse.rand(1000, 5, density=density).tocsc() + if strictly_signed == "positive": + X_sparse.data = np.abs(X_sparse.data) + elif strictly_signed == "negative": + X_sparse.data = -np.abs(X_sparse.data) + elif strictly_signed == "zeros": + X_sparse.data = np.zeros(X_sparse.data.shape, dtype=np.float64) + X_dense = X_sparse.toarray() + + scaler_sparse = RobustScaler(with_centering=False) + scaler_dense = RobustScaler(with_centering=False) + + scaler_sparse.fit(X_sparse) + scaler_dense.fit(X_dense) + + assert_allclose(scaler_sparse.scale_, scaler_dense.scale_) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_robust_scaler_transform_one_row_csr(csr_container): + # Check RobustScaler on transforming csr matrix with one row + rng = np.random.RandomState(0) + X = rng.randn(4, 5) + single_row = np.array([[0.1, 1.0, 2.0, 0.0, -1.0]]) + scaler = RobustScaler(with_centering=False) + scaler = scaler.fit(X) + row_trans = scaler.transform(csr_container(single_row)) + row_expected = single_row / scaler.scale_ + assert_array_almost_equal(row_trans.toarray(), row_expected) + row_scaled_back = scaler.inverse_transform(row_trans) + assert_array_almost_equal(single_row, row_scaled_back.toarray()) + + +def test_robust_scaler_iris(): + X = iris.data + scaler = RobustScaler() + X_trans = scaler.fit_transform(X) + assert_array_almost_equal(np.median(X_trans, axis=0), 0) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + q = np.percentile(X_trans, q=(25, 75), axis=0) + iqr = q[1] - q[0] + assert_array_almost_equal(iqr, 1) + + +def test_robust_scaler_iris_quantiles(): + X = iris.data + scaler = RobustScaler(quantile_range=(10, 90)) + X_trans = scaler.fit_transform(X) + assert_array_almost_equal(np.median(X_trans, axis=0), 0) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + q = np.percentile(X_trans, q=(10, 90), axis=0) + q_range = q[1] - q[0] + assert_array_almost_equal(q_range, 1) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_quantile_transform_iris(csc_container): + X = iris.data + # uniform output distribution + transformer = QuantileTransformer(n_quantiles=30) + X_trans = transformer.fit_transform(X) + X_trans_inv = transformer.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + # normal output distribution + transformer = QuantileTransformer(n_quantiles=30, output_distribution="normal") + X_trans = transformer.fit_transform(X) + X_trans_inv = transformer.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + # make sure it is possible to take the inverse of a sparse matrix + # which contain negative value; this is the case in the iris dataset + X_sparse = csc_container(X) + X_sparse_tran = transformer.fit_transform(X_sparse) + X_sparse_tran_inv = transformer.inverse_transform(X_sparse_tran) + assert_array_almost_equal(X_sparse.toarray(), X_sparse_tran_inv.toarray()) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_quantile_transform_check_error(csc_container): + X = np.transpose( + [ + [0, 25, 50, 0, 0, 0, 75, 0, 0, 100], + [2, 4, 0, 0, 6, 8, 0, 10, 0, 0], + [0, 0, 2.6, 4.1, 0, 0, 2.3, 0, 9.5, 0.1], + ] + ) + X = csc_container(X) + X_neg = np.transpose( + [ + [0, 25, 50, 0, 0, 0, 75, 0, 0, 100], + [-2, 4, 0, 0, 6, 8, 0, 10, 0, 0], + [0, 0, 2.6, 4.1, 0, 0, 2.3, 0, 9.5, 0.1], + ] + ) + X_neg = csc_container(X_neg) + + err_msg = ( + "The number of quantiles cannot be greater than " + "the number of samples used. Got 1000 quantiles " + "and 10 samples." + ) + with pytest.raises(ValueError, match=err_msg): + QuantileTransformer(subsample=10).fit(X) + + transformer = QuantileTransformer(n_quantiles=10) + err_msg = "QuantileTransformer only accepts non-negative sparse matrices." + with pytest.raises(ValueError, match=err_msg): + transformer.fit(X_neg) + transformer.fit(X) + err_msg = "QuantileTransformer only accepts non-negative sparse matrices." + with pytest.raises(ValueError, match=err_msg): + transformer.transform(X_neg) + + X_bad_feat = np.transpose( + [[0, 25, 50, 0, 0, 0, 75, 0, 0, 100], [0, 0, 2.6, 4.1, 0, 0, 2.3, 0, 9.5, 0.1]] + ) + err_msg = ( + "X has 2 features, but QuantileTransformer is expecting 3 features as input." + ) + with pytest.raises(ValueError, match=err_msg): + transformer.inverse_transform(X_bad_feat) + + transformer = QuantileTransformer(n_quantiles=10).fit(X) + # check that an error is raised if input is scalar + with pytest.raises(ValueError, match="Expected 2D array, got scalar array instead"): + transformer.transform(10) + # check that a warning is raised is n_quantiles > n_samples + transformer = QuantileTransformer(n_quantiles=100) + warn_msg = "n_quantiles is set to n_samples" + with pytest.warns(UserWarning, match=warn_msg) as record: + transformer.fit(X) + assert len(record) == 1 + assert transformer.n_quantiles_ == X.shape[0] + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_quantile_transform_sparse_ignore_zeros(csc_container): + X = np.array([[0, 1], [0, 0], [0, 2], [0, 2], [0, 1]]) + X_sparse = csc_container(X) + transformer = QuantileTransformer(ignore_implicit_zeros=True, n_quantiles=5) + + # dense case -> warning raise + warning_message = ( + "'ignore_implicit_zeros' takes effect" + " only with sparse matrix. This parameter has no" + " effect." + ) + with pytest.warns(UserWarning, match=warning_message): + transformer.fit(X) + + X_expected = np.array([[0, 0], [0, 0], [0, 1], [0, 1], [0, 0]]) + X_trans = transformer.fit_transform(X_sparse) + assert_almost_equal(X_expected, X_trans.toarray()) + + # consider the case where sparse entries are missing values and user-given + # zeros are to be considered + X_data = np.array([0, 0, 1, 0, 2, 2, 1, 0, 1, 2, 0]) + X_col = np.array([0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]) + X_row = np.array([0, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8]) + X_sparse = csc_container((X_data, (X_row, X_col))) + X_trans = transformer.fit_transform(X_sparse) + X_expected = np.array( + [ + [0.0, 0.5], + [0.0, 0.0], + [0.0, 1.0], + [0.0, 1.0], + [0.0, 0.5], + [0.0, 0.0], + [0.0, 0.5], + [0.0, 1.0], + [0.0, 0.0], + ] + ) + assert_almost_equal(X_expected, X_trans.toarray()) + + transformer = QuantileTransformer(ignore_implicit_zeros=True, n_quantiles=5) + X_data = np.array([-1, -1, 1, 0, 0, 0, 1, -1, 1]) + X_col = np.array([0, 0, 1, 1, 1, 1, 1, 1, 1]) + X_row = np.array([0, 4, 0, 1, 2, 3, 4, 5, 6]) + X_sparse = csc_container((X_data, (X_row, X_col))) + X_trans = transformer.fit_transform(X_sparse) + X_expected = np.array( + [[0, 1], [0, 0.375], [0, 0.375], [0, 0.375], [0, 1], [0, 0], [0, 1]] + ) + assert_almost_equal(X_expected, X_trans.toarray()) + assert_almost_equal( + X_sparse.toarray(), transformer.inverse_transform(X_trans).toarray() + ) + + # check in conjunction with subsampling + transformer = QuantileTransformer( + ignore_implicit_zeros=True, n_quantiles=5, subsample=8, random_state=0 + ) + X_trans = transformer.fit_transform(X_sparse) + assert_almost_equal(X_expected, X_trans.toarray()) + assert_almost_equal( + X_sparse.toarray(), transformer.inverse_transform(X_trans).toarray() + ) + + +def test_quantile_transform_dense_toy(): + X = np.array( + [[0, 2, 2.6], [25, 4, 4.1], [50, 6, 2.3], [75, 8, 9.5], [100, 10, 0.1]] + ) + + transformer = QuantileTransformer(n_quantiles=5) + transformer.fit(X) + + # using a uniform output, each entry of X should be map between 0 and 1 + # and equally spaced + X_trans = transformer.fit_transform(X) + X_expected = np.tile(np.linspace(0, 1, num=5), (3, 1)).T + assert_almost_equal(np.sort(X_trans, axis=0), X_expected) + + X_test = np.array( + [ + [-1, 1, 0], + [101, 11, 10], + ] + ) + X_expected = np.array( + [ + [0, 0, 0], + [1, 1, 1], + ] + ) + assert_array_almost_equal(transformer.transform(X_test), X_expected) + + X_trans_inv = transformer.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + + +def test_quantile_transform_subsampling(): + # Test that subsampling the input yield to a consistent results We check + # that the computed quantiles are almost mapped to a [0, 1] vector where + # values are equally spaced. The infinite norm is checked to be smaller + # than a given threshold. This is repeated 5 times. + + # dense support + n_samples = 1000000 + n_quantiles = 1000 + X = np.sort(np.random.sample((n_samples, 1)), axis=0) + ROUND = 5 + inf_norm_arr = [] + for random_state in range(ROUND): + transformer = QuantileTransformer( + random_state=random_state, + n_quantiles=n_quantiles, + subsample=n_samples // 10, + ) + transformer.fit(X) + diff = np.linspace(0, 1, n_quantiles) - np.ravel(transformer.quantiles_) + inf_norm = np.max(np.abs(diff)) + assert inf_norm < 1e-2 + inf_norm_arr.append(inf_norm) + # each random subsampling yield a unique approximation to the expected + # linspace CDF + assert len(np.unique(inf_norm_arr)) == len(inf_norm_arr) + + # sparse support + + X = sparse.rand(n_samples, 1, density=0.99, format="csc", random_state=0) + inf_norm_arr = [] + for random_state in range(ROUND): + transformer = QuantileTransformer( + random_state=random_state, + n_quantiles=n_quantiles, + subsample=n_samples // 10, + ) + transformer.fit(X) + diff = np.linspace(0, 1, n_quantiles) - np.ravel(transformer.quantiles_) + inf_norm = np.max(np.abs(diff)) + assert inf_norm < 1e-1 + inf_norm_arr.append(inf_norm) + # each random subsampling yield a unique approximation to the expected + # linspace CDF + assert len(np.unique(inf_norm_arr)) == len(inf_norm_arr) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_quantile_transform_sparse_toy(csc_container): + X = np.array( + [ + [0.0, 2.0, 0.0], + [25.0, 4.0, 0.0], + [50.0, 0.0, 2.6], + [0.0, 0.0, 4.1], + [0.0, 6.0, 0.0], + [0.0, 8.0, 0.0], + [75.0, 0.0, 2.3], + [0.0, 10.0, 0.0], + [0.0, 0.0, 9.5], + [100.0, 0.0, 0.1], + ] + ) + + X = csc_container(X) + + transformer = QuantileTransformer(n_quantiles=10) + transformer.fit(X) + + X_trans = transformer.fit_transform(X) + assert_array_almost_equal(np.min(X_trans.toarray(), axis=0), 0.0) + assert_array_almost_equal(np.max(X_trans.toarray(), axis=0), 1.0) + + X_trans_inv = transformer.inverse_transform(X_trans) + assert_array_almost_equal(X.toarray(), X_trans_inv.toarray()) + + transformer_dense = QuantileTransformer(n_quantiles=10).fit(X.toarray()) + + X_trans = transformer_dense.transform(X) + assert_array_almost_equal(np.min(X_trans.toarray(), axis=0), 0.0) + assert_array_almost_equal(np.max(X_trans.toarray(), axis=0), 1.0) + + X_trans_inv = transformer_dense.inverse_transform(X_trans) + assert_array_almost_equal(X.toarray(), X_trans_inv.toarray()) + + +def test_quantile_transform_axis1(): + X = np.array([[0, 25, 50, 75, 100], [2, 4, 6, 8, 10], [2.6, 4.1, 2.3, 9.5, 0.1]]) + + X_trans_a0 = quantile_transform(X.T, axis=0, n_quantiles=5) + X_trans_a1 = quantile_transform(X, axis=1, n_quantiles=5) + assert_array_almost_equal(X_trans_a0, X_trans_a1.T) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_quantile_transform_bounds(csc_container): + # Lower and upper bounds are manually mapped. We checked that in the case + # of a constant feature and binary feature, the bounds are properly mapped. + X_dense = np.array([[0, 0], [0, 0], [1, 0]]) + X_sparse = csc_container(X_dense) + + # check sparse and dense are consistent + X_trans = QuantileTransformer(n_quantiles=3, random_state=0).fit_transform(X_dense) + assert_array_almost_equal(X_trans, X_dense) + X_trans_sp = QuantileTransformer(n_quantiles=3, random_state=0).fit_transform( + X_sparse + ) + assert_array_almost_equal(X_trans_sp.toarray(), X_dense) + assert_array_almost_equal(X_trans, X_trans_sp.toarray()) + + # check the consistency of the bounds by learning on 1 matrix + # and transforming another + X = np.array([[0, 1], [0, 0.5], [1, 0]]) + X1 = np.array([[0, 0.1], [0, 0.5], [1, 0.1]]) + transformer = QuantileTransformer(n_quantiles=3).fit(X) + X_trans = transformer.transform(X1) + assert_array_almost_equal(X_trans, X1) + + # check that values outside of the range learned will be mapped properly. + X = np.random.random((1000, 1)) + transformer = QuantileTransformer() + transformer.fit(X) + assert transformer.transform([[-10]]) == transformer.transform([[np.min(X)]]) + assert transformer.transform([[10]]) == transformer.transform([[np.max(X)]]) + assert transformer.inverse_transform([[-10]]) == transformer.inverse_transform( + [[np.min(transformer.references_)]] + ) + assert transformer.inverse_transform([[10]]) == transformer.inverse_transform( + [[np.max(transformer.references_)]] + ) + + +def test_quantile_transform_and_inverse(): + X_1 = iris.data + X_2 = np.array([[0.0], [BOUNDS_THRESHOLD / 10], [1.5], [2], [3], [3], [4]]) + for X in [X_1, X_2]: + transformer = QuantileTransformer(n_quantiles=1000, random_state=0) + X_trans = transformer.fit_transform(X) + X_trans_inv = transformer.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv, decimal=9) + + +def test_quantile_transform_nan(): + X = np.array([[np.nan, 0, 0, 1], [np.nan, np.nan, 0, 0.5], [np.nan, 1, 1, 0]]) + + transformer = QuantileTransformer(n_quantiles=10, random_state=42) + transformer.fit_transform(X) + + # check that the quantile of the first column is all NaN + assert np.isnan(transformer.quantiles_[:, 0]).all() + # all other column should not contain NaN + assert not np.isnan(transformer.quantiles_[:, 1:]).any() + + +@pytest.mark.parametrize("array_type", ["array", "sparse"]) +def test_quantile_transformer_sorted_quantiles(array_type): + # Non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/15733 + # Taken from upstream bug report: + # https://github.com/numpy/numpy/issues/14685 + X = np.array([0, 1, 1, 2, 2, 3, 3, 4, 5, 5, 1, 1, 9, 9, 9, 8, 8, 7] * 10) + X = 0.1 * X.reshape(-1, 1) + X = _convert_container(X, array_type) + + n_quantiles = 100 + qt = QuantileTransformer(n_quantiles=n_quantiles).fit(X) + + # Check that the estimated quantile thresholds are monotically + # increasing: + quantiles = qt.quantiles_[:, 0] + assert len(quantiles) == 100 + assert all(np.diff(quantiles) >= 0) + + +def test_robust_scaler_invalid_range(): + for range_ in [ + (-1, 90), + (-2, -3), + (10, 101), + (100.5, 101), + (90, 50), + ]: + scaler = RobustScaler(quantile_range=range_) + + with pytest.raises(ValueError, match=r"Invalid quantile range: \("): + scaler.fit(iris.data) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_scale_function_without_centering(csr_container): + rng = np.random.RandomState(42) + X = rng.randn(4, 5) + X[:, 0] = 0.0 # first feature is always of zero + X_csr = csr_container(X) + + X_scaled = scale(X, with_mean=False) + assert not np.any(np.isnan(X_scaled)) + + X_csr_scaled = scale(X_csr, with_mean=False) + assert not np.any(np.isnan(X_csr_scaled.data)) + + # test csc has same outcome + X_csc_scaled = scale(X_csr.tocsc(), with_mean=False) + assert_array_almost_equal(X_scaled, X_csc_scaled.toarray()) + + # raises value error on axis != 0 + with pytest.raises(ValueError): + scale(X_csr, with_mean=False, axis=1) + + assert_array_almost_equal( + X_scaled.mean(axis=0), [0.0, -0.01, 2.24, -0.35, -0.78], 2 + ) + assert_array_almost_equal(X_scaled.std(axis=0), [0.0, 1.0, 1.0, 1.0, 1.0]) + # Check that X has not been copied + assert X_scaled is not X + + X_csr_scaled_mean, X_csr_scaled_std = mean_variance_axis(X_csr_scaled, 0) + assert_array_almost_equal(X_csr_scaled_mean, X_scaled.mean(axis=0)) + assert_array_almost_equal(X_csr_scaled_std, X_scaled.std(axis=0)) + + # null scale + X_csr_scaled = scale(X_csr, with_mean=False, with_std=False, copy=True) + assert_array_almost_equal(X_csr.toarray(), X_csr_scaled.toarray()) + + +def test_robust_scale_axis1(): + X = iris.data + X_trans = robust_scale(X, axis=1) + assert_array_almost_equal(np.median(X_trans, axis=1), 0) + q = np.percentile(X_trans, q=(25, 75), axis=1) + iqr = q[1] - q[0] + assert_array_almost_equal(iqr, 1) + + +def test_robust_scale_1d_array(): + X = iris.data[:, 1] + X_trans = robust_scale(X) + assert_array_almost_equal(np.median(X_trans), 0) + q = np.percentile(X_trans, q=(25, 75)) + iqr = q[1] - q[0] + assert_array_almost_equal(iqr, 1) + + +def test_robust_scaler_zero_variance_features(): + # Check RobustScaler on toy data with zero variance features + X = [[0.0, 1.0, +0.5], [0.0, 1.0, -0.1], [0.0, 1.0, +1.1]] + + scaler = RobustScaler() + X_trans = scaler.fit_transform(X) + + # NOTE: for such a small sample size, what we expect in the third column + # depends HEAVILY on the method used to calculate quantiles. The values + # here were calculated to fit the quantiles produces by np.percentile + # using numpy 1.9 Calculating quantiles with + # scipy.stats.mstats.scoreatquantile or scipy.stats.mstats.mquantiles + # would yield very different results! + X_expected = [[0.0, 0.0, +0.0], [0.0, 0.0, -1.0], [0.0, 0.0, +1.0]] + assert_array_almost_equal(X_trans, X_expected) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + + # make sure new data gets transformed correctly + X_new = [[+0.0, 2.0, 0.5], [-1.0, 1.0, 0.0], [+0.0, 1.0, 1.5]] + X_trans_new = scaler.transform(X_new) + X_expected_new = [[+0.0, 1.0, +0.0], [-1.0, 0.0, -0.83333], [+0.0, 0.0, +1.66667]] + assert_array_almost_equal(X_trans_new, X_expected_new, decimal=3) + + +def test_robust_scaler_unit_variance(): + # Check RobustScaler with unit_variance=True on standard normal data with + # outliers + rng = np.random.RandomState(42) + X = rng.randn(1000000, 1) + X_with_outliers = np.vstack([X, np.ones((100, 1)) * 100, np.ones((100, 1)) * -100]) + + quantile_range = (1, 99) + robust_scaler = RobustScaler(quantile_range=quantile_range, unit_variance=True).fit( + X_with_outliers + ) + X_trans = robust_scaler.transform(X) + + assert robust_scaler.center_ == pytest.approx(0, abs=1e-3) + assert robust_scaler.scale_ == pytest.approx(1, abs=1e-2) + assert X_trans.std() == pytest.approx(1, abs=1e-2) + + +@pytest.mark.parametrize("sparse_container", CSC_CONTAINERS + CSR_CONTAINERS) +def test_maxabs_scaler_zero_variance_features(sparse_container): + # Check MaxAbsScaler on toy data with zero variance features + X = [[0.0, 1.0, +0.5], [0.0, 1.0, -0.3], [0.0, 1.0, +1.5], [0.0, 0.0, +0.0]] + + scaler = MaxAbsScaler() + X_trans = scaler.fit_transform(X) + X_expected = [ + [0.0, 1.0, 1.0 / 3.0], + [0.0, 1.0, -0.2], + [0.0, 1.0, 1.0], + [0.0, 0.0, 0.0], + ] + assert_array_almost_equal(X_trans, X_expected) + X_trans_inv = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X, X_trans_inv) + + # make sure new data gets transformed correctly + X_new = [[+0.0, 2.0, 0.5], [-1.0, 1.0, 0.0], [+0.0, 1.0, 1.5]] + X_trans_new = scaler.transform(X_new) + X_expected_new = [[+0.0, 2.0, 1.0 / 3.0], [-1.0, 1.0, 0.0], [+0.0, 1.0, 1.0]] + + assert_array_almost_equal(X_trans_new, X_expected_new, decimal=2) + + # function interface + X_trans = maxabs_scale(X) + assert_array_almost_equal(X_trans, X_expected) + + # sparse data + X_sparse = sparse_container(X) + X_trans_sparse = scaler.fit_transform(X_sparse) + X_expected = [ + [0.0, 1.0, 1.0 / 3.0], + [0.0, 1.0, -0.2], + [0.0, 1.0, 1.0], + [0.0, 0.0, 0.0], + ] + assert_array_almost_equal(X_trans_sparse.toarray(), X_expected) + X_trans_sparse_inv = scaler.inverse_transform(X_trans_sparse) + assert_array_almost_equal(X, X_trans_sparse_inv.toarray()) + + +def test_maxabs_scaler_large_negative_value(): + # Check MaxAbsScaler on toy data with a large negative value + X = [ + [0.0, 1.0, +0.5, -1.0], + [0.0, 1.0, -0.3, -0.5], + [0.0, 1.0, -100.0, 0.0], + [0.0, 0.0, +0.0, -2.0], + ] + + scaler = MaxAbsScaler() + X_trans = scaler.fit_transform(X) + X_expected = [ + [0.0, 1.0, 0.005, -0.5], + [0.0, 1.0, -0.003, -0.25], + [0.0, 1.0, -1.0, 0.0], + [0.0, 0.0, 0.0, -1.0], + ] + assert_array_almost_equal(X_trans, X_expected) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_maxabs_scaler_transform_one_row_csr(csr_container): + # Check MaxAbsScaler on transforming csr matrix with one row + X = csr_container([[0.5, 1.0, 1.0]]) + scaler = MaxAbsScaler() + scaler = scaler.fit(X) + X_trans = scaler.transform(X) + X_expected = csr_container([[1.0, 1.0, 1.0]]) + assert_array_almost_equal(X_trans.toarray(), X_expected.toarray()) + X_scaled_back = scaler.inverse_transform(X_trans) + assert_array_almost_equal(X.toarray(), X_scaled_back.toarray()) + + +def test_maxabs_scaler_1d(): + # Test scaling of dataset along single axis + for X in [X_1row, X_1col, X_list_1row, X_list_1row]: + scaler = MaxAbsScaler(copy=True) + X_scaled = scaler.fit(X).transform(X) + + if isinstance(X, list): + X = np.array(X) # cast only after scaling done + + if _check_dim_1axis(X) == 1: + assert_array_almost_equal(np.abs(X_scaled.max(axis=0)), np.ones(n_features)) + else: + assert_array_almost_equal(np.abs(X_scaled.max(axis=0)), 1.0) + assert scaler.n_samples_seen_ == X.shape[0] + + # check inverse transform + X_scaled_back = scaler.inverse_transform(X_scaled) + assert_array_almost_equal(X_scaled_back, X) + + # Constant feature + X = np.ones((5, 1)) + scaler = MaxAbsScaler() + X_scaled = scaler.fit(X).transform(X) + assert_array_almost_equal(np.abs(X_scaled.max(axis=0)), 1.0) + assert scaler.n_samples_seen_ == X.shape[0] + + # function interface + X_1d = X_1row.ravel() + max_abs = np.abs(X_1d).max() + assert_array_almost_equal(X_1d / max_abs, maxabs_scale(X_1d, copy=True)) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_maxabs_scaler_partial_fit(csr_container): + # Test if partial_fit run over many batches of size 1 and 50 + # gives the same results as fit + X = X_2d[:100, :] + n = X.shape[0] + + for chunk_size in [1, 2, 50, n, n + 42]: + # Test mean at the end of the process + scaler_batch = MaxAbsScaler().fit(X) + + scaler_incr = MaxAbsScaler() + scaler_incr_csr = MaxAbsScaler() + scaler_incr_csc = MaxAbsScaler() + for batch in gen_batches(n, chunk_size): + scaler_incr = scaler_incr.partial_fit(X[batch]) + X_csr = csr_container(X[batch]) + scaler_incr_csr = scaler_incr_csr.partial_fit(X_csr) + X_csc = csr_container(X[batch]) + scaler_incr_csc = scaler_incr_csc.partial_fit(X_csc) + + assert_array_almost_equal(scaler_batch.max_abs_, scaler_incr.max_abs_) + assert_array_almost_equal(scaler_batch.max_abs_, scaler_incr_csr.max_abs_) + assert_array_almost_equal(scaler_batch.max_abs_, scaler_incr_csc.max_abs_) + assert scaler_batch.n_samples_seen_ == scaler_incr.n_samples_seen_ + assert scaler_batch.n_samples_seen_ == scaler_incr_csr.n_samples_seen_ + assert scaler_batch.n_samples_seen_ == scaler_incr_csc.n_samples_seen_ + assert_array_almost_equal(scaler_batch.scale_, scaler_incr.scale_) + assert_array_almost_equal(scaler_batch.scale_, scaler_incr_csr.scale_) + assert_array_almost_equal(scaler_batch.scale_, scaler_incr_csc.scale_) + assert_array_almost_equal(scaler_batch.transform(X), scaler_incr.transform(X)) + + # Test std after 1 step + batch0 = slice(0, chunk_size) + scaler_batch = MaxAbsScaler().fit(X[batch0]) + scaler_incr = MaxAbsScaler().partial_fit(X[batch0]) + + assert_array_almost_equal(scaler_batch.max_abs_, scaler_incr.max_abs_) + assert scaler_batch.n_samples_seen_ == scaler_incr.n_samples_seen_ + assert_array_almost_equal(scaler_batch.scale_, scaler_incr.scale_) + assert_array_almost_equal(scaler_batch.transform(X), scaler_incr.transform(X)) + + # Test std until the end of partial fits, and + scaler_batch = MaxAbsScaler().fit(X) + scaler_incr = MaxAbsScaler() # Clean estimator + for i, batch in enumerate(gen_batches(n, chunk_size)): + scaler_incr = scaler_incr.partial_fit(X[batch]) + assert_correct_incr( + i, + batch_start=batch.start, + batch_stop=batch.stop, + n=n, + chunk_size=chunk_size, + n_samples_seen=scaler_incr.n_samples_seen_, + ) + + +def check_normalizer(norm, X_norm): + """ + Convenient checking function for `test_normalizer_l1_l2_max` and + `test_normalizer_l1_l2_max_non_csr` + """ + if norm == "l1": + row_sums = np.abs(X_norm).sum(axis=1) + for i in range(3): + assert_almost_equal(row_sums[i], 1.0) + assert_almost_equal(row_sums[3], 0.0) + elif norm == "l2": + for i in range(3): + assert_almost_equal(la.norm(X_norm[i]), 1.0) + assert_almost_equal(la.norm(X_norm[3]), 0.0) + elif norm == "max": + row_maxs = abs(X_norm).max(axis=1) + for i in range(3): + assert_almost_equal(row_maxs[i], 1.0) + assert_almost_equal(row_maxs[3], 0.0) + + +@pytest.mark.parametrize("norm", ["l1", "l2", "max"]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_normalizer_l1_l2_max(norm, csr_container): + rng = np.random.RandomState(0) + X_dense = rng.randn(4, 5) + X_sparse_unpruned = csr_container(X_dense) + + # set the row number 3 to zero + X_dense[3, :] = 0.0 + + # set the row number 3 to zero without pruning (can happen in real life) + indptr_3 = X_sparse_unpruned.indptr[3] + indptr_4 = X_sparse_unpruned.indptr[4] + X_sparse_unpruned.data[indptr_3:indptr_4] = 0.0 + + # build the pruned variant using the regular constructor + X_sparse_pruned = csr_container(X_dense) + + # check inputs that support the no-copy optim + for X in (X_dense, X_sparse_pruned, X_sparse_unpruned): + normalizer = Normalizer(norm=norm, copy=True) + X_norm1 = normalizer.transform(X) + assert X_norm1 is not X + X_norm1 = toarray(X_norm1) + + normalizer = Normalizer(norm=norm, copy=False) + X_norm2 = normalizer.transform(X) + assert X_norm2 is X + X_norm2 = toarray(X_norm2) + + for X_norm in (X_norm1, X_norm2): + check_normalizer(norm, X_norm) + + +@pytest.mark.parametrize("norm", ["l1", "l2", "max"]) +@pytest.mark.parametrize( + "sparse_container", COO_CONTAINERS + CSC_CONTAINERS + LIL_CONTAINERS +) +def test_normalizer_l1_l2_max_non_csr(norm, sparse_container): + rng = np.random.RandomState(0) + X_dense = rng.randn(4, 5) + + # set the row number 3 to zero + X_dense[3, :] = 0.0 + + X = sparse_container(X_dense) + X_norm = Normalizer(norm=norm, copy=False).transform(X) + + assert X_norm is not X + assert sparse.issparse(X_norm) and X_norm.format == "csr" + + X_norm = toarray(X_norm) + check_normalizer(norm, X_norm) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_normalizer_max_sign(csr_container): + # check that we normalize by a positive number even for negative data + rng = np.random.RandomState(0) + X_dense = rng.randn(4, 5) + # set the row number 3 to zero + X_dense[3, :] = 0.0 + # check for mixed data where the value with + # largest magnitude is negative + X_dense[2, abs(X_dense[2, :]).argmax()] *= -1 + X_all_neg = -np.abs(X_dense) + X_all_neg_sparse = csr_container(X_all_neg) + + for X in (X_dense, X_all_neg, X_all_neg_sparse): + normalizer = Normalizer(norm="max") + X_norm = normalizer.transform(X) + assert X_norm is not X + X_norm = toarray(X_norm) + assert_array_equal(np.sign(X_norm), np.sign(toarray(X))) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_normalize(csr_container): + # Test normalize function + # Only tests functionality not used by the tests for Normalizer. + X = np.random.RandomState(37).randn(3, 2) + assert_array_equal(normalize(X, copy=False), normalize(X.T, axis=0, copy=False).T) + + rs = np.random.RandomState(0) + X_dense = rs.randn(10, 5) + X_sparse = csr_container(X_dense) + ones = np.ones((10)) + for X in (X_dense, X_sparse): + for dtype in (np.float32, np.float64): + for norm in ("l1", "l2"): + X = X.astype(dtype) + X_norm = normalize(X, norm=norm) + assert X_norm.dtype == dtype + + X_norm = toarray(X_norm) + if norm == "l1": + row_sums = np.abs(X_norm).sum(axis=1) + else: + X_norm_squared = X_norm**2 + row_sums = X_norm_squared.sum(axis=1) + + assert_array_almost_equal(row_sums, ones) + + # Test return_norm + X_dense = np.array([[3.0, 0, 4.0], [1.0, 0.0, 0.0], [2.0, 3.0, 0.0]]) + for norm in ("l1", "l2", "max"): + _, norms = normalize(X_dense, norm=norm, return_norm=True) + if norm == "l1": + assert_array_almost_equal(norms, np.array([7.0, 1.0, 5.0])) + elif norm == "l2": + assert_array_almost_equal(norms, np.array([5.0, 1.0, 3.60555127])) + else: + assert_array_almost_equal(norms, np.array([4.0, 1.0, 3.0])) + + X_sparse = csr_container(X_dense) + for norm in ("l1", "l2"): + with pytest.raises(NotImplementedError): + normalize(X_sparse, norm=norm, return_norm=True) + _, norms = normalize(X_sparse, norm="max", return_norm=True) + assert_array_almost_equal(norms, np.array([4.0, 1.0, 3.0])) + + +@pytest.mark.parametrize( + "constructor", [np.array, list] + CSC_CONTAINERS + CSR_CONTAINERS +) +def test_binarizer(constructor): + X_ = np.array([[1, 0, 5], [2, 3, -1]]) + X = constructor(X_.copy()) + + binarizer = Binarizer(threshold=2.0, copy=True) + X_bin = toarray(binarizer.transform(X)) + assert np.sum(X_bin == 0) == 4 + assert np.sum(X_bin == 1) == 2 + X_bin = binarizer.transform(X) + assert sparse.issparse(X) == sparse.issparse(X_bin) + + binarizer = Binarizer(copy=True).fit(X) + X_bin = toarray(binarizer.transform(X)) + assert X_bin is not X + assert np.sum(X_bin == 0) == 2 + assert np.sum(X_bin == 1) == 4 + + binarizer = Binarizer(copy=True) + X_bin = binarizer.transform(X) + assert X_bin is not X + X_bin = toarray(X_bin) + assert np.sum(X_bin == 0) == 2 + assert np.sum(X_bin == 1) == 4 + + binarizer = Binarizer(copy=False) + X_bin = binarizer.transform(X) + if constructor is not list: + assert X_bin is X + + binarizer = Binarizer(copy=False) + X_float = np.array([[1, 0, 5], [2, 3, -1]], dtype=np.float64) + X_bin = binarizer.transform(X_float) + if constructor is not list: + assert X_bin is X_float + + X_bin = toarray(X_bin) + assert np.sum(X_bin == 0) == 2 + assert np.sum(X_bin == 1) == 4 + + binarizer = Binarizer(threshold=-0.5, copy=True) + if constructor in (np.array, list): + X = constructor(X_.copy()) + + X_bin = toarray(binarizer.transform(X)) + assert np.sum(X_bin == 0) == 1 + assert np.sum(X_bin == 1) == 5 + X_bin = binarizer.transform(X) + + # Cannot use threshold < 0 for sparse + if constructor in CSC_CONTAINERS: + with pytest.raises(ValueError): + binarizer.transform(constructor(X)) + + +def test_center_kernel(): + # Test that KernelCenterer is equivalent to StandardScaler + # in feature space + rng = np.random.RandomState(0) + X_fit = rng.random_sample((5, 4)) + scaler = StandardScaler(with_std=False) + scaler.fit(X_fit) + X_fit_centered = scaler.transform(X_fit) + K_fit = np.dot(X_fit, X_fit.T) + + # center fit time matrix + centerer = KernelCenterer() + K_fit_centered = np.dot(X_fit_centered, X_fit_centered.T) + K_fit_centered2 = centerer.fit_transform(K_fit) + assert_array_almost_equal(K_fit_centered, K_fit_centered2) + + # center predict time matrix + X_pred = rng.random_sample((2, 4)) + K_pred = np.dot(X_pred, X_fit.T) + X_pred_centered = scaler.transform(X_pred) + K_pred_centered = np.dot(X_pred_centered, X_fit_centered.T) + K_pred_centered2 = centerer.transform(K_pred) + assert_array_almost_equal(K_pred_centered, K_pred_centered2) + + # check the results coherence with the method proposed in: + # B. Schölkopf, A. Smola, and K.R. Müller, + # "Nonlinear component analysis as a kernel eigenvalue problem" + # equation (B.3) + + # K_centered3 = (I - 1_M) K (I - 1_M) + # = K - 1_M K - K 1_M + 1_M K 1_M + ones_M = np.ones_like(K_fit) / K_fit.shape[0] + K_fit_centered3 = K_fit - ones_M @ K_fit - K_fit @ ones_M + ones_M @ K_fit @ ones_M + assert_allclose(K_fit_centered, K_fit_centered3) + + # K_test_centered3 = (K_test - 1'_M K)(I - 1_M) + # = K_test - 1'_M K - K_test 1_M + 1'_M K 1_M + ones_prime_M = np.ones_like(K_pred) / K_fit.shape[0] + K_pred_centered3 = ( + K_pred - ones_prime_M @ K_fit - K_pred @ ones_M + ones_prime_M @ K_fit @ ones_M + ) + assert_allclose(K_pred_centered, K_pred_centered3) + + +def test_kernelcenterer_non_linear_kernel(): + """Check kernel centering for non-linear kernel.""" + rng = np.random.RandomState(0) + X, X_test = rng.randn(100, 50), rng.randn(20, 50) + + def phi(X): + """Our mapping function phi.""" + return np.vstack( + [ + np.clip(X, a_min=0, a_max=None), + -np.clip(X, a_min=None, a_max=0), + ] + ) + + phi_X = phi(X) + phi_X_test = phi(X_test) + + # centered the projection + scaler = StandardScaler(with_std=False) + phi_X_center = scaler.fit_transform(phi_X) + phi_X_test_center = scaler.transform(phi_X_test) + + # create the different kernel + K = phi_X @ phi_X.T + K_test = phi_X_test @ phi_X.T + K_center = phi_X_center @ phi_X_center.T + K_test_center = phi_X_test_center @ phi_X_center.T + + kernel_centerer = KernelCenterer() + kernel_centerer.fit(K) + + assert_allclose(kernel_centerer.transform(K), K_center) + assert_allclose(kernel_centerer.transform(K_test), K_test_center) + + # check the results coherence with the method proposed in: + # B. Schölkopf, A. Smola, and K.R. Müller, + # "Nonlinear component analysis as a kernel eigenvalue problem" + # equation (B.3) + + # K_centered = (I - 1_M) K (I - 1_M) + # = K - 1_M K - K 1_M + 1_M K 1_M + ones_M = np.ones_like(K) / K.shape[0] + K_centered = K - ones_M @ K - K @ ones_M + ones_M @ K @ ones_M + assert_allclose(kernel_centerer.transform(K), K_centered) + + # K_test_centered = (K_test - 1'_M K)(I - 1_M) + # = K_test - 1'_M K - K_test 1_M + 1'_M K 1_M + ones_prime_M = np.ones_like(K_test) / K.shape[0] + K_test_centered = ( + K_test - ones_prime_M @ K - K_test @ ones_M + ones_prime_M @ K @ ones_M + ) + assert_allclose(kernel_centerer.transform(K_test), K_test_centered) + + +def test_cv_pipeline_precomputed(): + # Cross-validate a regression on four coplanar points with the same + # value. Use precomputed kernel to ensure Pipeline with KernelCenterer + # is treated as a pairwise operation. + X = np.array([[3, 0, 0], [0, 3, 0], [0, 0, 3], [1, 1, 1]]) + y_true = np.ones((4,)) + K = X.dot(X.T) + kcent = KernelCenterer() + pipeline = Pipeline([("kernel_centerer", kcent), ("svr", SVR())]) + + # did the pipeline set the pairwise attribute? + assert pipeline._get_tags()["pairwise"] + + # test cross-validation, score should be almost perfect + # NB: this test is pretty vacuous -- it's mainly to test integration + # of Pipeline and KernelCenterer + y_pred = cross_val_predict(pipeline, K, y_true, cv=2) + assert_array_almost_equal(y_true, y_pred) + + +def test_fit_transform(): + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + for obj in (StandardScaler(), Normalizer(), Binarizer()): + X_transformed = obj.fit(X).transform(X) + X_transformed2 = obj.fit_transform(X) + assert_array_equal(X_transformed, X_transformed2) + + +def test_add_dummy_feature(): + X = [[1, 0], [0, 1], [0, 1]] + X = add_dummy_feature(X) + assert_array_equal(X, [[1, 1, 0], [1, 0, 1], [1, 0, 1]]) + + +@pytest.mark.parametrize( + "sparse_container", COO_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS +) +def test_add_dummy_feature_sparse(sparse_container): + X = sparse_container([[1, 0], [0, 1], [0, 1]]) + desired_format = X.format + X = add_dummy_feature(X) + assert sparse.issparse(X) and X.format == desired_format, X + assert_array_equal(X.toarray(), [[1, 1, 0], [1, 0, 1], [1, 0, 1]]) + + +def test_fit_cold_start(): + X = iris.data + X_2d = X[:, :2] + + # Scalers that have a partial_fit method + scalers = [ + StandardScaler(with_mean=False, with_std=False), + MinMaxScaler(), + MaxAbsScaler(), + ] + + for scaler in scalers: + scaler.fit_transform(X) + # with a different shape, this may break the scaler unless the internal + # state is reset + scaler.fit_transform(X_2d) + + +@pytest.mark.parametrize("method", ["box-cox", "yeo-johnson"]) +def test_power_transformer_notfitted(method): + pt = PowerTransformer(method=method) + X = np.abs(X_1col) + with pytest.raises(NotFittedError): + pt.transform(X) + with pytest.raises(NotFittedError): + pt.inverse_transform(X) + + +@pytest.mark.parametrize("method", ["box-cox", "yeo-johnson"]) +@pytest.mark.parametrize("standardize", [True, False]) +@pytest.mark.parametrize("X", [X_1col, X_2d]) +def test_power_transformer_inverse(method, standardize, X): + # Make sure we get the original input when applying transform and then + # inverse transform + X = np.abs(X) if method == "box-cox" else X + pt = PowerTransformer(method=method, standardize=standardize) + X_trans = pt.fit_transform(X) + assert_almost_equal(X, pt.inverse_transform(X_trans)) + + +def test_power_transformer_1d(): + X = np.abs(X_1col) + + for standardize in [True, False]: + pt = PowerTransformer(method="box-cox", standardize=standardize) + + X_trans = pt.fit_transform(X) + X_trans_func = power_transform(X, method="box-cox", standardize=standardize) + + X_expected, lambda_expected = stats.boxcox(X.flatten()) + + if standardize: + X_expected = scale(X_expected) + + assert_almost_equal(X_expected.reshape(-1, 1), X_trans) + assert_almost_equal(X_expected.reshape(-1, 1), X_trans_func) + + assert_almost_equal(X, pt.inverse_transform(X_trans)) + assert_almost_equal(lambda_expected, pt.lambdas_[0]) + + assert len(pt.lambdas_) == X.shape[1] + assert isinstance(pt.lambdas_, np.ndarray) + + +def test_power_transformer_2d(): + X = np.abs(X_2d) + + for standardize in [True, False]: + pt = PowerTransformer(method="box-cox", standardize=standardize) + + X_trans_class = pt.fit_transform(X) + X_trans_func = power_transform(X, method="box-cox", standardize=standardize) + + for X_trans in [X_trans_class, X_trans_func]: + for j in range(X_trans.shape[1]): + X_expected, lmbda = stats.boxcox(X[:, j].flatten()) + + if standardize: + X_expected = scale(X_expected) + + assert_almost_equal(X_trans[:, j], X_expected) + assert_almost_equal(lmbda, pt.lambdas_[j]) + + # Test inverse transformation + X_inv = pt.inverse_transform(X_trans) + assert_array_almost_equal(X_inv, X) + + assert len(pt.lambdas_) == X.shape[1] + assert isinstance(pt.lambdas_, np.ndarray) + + +def test_power_transformer_boxcox_strictly_positive_exception(): + # Exceptions should be raised for negative arrays and zero arrays when + # method is boxcox + + pt = PowerTransformer(method="box-cox") + pt.fit(np.abs(X_2d)) + X_with_negatives = X_2d + not_positive_message = "strictly positive" + + with pytest.raises(ValueError, match=not_positive_message): + pt.transform(X_with_negatives) + + with pytest.raises(ValueError, match=not_positive_message): + pt.fit(X_with_negatives) + + with pytest.raises(ValueError, match=not_positive_message): + power_transform(X_with_negatives, method="box-cox") + + with pytest.raises(ValueError, match=not_positive_message): + pt.transform(np.zeros(X_2d.shape)) + + with pytest.raises(ValueError, match=not_positive_message): + pt.fit(np.zeros(X_2d.shape)) + + with pytest.raises(ValueError, match=not_positive_message): + power_transform(np.zeros(X_2d.shape), method="box-cox") + + +@pytest.mark.parametrize("X", [X_2d, np.abs(X_2d), -np.abs(X_2d), np.zeros(X_2d.shape)]) +def test_power_transformer_yeojohnson_any_input(X): + # Yeo-Johnson method should support any kind of input + power_transform(X, method="yeo-johnson") + + +@pytest.mark.parametrize("method", ["box-cox", "yeo-johnson"]) +def test_power_transformer_shape_exception(method): + pt = PowerTransformer(method=method) + X = np.abs(X_2d) + pt.fit(X) + + # Exceptions should be raised for arrays with different num_columns + # than during fitting + wrong_shape_message = ( + r"X has \d+ features, but PowerTransformer is " r"expecting \d+ features" + ) + + with pytest.raises(ValueError, match=wrong_shape_message): + pt.transform(X[:, 0:1]) + + with pytest.raises(ValueError, match=wrong_shape_message): + pt.inverse_transform(X[:, 0:1]) + + +def test_power_transformer_lambda_zero(): + pt = PowerTransformer(method="box-cox", standardize=False) + X = np.abs(X_2d)[:, 0:1] + + # Test the lambda = 0 case + pt.lambdas_ = np.array([0]) + X_trans = pt.transform(X) + assert_array_almost_equal(pt.inverse_transform(X_trans), X) + + +def test_power_transformer_lambda_one(): + # Make sure lambda = 1 corresponds to the identity for yeo-johnson + pt = PowerTransformer(method="yeo-johnson", standardize=False) + X = np.abs(X_2d)[:, 0:1] + + pt.lambdas_ = np.array([1]) + X_trans = pt.transform(X) + assert_array_almost_equal(X_trans, X) + + +@pytest.mark.parametrize( + "method, lmbda", + [ + ("box-cox", 0.1), + ("box-cox", 0.5), + ("yeo-johnson", 0.1), + ("yeo-johnson", 0.5), + ("yeo-johnson", 1.0), + ], +) +def test_optimization_power_transformer(method, lmbda): + # Test the optimization procedure: + # - set a predefined value for lambda + # - apply inverse_transform to a normal dist (we get X_inv) + # - apply fit_transform to X_inv (we get X_inv_trans) + # - check that X_inv_trans is roughly equal to X + + rng = np.random.RandomState(0) + n_samples = 20000 + X = rng.normal(loc=0, scale=1, size=(n_samples, 1)) + + pt = PowerTransformer(method=method, standardize=False) + pt.lambdas_ = [lmbda] + X_inv = pt.inverse_transform(X) + + pt = PowerTransformer(method=method, standardize=False) + X_inv_trans = pt.fit_transform(X_inv) + + assert_almost_equal(0, np.linalg.norm(X - X_inv_trans) / n_samples, decimal=2) + assert_almost_equal(0, X_inv_trans.mean(), decimal=1) + assert_almost_equal(1, X_inv_trans.std(), decimal=1) + + +def test_yeo_johnson_darwin_example(): + # test from original paper "A new family of power transformations to + # improve normality or symmetry" by Yeo and Johnson. + X = [6.1, -8.4, 1.0, 2.0, 0.7, 2.9, 3.5, 5.1, 1.8, 3.6, 7.0, 3.0, 9.3, 7.5, -6.0] + X = np.array(X).reshape(-1, 1) + lmbda = PowerTransformer(method="yeo-johnson").fit(X).lambdas_ + assert np.allclose(lmbda, 1.305, atol=1e-3) + + +@pytest.mark.parametrize("method", ["box-cox", "yeo-johnson"]) +def test_power_transformer_nans(method): + # Make sure lambda estimation is not influenced by NaN values + # and that transform() supports NaN silently + + X = np.abs(X_1col) + pt = PowerTransformer(method=method) + pt.fit(X) + lmbda_no_nans = pt.lambdas_[0] + + # concat nans at the end and check lambda stays the same + X = np.concatenate([X, np.full_like(X, np.nan)]) + X = shuffle(X, random_state=0) + + pt.fit(X) + lmbda_nans = pt.lambdas_[0] + + assert_almost_equal(lmbda_no_nans, lmbda_nans, decimal=5) + + X_trans = pt.transform(X) + assert_array_equal(np.isnan(X_trans), np.isnan(X)) + + +@pytest.mark.parametrize("method", ["box-cox", "yeo-johnson"]) +@pytest.mark.parametrize("standardize", [True, False]) +def test_power_transformer_fit_transform(method, standardize): + # check that fit_transform() and fit().transform() return the same values + X = X_1col + if method == "box-cox": + X = np.abs(X) + + pt = PowerTransformer(method, standardize=standardize) + assert_array_almost_equal(pt.fit(X).transform(X), pt.fit_transform(X)) + + +@pytest.mark.parametrize("method", ["box-cox", "yeo-johnson"]) +@pytest.mark.parametrize("standardize", [True, False]) +def test_power_transformer_copy_True(method, standardize): + # Check that neither fit, transform, fit_transform nor inverse_transform + # modify X inplace when copy=True + X = X_1col + if method == "box-cox": + X = np.abs(X) + + X_original = X.copy() + assert X is not X_original # sanity checks + assert_array_almost_equal(X, X_original) + + pt = PowerTransformer(method, standardize=standardize, copy=True) + + pt.fit(X) + assert_array_almost_equal(X, X_original) + X_trans = pt.transform(X) + assert X_trans is not X + + X_trans = pt.fit_transform(X) + assert_array_almost_equal(X, X_original) + assert X_trans is not X + + X_inv_trans = pt.inverse_transform(X_trans) + assert X_trans is not X_inv_trans + + +@pytest.mark.parametrize("method", ["box-cox", "yeo-johnson"]) +@pytest.mark.parametrize("standardize", [True, False]) +def test_power_transformer_copy_False(method, standardize): + # check that when copy=False fit doesn't change X inplace but transform, + # fit_transform and inverse_transform do. + X = X_1col + if method == "box-cox": + X = np.abs(X) + + X_original = X.copy() + assert X is not X_original # sanity checks + assert_array_almost_equal(X, X_original) + + pt = PowerTransformer(method, standardize=standardize, copy=False) + + pt.fit(X) + assert_array_almost_equal(X, X_original) # fit didn't change X + + X_trans = pt.transform(X) + assert X_trans is X + + if method == "box-cox": + X = np.abs(X) + X_trans = pt.fit_transform(X) + assert X_trans is X + + X_inv_trans = pt.inverse_transform(X_trans) + assert X_trans is X_inv_trans + + +def test_power_transformer_box_cox_raise_all_nans_col(): + """Check that box-cox raises informative when a column contains all nans. + + Non-regression test for gh-26303 + """ + X = rng.random_sample((4, 5)) + X[:, 0] = np.nan + + err_msg = "Column must not be all nan." + + pt = PowerTransformer(method="box-cox") + with pytest.raises(ValueError, match=err_msg): + pt.fit_transform(X) + + +@pytest.mark.parametrize( + "X_2", + [sparse.random(10, 1, density=0.8, random_state=0)] + + [ + csr_container(np.full((10, 1), fill_value=np.nan)) + for csr_container in CSR_CONTAINERS + ], +) +def test_standard_scaler_sparse_partial_fit_finite_variance(X_2): + # non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/16448 + X_1 = sparse.random(5, 1, density=0.8) + scaler = StandardScaler(with_mean=False) + scaler.fit(X_1).partial_fit(X_2) + assert np.isfinite(scaler.var_[0]) + + +@pytest.mark.parametrize("feature_range", [(0, 1), (-10, 10)]) +def test_minmax_scaler_clip(feature_range): + # test behaviour of the parameter 'clip' in MinMaxScaler + X = iris.data + scaler = MinMaxScaler(feature_range=feature_range, clip=True).fit(X) + X_min, X_max = np.min(X, axis=0), np.max(X, axis=0) + X_test = [np.r_[X_min[:2] - 10, X_max[2:] + 10]] + X_transformed = scaler.transform(X_test) + assert_allclose( + X_transformed, + [[feature_range[0], feature_range[0], feature_range[1], feature_range[1]]], + ) + + +def test_standard_scaler_raise_error_for_1d_input(): + """Check that `inverse_transform` from `StandardScaler` raises an error + with 1D array. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/19518 + """ + scaler = StandardScaler().fit(X_2d) + err_msg = "Expected 2D array, got 1D array instead" + with pytest.raises(ValueError, match=err_msg): + scaler.inverse_transform(X_2d[:, 0]) + + +def test_power_transformer_significantly_non_gaussian(): + """Check that significantly non-Gaussian data before transforms correctly. + + For some explored lambdas, the transformed data may be constant and will + be rejected. Non-regression test for + https://github.com/scikit-learn/scikit-learn/issues/14959 + """ + + X_non_gaussian = 1e6 * np.array( + [0.6, 2.0, 3.0, 4.0] * 4 + [11, 12, 12, 16, 17, 20, 85, 90], dtype=np.float64 + ).reshape(-1, 1) + pt = PowerTransformer() + + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + X_trans = pt.fit_transform(X_non_gaussian) + + assert not np.any(np.isnan(X_trans)) + assert X_trans.mean() == pytest.approx(0.0) + assert X_trans.std() == pytest.approx(1.0) + assert X_trans.min() > -2 + assert X_trans.max() < 2 + + +@pytest.mark.parametrize( + "Transformer", + [ + MinMaxScaler, + MaxAbsScaler, + RobustScaler, + StandardScaler, + QuantileTransformer, + PowerTransformer, + ], +) +def test_one_to_one_features(Transformer): + """Check one-to-one transformers give correct feature names.""" + tr = Transformer().fit(iris.data) + names_out = tr.get_feature_names_out(iris.feature_names) + assert_array_equal(names_out, iris.feature_names) + + +@pytest.mark.parametrize( + "Transformer", + [ + MinMaxScaler, + MaxAbsScaler, + RobustScaler, + StandardScaler, + QuantileTransformer, + PowerTransformer, + Normalizer, + Binarizer, + ], +) +def test_one_to_one_features_pandas(Transformer): + """Check one-to-one transformers give correct feature names.""" + pd = pytest.importorskip("pandas") + + df = pd.DataFrame(iris.data, columns=iris.feature_names) + tr = Transformer().fit(df) + + names_out_df_default = tr.get_feature_names_out() + assert_array_equal(names_out_df_default, iris.feature_names) + + names_out_df_valid_in = tr.get_feature_names_out(iris.feature_names) + assert_array_equal(names_out_df_valid_in, iris.feature_names) + + msg = re.escape("input_features is not equal to feature_names_in_") + with pytest.raises(ValueError, match=msg): + invalid_names = list("abcd") + tr.get_feature_names_out(invalid_names) + + +def test_kernel_centerer_feature_names_out(): + """Test that kernel centerer `feature_names_out`.""" + + rng = np.random.RandomState(0) + X = rng.random_sample((6, 4)) + X_pairwise = linear_kernel(X) + centerer = KernelCenterer().fit(X_pairwise) + + names_out = centerer.get_feature_names_out() + samples_out2 = X_pairwise.shape[1] + assert_array_equal(names_out, [f"kernelcenterer{i}" for i in range(samples_out2)]) + + +@pytest.mark.parametrize("standardize", [True, False]) +def test_power_transformer_constant_feature(standardize): + """Check that PowerTransfomer leaves constant features unchanged.""" + X = [[-2, 0, 2], [-2, 0, 2], [-2, 0, 2]] + + pt = PowerTransformer(method="yeo-johnson", standardize=standardize).fit(X) + + assert_allclose(pt.lambdas_, [1, 1, 1]) + + Xft = pt.fit_transform(X) + Xt = pt.transform(X) + + for Xt_ in [Xft, Xt]: + if standardize: + assert_allclose(Xt_, np.zeros_like(X)) + else: + assert_allclose(Xt_, X) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_discretization.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_discretization.py new file mode 100644 index 0000000000000000000000000000000000000000..46ec86f7a75d43378614639f04e3c72e7e69aede --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_discretization.py @@ -0,0 +1,503 @@ +import warnings + +import numpy as np +import pytest +import scipy.sparse as sp + +from sklearn import clone +from sklearn.preprocessing import KBinsDiscretizer, OneHotEncoder +from sklearn.utils._testing import ( + assert_allclose, + assert_allclose_dense_sparse, + assert_array_almost_equal, + assert_array_equal, +) + +X = [[-2, 1.5, -4, -1], [-1, 2.5, -3, -0.5], [0, 3.5, -2, 0.5], [1, 4.5, -1, 2]] + + +@pytest.mark.parametrize( + "strategy, expected, sample_weight", + [ + ("uniform", [[0, 0, 0, 0], [1, 1, 1, 0], [2, 2, 2, 1], [2, 2, 2, 2]], None), + ("kmeans", [[0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2]], None), + ("quantile", [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [2, 2, 2, 2]], None), + ( + "quantile", + [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [2, 2, 2, 2]], + [1, 1, 2, 1], + ), + ( + "quantile", + [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [2, 2, 2, 2]], + [1, 1, 1, 1], + ), + ( + "quantile", + [[0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1]], + [0, 1, 1, 1], + ), + ( + "kmeans", + [[0, 0, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1], [2, 2, 2, 2]], + [1, 0, 3, 1], + ), + ( + "kmeans", + [[0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2]], + [1, 1, 1, 1], + ), + ], +) +# TODO(1.5) remove warning filter when kbd's subsample default is changed +@pytest.mark.filterwarnings("ignore:In version 1.5 onwards, subsample=200_000") +def test_fit_transform(strategy, expected, sample_weight): + est = KBinsDiscretizer(n_bins=3, encode="ordinal", strategy=strategy) + est.fit(X, sample_weight=sample_weight) + assert_array_equal(expected, est.transform(X)) + + +def test_valid_n_bins(): + KBinsDiscretizer(n_bins=2).fit_transform(X) + KBinsDiscretizer(n_bins=np.array([2])[0]).fit_transform(X) + assert KBinsDiscretizer(n_bins=2).fit(X).n_bins_.dtype == np.dtype(int) + + +@pytest.mark.parametrize("strategy", ["uniform"]) +def test_kbinsdiscretizer_wrong_strategy_with_weights(strategy): + """Check that we raise an error when the wrong strategy is used.""" + sample_weight = np.ones(shape=(len(X))) + est = KBinsDiscretizer(n_bins=3, strategy=strategy) + err_msg = ( + "`sample_weight` was provided but it cannot be used with strategy='uniform'." + ) + with pytest.raises(ValueError, match=err_msg): + est.fit(X, sample_weight=sample_weight) + + +def test_invalid_n_bins_array(): + # Bad shape + n_bins = np.full((2, 4), 2.0) + est = KBinsDiscretizer(n_bins=n_bins) + err_msg = r"n_bins must be a scalar or array of shape \(n_features,\)." + with pytest.raises(ValueError, match=err_msg): + est.fit_transform(X) + + # Incorrect number of features + n_bins = [1, 2, 2] + est = KBinsDiscretizer(n_bins=n_bins) + err_msg = r"n_bins must be a scalar or array of shape \(n_features,\)." + with pytest.raises(ValueError, match=err_msg): + est.fit_transform(X) + + # Bad bin values + n_bins = [1, 2, 2, 1] + est = KBinsDiscretizer(n_bins=n_bins) + err_msg = ( + "KBinsDiscretizer received an invalid number of bins " + "at indices 0, 3. Number of bins must be at least 2, " + "and must be an int." + ) + with pytest.raises(ValueError, match=err_msg): + est.fit_transform(X) + + # Float bin values + n_bins = [2.1, 2, 2.1, 2] + est = KBinsDiscretizer(n_bins=n_bins) + err_msg = ( + "KBinsDiscretizer received an invalid number of bins " + "at indices 0, 2. Number of bins must be at least 2, " + "and must be an int." + ) + with pytest.raises(ValueError, match=err_msg): + est.fit_transform(X) + + +@pytest.mark.parametrize( + "strategy, expected, sample_weight", + [ + ("uniform", [[0, 0, 0, 0], [0, 1, 1, 0], [1, 2, 2, 1], [1, 2, 2, 2]], None), + ("kmeans", [[0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [1, 2, 2, 2]], None), + ("quantile", [[0, 0, 0, 0], [0, 1, 1, 1], [1, 2, 2, 2], [1, 2, 2, 2]], None), + ( + "quantile", + [[0, 0, 0, 0], [0, 1, 1, 1], [1, 2, 2, 2], [1, 2, 2, 2]], + [1, 1, 3, 1], + ), + ( + "quantile", + [[0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1]], + [0, 1, 3, 1], + ), + # ( + # "quantile", + # [[0, 0, 0, 0], [0, 1, 1, 1], [1, 2, 2, 2], [1, 2, 2, 2]], + # [1, 1, 1, 1], + # ), + # + # TODO: This test case above aims to test if the case where an array of + # ones passed in sample_weight parameter is equal to the case when + # sample_weight is None. + # Unfortunately, the behavior of `_weighted_percentile` when + # `sample_weight = [1, 1, 1, 1]` are currently not equivalent. + # This problem has been addressed in issue : + # https://github.com/scikit-learn/scikit-learn/issues/17370 + ( + "kmeans", + [[0, 0, 0, 0], [0, 1, 1, 0], [1, 1, 1, 1], [1, 2, 2, 2]], + [1, 0, 3, 1], + ), + ], +) +# TODO(1.5) remove warning filter when kbd's subsample default is changed +@pytest.mark.filterwarnings("ignore:In version 1.5 onwards, subsample=200_000") +def test_fit_transform_n_bins_array(strategy, expected, sample_weight): + est = KBinsDiscretizer( + n_bins=[2, 3, 3, 3], encode="ordinal", strategy=strategy + ).fit(X, sample_weight=sample_weight) + assert_array_equal(expected, est.transform(X)) + + # test the shape of bin_edges_ + n_features = np.array(X).shape[1] + assert est.bin_edges_.shape == (n_features,) + for bin_edges, n_bins in zip(est.bin_edges_, est.n_bins_): + assert bin_edges.shape == (n_bins + 1,) + + +@pytest.mark.filterwarnings("ignore: Bins whose width are too small") +def test_kbinsdiscretizer_effect_sample_weight(): + """Check the impact of `sample_weight` one computed quantiles.""" + X = np.array([[-2], [-1], [1], [3], [500], [1000]]) + # add a large number of bins such that each sample with a non-null weight + # will be used as bin edge + est = KBinsDiscretizer(n_bins=10, encode="ordinal", strategy="quantile") + est.fit(X, sample_weight=[1, 1, 1, 1, 0, 0]) + assert_allclose(est.bin_edges_[0], [-2, -1, 1, 3]) + assert_allclose(est.transform(X), [[0.0], [1.0], [2.0], [2.0], [2.0], [2.0]]) + + +# TODO(1.5) remove warning filter when kbd's subsample default is changed +@pytest.mark.filterwarnings("ignore:In version 1.5 onwards, subsample=200_000") +@pytest.mark.parametrize("strategy", ["kmeans", "quantile"]) +def test_kbinsdiscretizer_no_mutating_sample_weight(strategy): + """Make sure that `sample_weight` is not changed in place.""" + est = KBinsDiscretizer(n_bins=3, encode="ordinal", strategy=strategy) + sample_weight = np.array([1, 3, 1, 2], dtype=np.float64) + sample_weight_copy = np.copy(sample_weight) + est.fit(X, sample_weight=sample_weight) + assert_allclose(sample_weight, sample_weight_copy) + + +@pytest.mark.parametrize("strategy", ["uniform", "kmeans", "quantile"]) +def test_same_min_max(strategy): + warnings.simplefilter("always") + X = np.array([[1, -2], [1, -1], [1, 0], [1, 1]]) + est = KBinsDiscretizer(strategy=strategy, n_bins=3, encode="ordinal") + warning_message = "Feature 0 is constant and will be replaced with 0." + with pytest.warns(UserWarning, match=warning_message): + est.fit(X) + assert est.n_bins_[0] == 1 + # replace the feature with zeros + Xt = est.transform(X) + assert_array_equal(Xt[:, 0], np.zeros(X.shape[0])) + + +def test_transform_1d_behavior(): + X = np.arange(4) + est = KBinsDiscretizer(n_bins=2) + with pytest.raises(ValueError): + est.fit(X) + + est = KBinsDiscretizer(n_bins=2) + est.fit(X.reshape(-1, 1)) + with pytest.raises(ValueError): + est.transform(X) + + +@pytest.mark.parametrize("i", range(1, 9)) +def test_numeric_stability(i): + X_init = np.array([2.0, 4.0, 6.0, 8.0, 10.0]).reshape(-1, 1) + Xt_expected = np.array([0, 0, 1, 1, 1]).reshape(-1, 1) + + # Test up to discretizing nano units + X = X_init / 10**i + Xt = KBinsDiscretizer(n_bins=2, encode="ordinal").fit_transform(X) + assert_array_equal(Xt_expected, Xt) + + +def test_encode_options(): + est = KBinsDiscretizer(n_bins=[2, 3, 3, 3], encode="ordinal").fit(X) + Xt_1 = est.transform(X) + est = KBinsDiscretizer(n_bins=[2, 3, 3, 3], encode="onehot-dense").fit(X) + Xt_2 = est.transform(X) + assert not sp.issparse(Xt_2) + assert_array_equal( + OneHotEncoder( + categories=[np.arange(i) for i in [2, 3, 3, 3]], sparse_output=False + ).fit_transform(Xt_1), + Xt_2, + ) + est = KBinsDiscretizer(n_bins=[2, 3, 3, 3], encode="onehot").fit(X) + Xt_3 = est.transform(X) + assert sp.issparse(Xt_3) + assert_array_equal( + OneHotEncoder( + categories=[np.arange(i) for i in [2, 3, 3, 3]], sparse_output=True + ) + .fit_transform(Xt_1) + .toarray(), + Xt_3.toarray(), + ) + + +@pytest.mark.parametrize( + "strategy, expected_2bins, expected_3bins, expected_5bins", + [ + ("uniform", [0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 2, 2], [0, 0, 1, 1, 4, 4]), + ("kmeans", [0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 2, 2], [0, 0, 1, 2, 3, 4]), + ("quantile", [0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 2, 2], [0, 1, 2, 3, 4, 4]), + ], +) +# TODO(1.5) remove warning filter when kbd's subsample default is changed +@pytest.mark.filterwarnings("ignore:In version 1.5 onwards, subsample=200_000") +def test_nonuniform_strategies( + strategy, expected_2bins, expected_3bins, expected_5bins +): + X = np.array([0, 0.5, 2, 3, 9, 10]).reshape(-1, 1) + + # with 2 bins + est = KBinsDiscretizer(n_bins=2, strategy=strategy, encode="ordinal") + Xt = est.fit_transform(X) + assert_array_equal(expected_2bins, Xt.ravel()) + + # with 3 bins + est = KBinsDiscretizer(n_bins=3, strategy=strategy, encode="ordinal") + Xt = est.fit_transform(X) + assert_array_equal(expected_3bins, Xt.ravel()) + + # with 5 bins + est = KBinsDiscretizer(n_bins=5, strategy=strategy, encode="ordinal") + Xt = est.fit_transform(X) + assert_array_equal(expected_5bins, Xt.ravel()) + + +@pytest.mark.parametrize( + "strategy, expected_inv", + [ + ( + "uniform", + [ + [-1.5, 2.0, -3.5, -0.5], + [-0.5, 3.0, -2.5, -0.5], + [0.5, 4.0, -1.5, 0.5], + [0.5, 4.0, -1.5, 1.5], + ], + ), + ( + "kmeans", + [ + [-1.375, 2.125, -3.375, -0.5625], + [-1.375, 2.125, -3.375, -0.5625], + [-0.125, 3.375, -2.125, 0.5625], + [0.75, 4.25, -1.25, 1.625], + ], + ), + ( + "quantile", + [ + [-1.5, 2.0, -3.5, -0.75], + [-0.5, 3.0, -2.5, 0.0], + [0.5, 4.0, -1.5, 1.25], + [0.5, 4.0, -1.5, 1.25], + ], + ), + ], +) +# TODO(1.5) remove warning filter when kbd's subsample default is changed +@pytest.mark.filterwarnings("ignore:In version 1.5 onwards, subsample=200_000") +@pytest.mark.parametrize("encode", ["ordinal", "onehot", "onehot-dense"]) +def test_inverse_transform(strategy, encode, expected_inv): + kbd = KBinsDiscretizer(n_bins=3, strategy=strategy, encode=encode) + Xt = kbd.fit_transform(X) + Xinv = kbd.inverse_transform(Xt) + assert_array_almost_equal(expected_inv, Xinv) + + +# TODO(1.5) remove warning filter when kbd's subsample default is changed +@pytest.mark.filterwarnings("ignore:In version 1.5 onwards, subsample=200_000") +@pytest.mark.parametrize("strategy", ["uniform", "kmeans", "quantile"]) +def test_transform_outside_fit_range(strategy): + X = np.array([0, 1, 2, 3])[:, None] + kbd = KBinsDiscretizer(n_bins=4, strategy=strategy, encode="ordinal") + kbd.fit(X) + + X2 = np.array([-2, 5])[:, None] + X2t = kbd.transform(X2) + assert_array_equal(X2t.max(axis=0) + 1, kbd.n_bins_) + assert_array_equal(X2t.min(axis=0), [0]) + + +def test_overwrite(): + X = np.array([0, 1, 2, 3])[:, None] + X_before = X.copy() + + est = KBinsDiscretizer(n_bins=3, encode="ordinal") + Xt = est.fit_transform(X) + assert_array_equal(X, X_before) + + Xt_before = Xt.copy() + Xinv = est.inverse_transform(Xt) + assert_array_equal(Xt, Xt_before) + assert_array_equal(Xinv, np.array([[0.5], [1.5], [2.5], [2.5]])) + + +@pytest.mark.parametrize( + "strategy, expected_bin_edges", [("quantile", [0, 1, 3]), ("kmeans", [0, 1.5, 3])] +) +def test_redundant_bins(strategy, expected_bin_edges): + X = [[0], [0], [0], [0], [3], [3]] + kbd = KBinsDiscretizer(n_bins=3, strategy=strategy, subsample=None) + warning_message = "Consider decreasing the number of bins." + with pytest.warns(UserWarning, match=warning_message): + kbd.fit(X) + assert_array_almost_equal(kbd.bin_edges_[0], expected_bin_edges) + + +def test_percentile_numeric_stability(): + X = np.array([0.05, 0.05, 0.95]).reshape(-1, 1) + bin_edges = np.array([0.05, 0.23, 0.41, 0.59, 0.77, 0.95]) + Xt = np.array([0, 0, 4]).reshape(-1, 1) + kbd = KBinsDiscretizer(n_bins=10, encode="ordinal", strategy="quantile") + warning_message = "Consider decreasing the number of bins." + with pytest.warns(UserWarning, match=warning_message): + kbd.fit(X) + + assert_array_almost_equal(kbd.bin_edges_[0], bin_edges) + assert_array_almost_equal(kbd.transform(X), Xt) + + +@pytest.mark.parametrize("in_dtype", [np.float16, np.float32, np.float64]) +@pytest.mark.parametrize("out_dtype", [None, np.float32, np.float64]) +@pytest.mark.parametrize("encode", ["ordinal", "onehot", "onehot-dense"]) +def test_consistent_dtype(in_dtype, out_dtype, encode): + X_input = np.array(X, dtype=in_dtype) + kbd = KBinsDiscretizer(n_bins=3, encode=encode, dtype=out_dtype) + kbd.fit(X_input) + + # test output dtype + if out_dtype is not None: + expected_dtype = out_dtype + elif out_dtype is None and X_input.dtype == np.float16: + # wrong numeric input dtype are cast in np.float64 + expected_dtype = np.float64 + else: + expected_dtype = X_input.dtype + Xt = kbd.transform(X_input) + assert Xt.dtype == expected_dtype + + +@pytest.mark.parametrize("input_dtype", [np.float16, np.float32, np.float64]) +@pytest.mark.parametrize("encode", ["ordinal", "onehot", "onehot-dense"]) +def test_32_equal_64(input_dtype, encode): + # TODO this check is redundant with common checks and can be removed + # once #16290 is merged + X_input = np.array(X, dtype=input_dtype) + + # 32 bit output + kbd_32 = KBinsDiscretizer(n_bins=3, encode=encode, dtype=np.float32) + kbd_32.fit(X_input) + Xt_32 = kbd_32.transform(X_input) + + # 64 bit output + kbd_64 = KBinsDiscretizer(n_bins=3, encode=encode, dtype=np.float64) + kbd_64.fit(X_input) + Xt_64 = kbd_64.transform(X_input) + + assert_allclose_dense_sparse(Xt_32, Xt_64) + + +def test_kbinsdiscretizer_subsample_default(): + # Since the size of X is small (< 2e5), subsampling will not take place. + X = np.array([-2, 1.5, -4, -1]).reshape(-1, 1) + kbd_default = KBinsDiscretizer(n_bins=10, encode="ordinal", strategy="quantile") + kbd_default.fit(X) + + kbd_without_subsampling = clone(kbd_default) + kbd_without_subsampling.set_params(subsample=None) + kbd_without_subsampling.fit(X) + + for bin_kbd_default, bin_kbd_with_subsampling in zip( + kbd_default.bin_edges_[0], kbd_without_subsampling.bin_edges_[0] + ): + np.testing.assert_allclose(bin_kbd_default, bin_kbd_with_subsampling) + assert kbd_default.bin_edges_.shape == kbd_without_subsampling.bin_edges_.shape + + +@pytest.mark.parametrize( + "encode, expected_names", + [ + ( + "onehot", + [ + f"feat{col_id}_{float(bin_id)}" + for col_id in range(3) + for bin_id in range(4) + ], + ), + ( + "onehot-dense", + [ + f"feat{col_id}_{float(bin_id)}" + for col_id in range(3) + for bin_id in range(4) + ], + ), + ("ordinal", [f"feat{col_id}" for col_id in range(3)]), + ], +) +def test_kbinsdiscrtizer_get_feature_names_out(encode, expected_names): + """Check get_feature_names_out for different settings. + Non-regression test for #22731 + """ + X = [[-2, 1, -4], [-1, 2, -3], [0, 3, -2], [1, 4, -1]] + + kbd = KBinsDiscretizer(n_bins=4, encode=encode).fit(X) + Xt = kbd.transform(X) + + input_features = [f"feat{i}" for i in range(3)] + output_names = kbd.get_feature_names_out(input_features) + assert Xt.shape[1] == output_names.shape[0] + + assert_array_equal(output_names, expected_names) + + +@pytest.mark.parametrize("strategy", ["uniform", "kmeans", "quantile"]) +def test_kbinsdiscretizer_subsample(strategy, global_random_seed): + # Check that the bin edges are almost the same when subsampling is used. + X = np.random.RandomState(global_random_seed).random_sample((100000, 1)) + 1 + + kbd_subsampling = KBinsDiscretizer( + strategy=strategy, subsample=50000, random_state=global_random_seed + ) + kbd_subsampling.fit(X) + + kbd_no_subsampling = clone(kbd_subsampling) + kbd_no_subsampling.set_params(subsample=None) + kbd_no_subsampling.fit(X) + + # We use a large tolerance because we can't expect the bin edges to be exactly the + # same when subsampling is used. + assert_allclose( + kbd_subsampling.bin_edges_[0], kbd_no_subsampling.bin_edges_[0], rtol=1e-2 + ) + + +# TODO(1.5) remove this test +@pytest.mark.parametrize("strategy", ["uniform", "kmeans"]) +def test_kbd_subsample_warning(strategy): + # Check the future warning for the change of default of subsample + X = np.random.RandomState(0).random_sample((100, 1)) + + kbd = KBinsDiscretizer(strategy=strategy, random_state=0) + with pytest.warns(FutureWarning, match="subsample=200_000 will be used by default"): + kbd.fit(X) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_function_transformer.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_function_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b86e88d1547cb296d89687f2179ab850349dd5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_function_transformer.py @@ -0,0 +1,591 @@ +import warnings + +import numpy as np +import pytest + +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import FunctionTransformer, StandardScaler +from sklearn.preprocessing._function_transformer import _get_adapter_from_container +from sklearn.utils._testing import ( + _convert_container, + assert_allclose_dense_sparse, + assert_array_equal, +) +from sklearn.utils.fixes import CSC_CONTAINERS, CSR_CONTAINERS + + +def test_get_adapter_from_container(): + """Check the behavior fo `_get_adapter_from_container`.""" + pd = pytest.importorskip("pandas") + X = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 100]}) + adapter = _get_adapter_from_container(X) + assert adapter.container_lib == "pandas" + err_msg = "The container does not have a registered adapter in scikit-learn." + with pytest.raises(ValueError, match=err_msg): + _get_adapter_from_container(X.to_numpy()) + + +def _make_func(args_store, kwargs_store, func=lambda X, *a, **k: X): + def _func(X, *args, **kwargs): + args_store.append(X) + args_store.extend(args) + kwargs_store.update(kwargs) + return func(X) + + return _func + + +def test_delegate_to_func(): + # (args|kwargs)_store will hold the positional and keyword arguments + # passed to the function inside the FunctionTransformer. + args_store = [] + kwargs_store = {} + X = np.arange(10).reshape((5, 2)) + assert_array_equal( + FunctionTransformer(_make_func(args_store, kwargs_store)).transform(X), + X, + "transform should have returned X unchanged", + ) + + # The function should only have received X. + assert args_store == [ + X + ], "Incorrect positional arguments passed to func: {args}".format(args=args_store) + + assert ( + not kwargs_store + ), "Unexpected keyword arguments passed to func: {args}".format(args=kwargs_store) + + # reset the argument stores. + args_store[:] = [] + kwargs_store.clear() + transformed = FunctionTransformer( + _make_func(args_store, kwargs_store), + ).transform(X) + + assert_array_equal( + transformed, X, err_msg="transform should have returned X unchanged" + ) + + # The function should have received X + assert args_store == [ + X + ], "Incorrect positional arguments passed to func: {args}".format(args=args_store) + + assert ( + not kwargs_store + ), "Unexpected keyword arguments passed to func: {args}".format(args=kwargs_store) + + +def test_np_log(): + X = np.arange(10).reshape((5, 2)) + + # Test that the numpy.log example still works. + assert_array_equal( + FunctionTransformer(np.log1p).transform(X), + np.log1p(X), + ) + + +def test_kw_arg(): + X = np.linspace(0, 1, num=10).reshape((5, 2)) + + F = FunctionTransformer(np.around, kw_args=dict(decimals=3)) + + # Test that rounding is correct + assert_array_equal(F.transform(X), np.around(X, decimals=3)) + + +def test_kw_arg_update(): + X = np.linspace(0, 1, num=10).reshape((5, 2)) + + F = FunctionTransformer(np.around, kw_args=dict(decimals=3)) + + F.kw_args["decimals"] = 1 + + # Test that rounding is correct + assert_array_equal(F.transform(X), np.around(X, decimals=1)) + + +def test_kw_arg_reset(): + X = np.linspace(0, 1, num=10).reshape((5, 2)) + + F = FunctionTransformer(np.around, kw_args=dict(decimals=3)) + + F.kw_args = dict(decimals=1) + + # Test that rounding is correct + assert_array_equal(F.transform(X), np.around(X, decimals=1)) + + +def test_inverse_transform(): + X = np.array([1, 4, 9, 16]).reshape((2, 2)) + + # Test that inverse_transform works correctly + F = FunctionTransformer( + func=np.sqrt, + inverse_func=np.around, + inv_kw_args=dict(decimals=3), + ) + assert_array_equal( + F.inverse_transform(F.transform(X)), + np.around(np.sqrt(X), decimals=3), + ) + + +@pytest.mark.parametrize("sparse_container", [None] + CSC_CONTAINERS + CSR_CONTAINERS) +def test_check_inverse(sparse_container): + X = np.array([1, 4, 9, 16], dtype=np.float64).reshape((2, 2)) + if sparse_container is not None: + X = sparse_container(X) + + trans = FunctionTransformer( + func=np.sqrt, + inverse_func=np.around, + accept_sparse=sparse_container is not None, + check_inverse=True, + validate=True, + ) + warning_message = ( + "The provided functions are not strictly" + " inverse of each other. If you are sure you" + " want to proceed regardless, set" + " 'check_inverse=False'." + ) + with pytest.warns(UserWarning, match=warning_message): + trans.fit(X) + + trans = FunctionTransformer( + func=np.expm1, + inverse_func=np.log1p, + accept_sparse=sparse_container is not None, + check_inverse=True, + validate=True, + ) + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + Xt = trans.fit_transform(X) + + assert_allclose_dense_sparse(X, trans.inverse_transform(Xt)) + + +def test_check_inverse_func_or_inverse_not_provided(): + # check that we don't check inverse when one of the func or inverse is not + # provided. + X = np.array([1, 4, 9, 16], dtype=np.float64).reshape((2, 2)) + + trans = FunctionTransformer( + func=np.expm1, inverse_func=None, check_inverse=True, validate=True + ) + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + trans.fit(X) + trans = FunctionTransformer( + func=None, inverse_func=np.expm1, check_inverse=True, validate=True + ) + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + trans.fit(X) + + +def test_function_transformer_frame(): + pd = pytest.importorskip("pandas") + X_df = pd.DataFrame(np.random.randn(100, 10)) + transformer = FunctionTransformer() + X_df_trans = transformer.fit_transform(X_df) + assert hasattr(X_df_trans, "loc") + + +@pytest.mark.parametrize("X_type", ["array", "series"]) +def test_function_transformer_raise_error_with_mixed_dtype(X_type): + """Check that `FunctionTransformer.check_inverse` raises error on mixed dtype.""" + mapping = {"one": 1, "two": 2, "three": 3, 5: "five", 6: "six"} + inverse_mapping = {value: key for key, value in mapping.items()} + dtype = "object" + + data = ["one", "two", "three", "one", "one", 5, 6] + data = _convert_container(data, X_type, columns_name=["value"], dtype=dtype) + + def func(X): + return np.array([mapping[X[i]] for i in range(X.size)], dtype=object) + + def inverse_func(X): + return _convert_container( + [inverse_mapping[x] for x in X], + X_type, + columns_name=["value"], + dtype=dtype, + ) + + transformer = FunctionTransformer( + func=func, inverse_func=inverse_func, validate=False, check_inverse=True + ) + + msg = "'check_inverse' is only supported when all the elements in `X` is numerical." + with pytest.raises(ValueError, match=msg): + transformer.fit(data) + + +def test_function_transformer_support_all_nummerical_dataframes_check_inverse_True(): + """Check support for dataframes with only numerical values.""" + pd = pytest.importorskip("pandas") + + df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + transformer = FunctionTransformer( + func=lambda x: x + 2, inverse_func=lambda x: x - 2, check_inverse=True + ) + + # Does not raise an error + df_out = transformer.fit_transform(df) + assert_allclose_dense_sparse(df_out, df + 2) + + +def test_function_transformer_with_dataframe_and_check_inverse_True(): + """Check error is raised when check_inverse=True. + + Non-regresion test for gh-25261. + """ + pd = pytest.importorskip("pandas") + transformer = FunctionTransformer( + func=lambda x: x, inverse_func=lambda x: x, check_inverse=True + ) + + df_mixed = pd.DataFrame({"a": [1, 2, 3], "b": ["a", "b", "c"]}) + msg = "'check_inverse' is only supported when all the elements in `X` is numerical." + with pytest.raises(ValueError, match=msg): + transformer.fit(df_mixed) + + +@pytest.mark.parametrize( + "X, feature_names_out, input_features, expected", + [ + ( + # NumPy inputs, default behavior: generate names + np.random.rand(100, 3), + "one-to-one", + None, + ("x0", "x1", "x2"), + ), + ( + # Pandas input, default behavior: use input feature names + {"a": np.random.rand(100), "b": np.random.rand(100)}, + "one-to-one", + None, + ("a", "b"), + ), + ( + # NumPy input, feature_names_out=callable + np.random.rand(100, 3), + lambda transformer, input_features: ("a", "b"), + None, + ("a", "b"), + ), + ( + # Pandas input, feature_names_out=callable + {"a": np.random.rand(100), "b": np.random.rand(100)}, + lambda transformer, input_features: ("c", "d", "e"), + None, + ("c", "d", "e"), + ), + ( + # NumPy input, feature_names_out=callable – default input_features + np.random.rand(100, 3), + lambda transformer, input_features: tuple(input_features) + ("a",), + None, + ("x0", "x1", "x2", "a"), + ), + ( + # Pandas input, feature_names_out=callable – default input_features + {"a": np.random.rand(100), "b": np.random.rand(100)}, + lambda transformer, input_features: tuple(input_features) + ("c",), + None, + ("a", "b", "c"), + ), + ( + # NumPy input, input_features=list of names + np.random.rand(100, 3), + "one-to-one", + ("a", "b", "c"), + ("a", "b", "c"), + ), + ( + # Pandas input, input_features=list of names + {"a": np.random.rand(100), "b": np.random.rand(100)}, + "one-to-one", + ("a", "b"), # must match feature_names_in_ + ("a", "b"), + ), + ( + # NumPy input, feature_names_out=callable, input_features=list + np.random.rand(100, 3), + lambda transformer, input_features: tuple(input_features) + ("d",), + ("a", "b", "c"), + ("a", "b", "c", "d"), + ), + ( + # Pandas input, feature_names_out=callable, input_features=list + {"a": np.random.rand(100), "b": np.random.rand(100)}, + lambda transformer, input_features: tuple(input_features) + ("c",), + ("a", "b"), # must match feature_names_in_ + ("a", "b", "c"), + ), + ], +) +@pytest.mark.parametrize("validate", [True, False]) +def test_function_transformer_get_feature_names_out( + X, feature_names_out, input_features, expected, validate +): + if isinstance(X, dict): + pd = pytest.importorskip("pandas") + X = pd.DataFrame(X) + + transformer = FunctionTransformer( + feature_names_out=feature_names_out, validate=validate + ) + transformer.fit(X) + names = transformer.get_feature_names_out(input_features) + assert isinstance(names, np.ndarray) + assert names.dtype == object + assert_array_equal(names, expected) + + +def test_function_transformer_get_feature_names_out_without_validation(): + transformer = FunctionTransformer(feature_names_out="one-to-one", validate=False) + X = np.random.rand(100, 2) + transformer.fit_transform(X) + + names = transformer.get_feature_names_out(("a", "b")) + assert isinstance(names, np.ndarray) + assert names.dtype == object + assert_array_equal(names, ("a", "b")) + + +def test_function_transformer_feature_names_out_is_None(): + transformer = FunctionTransformer() + X = np.random.rand(100, 2) + transformer.fit_transform(X) + + msg = "This 'FunctionTransformer' has no attribute 'get_feature_names_out'" + with pytest.raises(AttributeError, match=msg): + transformer.get_feature_names_out() + + +def test_function_transformer_feature_names_out_uses_estimator(): + def add_n_random_features(X, n): + return np.concatenate([X, np.random.rand(len(X), n)], axis=1) + + def feature_names_out(transformer, input_features): + n = transformer.kw_args["n"] + return list(input_features) + [f"rnd{i}" for i in range(n)] + + transformer = FunctionTransformer( + func=add_n_random_features, + feature_names_out=feature_names_out, + kw_args=dict(n=3), + validate=True, + ) + pd = pytest.importorskip("pandas") + df = pd.DataFrame({"a": np.random.rand(100), "b": np.random.rand(100)}) + transformer.fit_transform(df) + names = transformer.get_feature_names_out() + + assert isinstance(names, np.ndarray) + assert names.dtype == object + assert_array_equal(names, ("a", "b", "rnd0", "rnd1", "rnd2")) + + +def test_function_transformer_validate_inverse(): + """Test that function transformer does not reset estimator in + `inverse_transform`.""" + + def add_constant_feature(X): + X_one = np.ones((X.shape[0], 1)) + return np.concatenate((X, X_one), axis=1) + + def inverse_add_constant(X): + return X[:, :-1] + + X = np.array([[1, 2], [3, 4], [3, 4]]) + trans = FunctionTransformer( + func=add_constant_feature, + inverse_func=inverse_add_constant, + validate=True, + ) + X_trans = trans.fit_transform(X) + assert trans.n_features_in_ == X.shape[1] + + trans.inverse_transform(X_trans) + assert trans.n_features_in_ == X.shape[1] + + +@pytest.mark.parametrize( + "feature_names_out, expected", + [ + ("one-to-one", ["pet", "color"]), + [lambda est, names: [f"{n}_out" for n in names], ["pet_out", "color_out"]], + ], +) +@pytest.mark.parametrize("in_pipeline", [True, False]) +def test_get_feature_names_out_dataframe_with_string_data( + feature_names_out, expected, in_pipeline +): + """Check that get_feature_names_out works with DataFrames with string data.""" + pd = pytest.importorskip("pandas") + X = pd.DataFrame({"pet": ["dog", "cat"], "color": ["red", "green"]}) + + def func(X): + if feature_names_out == "one-to-one": + return X + else: + name = feature_names_out(None, X.columns) + return X.rename(columns=dict(zip(X.columns, name))) + + transformer = FunctionTransformer(func=func, feature_names_out=feature_names_out) + if in_pipeline: + transformer = make_pipeline(transformer) + + X_trans = transformer.fit_transform(X) + assert isinstance(X_trans, pd.DataFrame) + + names = transformer.get_feature_names_out() + assert isinstance(names, np.ndarray) + assert names.dtype == object + assert_array_equal(names, expected) + + +def test_set_output_func(): + """Check behavior of set_output with different settings.""" + pd = pytest.importorskip("pandas") + + X = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 100]}) + + ft = FunctionTransformer(np.log, feature_names_out="one-to-one") + + # no warning is raised when feature_names_out is defined + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + ft.set_output(transform="pandas") + + X_trans = ft.fit_transform(X) + assert isinstance(X_trans, pd.DataFrame) + assert_array_equal(X_trans.columns, ["a", "b"]) + + ft = FunctionTransformer(lambda x: 2 * x) + ft.set_output(transform="pandas") + + # no warning is raised when func returns a panda dataframe + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + X_trans = ft.fit_transform(X) + assert isinstance(X_trans, pd.DataFrame) + assert_array_equal(X_trans.columns, ["a", "b"]) + + # Warning is raised when func returns a ndarray + ft_np = FunctionTransformer(lambda x: np.asarray(x)) + + for transform in ("pandas", "polars"): + ft_np.set_output(transform=transform) + msg = ( + f"When `set_output` is configured to be '{transform}'.*{transform} " + "DataFrame.*" + ) + with pytest.warns(UserWarning, match=msg): + ft_np.fit_transform(X) + + # default transform does not warn + ft_np.set_output(transform="default") + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + ft_np.fit_transform(X) + + +def test_consistence_column_name_between_steps(): + """Check that we have a consistence between the feature names out of + `FunctionTransformer` and the feature names in of the next step in the pipeline. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/27695 + """ + pd = pytest.importorskip("pandas") + + def with_suffix(_, names): + return [name + "__log" for name in names] + + pipeline = make_pipeline( + FunctionTransformer(np.log1p, feature_names_out=with_suffix), StandardScaler() + ) + + df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], columns=["a", "b"]) + X_trans = pipeline.fit_transform(df) + assert pipeline.get_feature_names_out().tolist() == ["a__log", "b__log"] + # StandardScaler will convert to a numpy array + assert isinstance(X_trans, np.ndarray) + + +@pytest.mark.parametrize("dataframe_lib", ["pandas", "polars"]) +@pytest.mark.parametrize("transform_output", ["default", "pandas", "polars"]) +def test_function_transformer_overwrite_column_names(dataframe_lib, transform_output): + """Check that we overwrite the column names when we should.""" + lib = pytest.importorskip(dataframe_lib) + if transform_output != "numpy": + pytest.importorskip(transform_output) + + df = lib.DataFrame({"a": [1, 2, 3], "b": [10, 20, 100]}) + + def with_suffix(_, names): + return [name + "__log" for name in names] + + transformer = FunctionTransformer(feature_names_out=with_suffix).set_output( + transform=transform_output + ) + X_trans = transformer.fit_transform(df) + assert_array_equal(np.asarray(X_trans), np.asarray(df)) + + feature_names = transformer.get_feature_names_out() + assert list(X_trans.columns) == with_suffix(None, df.columns) + assert feature_names.tolist() == with_suffix(None, df.columns) + + +@pytest.mark.parametrize( + "feature_names_out", + ["one-to-one", lambda _, names: [f"{name}_log" for name in names]], +) +def test_function_transformer_overwrite_column_names_numerical(feature_names_out): + """Check the same as `test_function_transformer_overwrite_column_names` + but for the specific case of pandas where column names can be numerical.""" + pd = pytest.importorskip("pandas") + + df = pd.DataFrame({0: [1, 2, 3], 1: [10, 20, 100]}) + + transformer = FunctionTransformer(feature_names_out=feature_names_out) + X_trans = transformer.fit_transform(df) + assert_array_equal(np.asarray(X_trans), np.asarray(df)) + + feature_names = transformer.get_feature_names_out() + assert list(X_trans.columns) == list(feature_names) + + +@pytest.mark.parametrize("dataframe_lib", ["pandas", "polars"]) +@pytest.mark.parametrize( + "feature_names_out", + ["one-to-one", lambda _, names: [f"{name}_log" for name in names]], +) +def test_function_transformer_error_column_inconsistent( + dataframe_lib, feature_names_out +): + """Check that we raise an error when `func` returns a dataframe with new + column names that become inconsistent with `get_feature_names_out`.""" + lib = pytest.importorskip(dataframe_lib) + + df = lib.DataFrame({"a": [1, 2, 3], "b": [10, 20, 100]}) + + def func(df): + if dataframe_lib == "pandas": + return df.rename(columns={"a": "c"}) + else: + return df.rename({"a": "c"}) + + transformer = FunctionTransformer(func=func, feature_names_out=feature_names_out) + err_msg = "The output generated by `func` have different column names" + with pytest.raises(ValueError, match=err_msg): + transformer.fit_transform(df).columns diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_polynomial.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_polynomial.py new file mode 100644 index 0000000000000000000000000000000000000000..b97500d43ef731b47fa5788a8bc9bd8ec47fd32a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_polynomial.py @@ -0,0 +1,1258 @@ +import sys + +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_equal +from scipy import sparse +from scipy.interpolate import BSpline +from scipy.sparse import random as sparse_random + +from sklearn.linear_model import LinearRegression +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import ( + KBinsDiscretizer, + PolynomialFeatures, + SplineTransformer, +) +from sklearn.preprocessing._csr_polynomial_expansion import ( + _calc_expanded_nnz, + _calc_total_nnz, + _get_sizeof_LARGEST_INT_t, +) +from sklearn.utils._testing import assert_array_almost_equal +from sklearn.utils.fixes import ( + CSC_CONTAINERS, + CSR_CONTAINERS, + parse_version, + sp_version, +) + + +@pytest.mark.parametrize("est", (PolynomialFeatures, SplineTransformer)) +def test_polynomial_and_spline_array_order(est): + """Test that output array has the given order.""" + X = np.arange(10).reshape(5, 2) + + def is_c_contiguous(a): + return np.isfortran(a.T) + + assert is_c_contiguous(est().fit_transform(X)) + assert is_c_contiguous(est(order="C").fit_transform(X)) + assert np.isfortran(est(order="F").fit_transform(X)) + + +@pytest.mark.parametrize( + "params, err_msg", + [ + ({"knots": [[1]]}, r"Number of knots, knots.shape\[0\], must be >= 2."), + ({"knots": [[1, 1], [2, 2]]}, r"knots.shape\[1\] == n_features is violated"), + ({"knots": [[1], [0]]}, "knots must be sorted without duplicates."), + ], +) +def test_spline_transformer_input_validation(params, err_msg): + """Test that we raise errors for invalid input in SplineTransformer.""" + X = [[1], [2]] + + with pytest.raises(ValueError, match=err_msg): + SplineTransformer(**params).fit(X) + + +@pytest.mark.parametrize("extrapolation", ["continue", "periodic"]) +def test_spline_transformer_integer_knots(extrapolation): + """Test that SplineTransformer accepts integer value knot positions.""" + X = np.arange(20).reshape(10, 2) + knots = [[0, 1], [1, 2], [5, 5], [11, 10], [12, 11]] + _ = SplineTransformer( + degree=3, knots=knots, extrapolation=extrapolation + ).fit_transform(X) + + +def test_spline_transformer_feature_names(): + """Test that SplineTransformer generates correct features name.""" + X = np.arange(20).reshape(10, 2) + splt = SplineTransformer(n_knots=3, degree=3, include_bias=True).fit(X) + feature_names = splt.get_feature_names_out() + assert_array_equal( + feature_names, + [ + "x0_sp_0", + "x0_sp_1", + "x0_sp_2", + "x0_sp_3", + "x0_sp_4", + "x1_sp_0", + "x1_sp_1", + "x1_sp_2", + "x1_sp_3", + "x1_sp_4", + ], + ) + + splt = SplineTransformer(n_knots=3, degree=3, include_bias=False).fit(X) + feature_names = splt.get_feature_names_out(["a", "b"]) + assert_array_equal( + feature_names, + [ + "a_sp_0", + "a_sp_1", + "a_sp_2", + "a_sp_3", + "b_sp_0", + "b_sp_1", + "b_sp_2", + "b_sp_3", + ], + ) + + +@pytest.mark.parametrize( + "extrapolation", + ["constant", "linear", "continue", "periodic"], +) +@pytest.mark.parametrize("degree", [2, 3]) +def test_split_transform_feature_names_extrapolation_degree(extrapolation, degree): + """Test feature names are correct for different extrapolations and degree. + + Non-regression test for gh-25292. + """ + X = np.arange(20).reshape(10, 2) + splt = SplineTransformer(degree=degree, extrapolation=extrapolation).fit(X) + feature_names = splt.get_feature_names_out(["a", "b"]) + assert len(feature_names) == splt.n_features_out_ + + X_trans = splt.transform(X) + assert X_trans.shape[1] == len(feature_names) + + +@pytest.mark.parametrize("degree", range(1, 5)) +@pytest.mark.parametrize("n_knots", range(3, 5)) +@pytest.mark.parametrize("knots", ["uniform", "quantile"]) +@pytest.mark.parametrize("extrapolation", ["constant", "periodic"]) +def test_spline_transformer_unity_decomposition(degree, n_knots, knots, extrapolation): + """Test that B-splines are indeed a decomposition of unity. + + Splines basis functions must sum up to 1 per row, if we stay in between boundaries. + """ + X = np.linspace(0, 1, 100)[:, None] + # make the boundaries 0 and 1 part of X_train, for sure. + X_train = np.r_[[[0]], X[::2, :], [[1]]] + X_test = X[1::2, :] + + if extrapolation == "periodic": + n_knots = n_knots + degree # periodic splines require degree < n_knots + + splt = SplineTransformer( + n_knots=n_knots, + degree=degree, + knots=knots, + include_bias=True, + extrapolation=extrapolation, + ) + splt.fit(X_train) + for X in [X_train, X_test]: + assert_allclose(np.sum(splt.transform(X), axis=1), 1) + + +@pytest.mark.parametrize(["bias", "intercept"], [(True, False), (False, True)]) +def test_spline_transformer_linear_regression(bias, intercept): + """Test that B-splines fit a sinusodial curve pretty well.""" + X = np.linspace(0, 10, 100)[:, None] + y = np.sin(X[:, 0]) + 2 # +2 to avoid the value 0 in assert_allclose + pipe = Pipeline( + steps=[ + ( + "spline", + SplineTransformer( + n_knots=15, + degree=3, + include_bias=bias, + extrapolation="constant", + ), + ), + ("ols", LinearRegression(fit_intercept=intercept)), + ] + ) + pipe.fit(X, y) + assert_allclose(pipe.predict(X), y, rtol=1e-3) + + +@pytest.mark.parametrize( + ["knots", "n_knots", "sample_weight", "expected_knots"], + [ + ("uniform", 3, None, np.array([[0, 2], [3, 8], [6, 14]])), + ( + "uniform", + 3, + np.array([0, 0, 1, 1, 0, 3, 1]), + np.array([[2, 2], [4, 8], [6, 14]]), + ), + ("uniform", 4, None, np.array([[0, 2], [2, 6], [4, 10], [6, 14]])), + ("quantile", 3, None, np.array([[0, 2], [3, 3], [6, 14]])), + ( + "quantile", + 3, + np.array([0, 0, 1, 1, 0, 3, 1]), + np.array([[2, 2], [5, 8], [6, 14]]), + ), + ], +) +def test_spline_transformer_get_base_knot_positions( + knots, n_knots, sample_weight, expected_knots +): + """Check the behaviour to find knot positions with and without sample_weight.""" + X = np.array([[0, 2], [0, 2], [2, 2], [3, 3], [4, 6], [5, 8], [6, 14]]) + base_knots = SplineTransformer._get_base_knot_positions( + X=X, knots=knots, n_knots=n_knots, sample_weight=sample_weight + ) + assert_allclose(base_knots, expected_knots) + + +@pytest.mark.parametrize(["bias", "intercept"], [(True, False), (False, True)]) +def test_spline_transformer_periodic_linear_regression(bias, intercept): + """Test that B-splines fit a periodic curve pretty well.""" + + # "+ 3" to avoid the value 0 in assert_allclose + def f(x): + return np.sin(2 * np.pi * x) - np.sin(8 * np.pi * x) + 3 + + X = np.linspace(0, 1, 101)[:, None] + pipe = Pipeline( + steps=[ + ( + "spline", + SplineTransformer( + n_knots=20, + degree=3, + include_bias=bias, + extrapolation="periodic", + ), + ), + ("ols", LinearRegression(fit_intercept=intercept)), + ] + ) + pipe.fit(X, f(X[:, 0])) + + # Generate larger array to check periodic extrapolation + X_ = np.linspace(-1, 2, 301)[:, None] + predictions = pipe.predict(X_) + assert_allclose(predictions, f(X_[:, 0]), atol=0.01, rtol=0.01) + assert_allclose(predictions[0:100], predictions[100:200], rtol=1e-3) + + +def test_spline_transformer_periodic_spline_backport(): + """Test that the backport of extrapolate="periodic" works correctly""" + X = np.linspace(-2, 3.5, 10)[:, None] + degree = 2 + + # Use periodic extrapolation backport in SplineTransformer + transformer = SplineTransformer( + degree=degree, extrapolation="periodic", knots=[[-1.0], [0.0], [1.0]] + ) + Xt = transformer.fit_transform(X) + + # Use periodic extrapolation in BSpline + coef = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 1.0]]) + spl = BSpline(np.arange(-3, 4), coef, degree, "periodic") + Xspl = spl(X[:, 0]) + assert_allclose(Xt, Xspl) + + +def test_spline_transformer_periodic_splines_periodicity(): + """Test if shifted knots result in the same transformation up to permutation.""" + X = np.linspace(0, 10, 101)[:, None] + + transformer_1 = SplineTransformer( + degree=3, + extrapolation="periodic", + knots=[[0.0], [1.0], [3.0], [4.0], [5.0], [8.0]], + ) + + transformer_2 = SplineTransformer( + degree=3, + extrapolation="periodic", + knots=[[1.0], [3.0], [4.0], [5.0], [8.0], [9.0]], + ) + + Xt_1 = transformer_1.fit_transform(X) + Xt_2 = transformer_2.fit_transform(X) + + assert_allclose(Xt_1, Xt_2[:, [4, 0, 1, 2, 3]]) + + +@pytest.mark.parametrize("degree", [3, 5]) +def test_spline_transformer_periodic_splines_smoothness(degree): + """Test that spline transformation is smooth at first / last knot.""" + X = np.linspace(-2, 10, 10_000)[:, None] + + transformer = SplineTransformer( + degree=degree, + extrapolation="periodic", + knots=[[0.0], [1.0], [3.0], [4.0], [5.0], [8.0]], + ) + Xt = transformer.fit_transform(X) + + delta = (X.max() - X.min()) / len(X) + tol = 10 * delta + + dXt = Xt + # We expect splines of degree `degree` to be (`degree`-1) times + # continuously differentiable. I.e. for d = 0, ..., `degree` - 1 the d-th + # derivative should be continuous. This is the case if the (d+1)-th + # numerical derivative is reasonably small (smaller than `tol` in absolute + # value). We thus compute d-th numeric derivatives for d = 1, ..., `degree` + # and compare them to `tol`. + # + # Note that the 0-th derivative is the function itself, such that we are + # also checking its continuity. + for d in range(1, degree + 1): + # Check continuity of the (d-1)-th derivative + diff = np.diff(dXt, axis=0) + assert np.abs(diff).max() < tol + # Compute d-th numeric derivative + dXt = diff / delta + + # As degree `degree` splines are not `degree` times continuously + # differentiable at the knots, the `degree + 1`-th numeric derivative + # should have spikes at the knots. + diff = np.diff(dXt, axis=0) + assert np.abs(diff).max() > 1 + + +@pytest.mark.parametrize(["bias", "intercept"], [(True, False), (False, True)]) +@pytest.mark.parametrize("degree", [1, 2, 3, 4, 5]) +def test_spline_transformer_extrapolation(bias, intercept, degree): + """Test that B-spline extrapolation works correctly.""" + # we use a straight line for that + X = np.linspace(-1, 1, 100)[:, None] + y = X.squeeze() + + # 'constant' + pipe = Pipeline( + [ + [ + "spline", + SplineTransformer( + n_knots=4, + degree=degree, + include_bias=bias, + extrapolation="constant", + ), + ], + ["ols", LinearRegression(fit_intercept=intercept)], + ] + ) + pipe.fit(X, y) + assert_allclose(pipe.predict([[-10], [5]]), [-1, 1]) + + # 'linear' + pipe = Pipeline( + [ + [ + "spline", + SplineTransformer( + n_knots=4, + degree=degree, + include_bias=bias, + extrapolation="linear", + ), + ], + ["ols", LinearRegression(fit_intercept=intercept)], + ] + ) + pipe.fit(X, y) + assert_allclose(pipe.predict([[-10], [5]]), [-10, 5]) + + # 'error' + splt = SplineTransformer( + n_knots=4, degree=degree, include_bias=bias, extrapolation="error" + ) + splt.fit(X) + msg = "X contains values beyond the limits of the knots" + with pytest.raises(ValueError, match=msg): + splt.transform([[-10]]) + with pytest.raises(ValueError, match=msg): + splt.transform([[5]]) + + +def test_spline_transformer_kbindiscretizer(): + """Test that a B-spline of degree=0 is equivalent to KBinsDiscretizer.""" + rng = np.random.RandomState(97531) + X = rng.randn(200).reshape(200, 1) + n_bins = 5 + n_knots = n_bins + 1 + + splt = SplineTransformer( + n_knots=n_knots, degree=0, knots="quantile", include_bias=True + ) + splines = splt.fit_transform(X) + + kbd = KBinsDiscretizer(n_bins=n_bins, encode="onehot-dense", strategy="quantile") + kbins = kbd.fit_transform(X) + + # Though they should be exactly equal, we test approximately with high + # accuracy. + assert_allclose(splines, kbins, rtol=1e-13) + + +@pytest.mark.skipif( + sp_version < parse_version("1.8.0"), + reason="The option `sparse_output` is available as of scipy 1.8.0", +) +@pytest.mark.parametrize("degree", range(1, 3)) +@pytest.mark.parametrize("knots", ["uniform", "quantile"]) +@pytest.mark.parametrize( + "extrapolation", ["error", "constant", "linear", "continue", "periodic"] +) +@pytest.mark.parametrize("include_bias", [False, True]) +def test_spline_transformer_sparse_output( + degree, knots, extrapolation, include_bias, global_random_seed +): + rng = np.random.RandomState(global_random_seed) + X = rng.randn(200).reshape(40, 5) + + splt_dense = SplineTransformer( + degree=degree, + knots=knots, + extrapolation=extrapolation, + include_bias=include_bias, + sparse_output=False, + ) + splt_sparse = SplineTransformer( + degree=degree, + knots=knots, + extrapolation=extrapolation, + include_bias=include_bias, + sparse_output=True, + ) + + splt_dense.fit(X) + splt_sparse.fit(X) + + X_trans_sparse = splt_sparse.transform(X) + X_trans_dense = splt_dense.transform(X) + assert sparse.issparse(X_trans_sparse) and X_trans_sparse.format == "csr" + assert_allclose(X_trans_dense, X_trans_sparse.toarray()) + + # extrapolation regime + X_min = np.amin(X, axis=0) + X_max = np.amax(X, axis=0) + X_extra = np.r_[ + np.linspace(X_min - 5, X_min, 10), np.linspace(X_max, X_max + 5, 10) + ] + if extrapolation == "error": + msg = "X contains values beyond the limits of the knots" + with pytest.raises(ValueError, match=msg): + splt_dense.transform(X_extra) + msg = "Out of bounds" + with pytest.raises(ValueError, match=msg): + splt_sparse.transform(X_extra) + else: + assert_allclose( + splt_dense.transform(X_extra), splt_sparse.transform(X_extra).toarray() + ) + + +@pytest.mark.skipif( + sp_version >= parse_version("1.8.0"), + reason="The option `sparse_output` is available as of scipy 1.8.0", +) +def test_spline_transformer_sparse_output_raise_error_for_old_scipy(): + """Test that SplineTransformer with sparse=True raises for scipy<1.8.0.""" + X = [[1], [2]] + with pytest.raises(ValueError, match="scipy>=1.8.0"): + SplineTransformer(sparse_output=True).fit(X) + + +@pytest.mark.parametrize("n_knots", [5, 10]) +@pytest.mark.parametrize("include_bias", [True, False]) +@pytest.mark.parametrize("degree", [3, 4]) +@pytest.mark.parametrize( + "extrapolation", ["error", "constant", "linear", "continue", "periodic"] +) +@pytest.mark.parametrize("sparse_output", [False, True]) +def test_spline_transformer_n_features_out( + n_knots, include_bias, degree, extrapolation, sparse_output +): + """Test that transform results in n_features_out_ features.""" + if sparse_output and sp_version < parse_version("1.8.0"): + pytest.skip("The option `sparse_output` is available as of scipy 1.8.0") + + splt = SplineTransformer( + n_knots=n_knots, + degree=degree, + include_bias=include_bias, + extrapolation=extrapolation, + sparse_output=sparse_output, + ) + X = np.linspace(0, 1, 10)[:, None] + splt.fit(X) + + assert splt.transform(X).shape[1] == splt.n_features_out_ + + +@pytest.mark.parametrize( + "params, err_msg", + [ + ({"degree": (-1, 2)}, r"degree=\(min_degree, max_degree\) must"), + ({"degree": (0, 1.5)}, r"degree=\(min_degree, max_degree\) must"), + ({"degree": (3, 2)}, r"degree=\(min_degree, max_degree\) must"), + ({"degree": (1, 2, 3)}, r"int or tuple \(min_degree, max_degree\)"), + ], +) +def test_polynomial_features_input_validation(params, err_msg): + """Test that we raise errors for invalid input in PolynomialFeatures.""" + X = [[1], [2]] + + with pytest.raises(ValueError, match=err_msg): + PolynomialFeatures(**params).fit(X) + + +@pytest.fixture() +def single_feature_degree3(): + X = np.arange(6)[:, np.newaxis] + P = np.hstack([np.ones_like(X), X, X**2, X**3]) + return X, P + + +@pytest.mark.parametrize( + "degree, include_bias, interaction_only, indices", + [ + (3, True, False, slice(None, None)), + (3, False, False, slice(1, None)), + (3, True, True, [0, 1]), + (3, False, True, [1]), + ((2, 3), True, False, [0, 2, 3]), + ((2, 3), False, False, [2, 3]), + ((2, 3), True, True, [0]), + ((2, 3), False, True, []), + ], +) +@pytest.mark.parametrize("X_container", [None] + CSR_CONTAINERS + CSC_CONTAINERS) +def test_polynomial_features_one_feature( + single_feature_degree3, + degree, + include_bias, + interaction_only, + indices, + X_container, +): + """Test PolynomialFeatures on single feature up to degree 3.""" + X, P = single_feature_degree3 + if X_container is not None: + X = X_container(X) + tf = PolynomialFeatures( + degree=degree, include_bias=include_bias, interaction_only=interaction_only + ).fit(X) + out = tf.transform(X) + if X_container is not None: + out = out.toarray() + assert_allclose(out, P[:, indices]) + if tf.n_output_features_ > 0: + assert tf.powers_.shape == (tf.n_output_features_, tf.n_features_in_) + + +@pytest.fixture() +def two_features_degree3(): + X = np.arange(6).reshape((3, 2)) + x1 = X[:, :1] + x2 = X[:, 1:] + P = np.hstack( + [ + x1**0 * x2**0, # 0 + x1**1 * x2**0, # 1 + x1**0 * x2**1, # 2 + x1**2 * x2**0, # 3 + x1**1 * x2**1, # 4 + x1**0 * x2**2, # 5 + x1**3 * x2**0, # 6 + x1**2 * x2**1, # 7 + x1**1 * x2**2, # 8 + x1**0 * x2**3, # 9 + ] + ) + return X, P + + +@pytest.mark.parametrize( + "degree, include_bias, interaction_only, indices", + [ + (2, True, False, slice(0, 6)), + (2, False, False, slice(1, 6)), + (2, True, True, [0, 1, 2, 4]), + (2, False, True, [1, 2, 4]), + ((2, 2), True, False, [0, 3, 4, 5]), + ((2, 2), False, False, [3, 4, 5]), + ((2, 2), True, True, [0, 4]), + ((2, 2), False, True, [4]), + (3, True, False, slice(None, None)), + (3, False, False, slice(1, None)), + (3, True, True, [0, 1, 2, 4]), + (3, False, True, [1, 2, 4]), + ((2, 3), True, False, [0, 3, 4, 5, 6, 7, 8, 9]), + ((2, 3), False, False, slice(3, None)), + ((2, 3), True, True, [0, 4]), + ((2, 3), False, True, [4]), + ((3, 3), True, False, [0, 6, 7, 8, 9]), + ((3, 3), False, False, [6, 7, 8, 9]), + ((3, 3), True, True, [0]), + ((3, 3), False, True, []), # would need 3 input features + ], +) +@pytest.mark.parametrize("X_container", [None] + CSR_CONTAINERS + CSC_CONTAINERS) +def test_polynomial_features_two_features( + two_features_degree3, + degree, + include_bias, + interaction_only, + indices, + X_container, +): + """Test PolynomialFeatures on 2 features up to degree 3.""" + X, P = two_features_degree3 + if X_container is not None: + X = X_container(X) + tf = PolynomialFeatures( + degree=degree, include_bias=include_bias, interaction_only=interaction_only + ).fit(X) + out = tf.transform(X) + if X_container is not None: + out = out.toarray() + assert_allclose(out, P[:, indices]) + if tf.n_output_features_ > 0: + assert tf.powers_.shape == (tf.n_output_features_, tf.n_features_in_) + + +def test_polynomial_feature_names(): + X = np.arange(30).reshape(10, 3) + poly = PolynomialFeatures(degree=2, include_bias=True).fit(X) + feature_names = poly.get_feature_names_out() + assert_array_equal( + ["1", "x0", "x1", "x2", "x0^2", "x0 x1", "x0 x2", "x1^2", "x1 x2", "x2^2"], + feature_names, + ) + assert len(feature_names) == poly.transform(X).shape[1] + + poly = PolynomialFeatures(degree=3, include_bias=False).fit(X) + feature_names = poly.get_feature_names_out(["a", "b", "c"]) + assert_array_equal( + [ + "a", + "b", + "c", + "a^2", + "a b", + "a c", + "b^2", + "b c", + "c^2", + "a^3", + "a^2 b", + "a^2 c", + "a b^2", + "a b c", + "a c^2", + "b^3", + "b^2 c", + "b c^2", + "c^3", + ], + feature_names, + ) + assert len(feature_names) == poly.transform(X).shape[1] + + poly = PolynomialFeatures(degree=(2, 3), include_bias=False).fit(X) + feature_names = poly.get_feature_names_out(["a", "b", "c"]) + assert_array_equal( + [ + "a^2", + "a b", + "a c", + "b^2", + "b c", + "c^2", + "a^3", + "a^2 b", + "a^2 c", + "a b^2", + "a b c", + "a c^2", + "b^3", + "b^2 c", + "b c^2", + "c^3", + ], + feature_names, + ) + assert len(feature_names) == poly.transform(X).shape[1] + + poly = PolynomialFeatures( + degree=(3, 3), include_bias=True, interaction_only=True + ).fit(X) + feature_names = poly.get_feature_names_out(["a", "b", "c"]) + assert_array_equal(["1", "a b c"], feature_names) + assert len(feature_names) == poly.transform(X).shape[1] + + # test some unicode + poly = PolynomialFeatures(degree=1, include_bias=True).fit(X) + feature_names = poly.get_feature_names_out(["\u0001F40D", "\u262e", "\u05d0"]) + assert_array_equal(["1", "\u0001F40D", "\u262e", "\u05d0"], feature_names) + + +@pytest.mark.parametrize( + ["deg", "include_bias", "interaction_only", "dtype"], + [ + (1, True, False, int), + (2, True, False, int), + (2, True, False, np.float32), + (2, True, False, np.float64), + (3, False, False, np.float64), + (3, False, True, np.float64), + (4, False, False, np.float64), + (4, False, True, np.float64), + ], +) +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_polynomial_features_csc_X( + deg, include_bias, interaction_only, dtype, csc_container +): + rng = np.random.RandomState(0) + X = rng.randint(0, 2, (100, 2)) + X_csc = csc_container(X) + + est = PolynomialFeatures( + deg, include_bias=include_bias, interaction_only=interaction_only + ) + Xt_csc = est.fit_transform(X_csc.astype(dtype)) + Xt_dense = est.fit_transform(X.astype(dtype)) + + assert sparse.issparse(Xt_csc) and Xt_csc.format == "csc" + assert Xt_csc.dtype == Xt_dense.dtype + assert_array_almost_equal(Xt_csc.toarray(), Xt_dense) + + +@pytest.mark.parametrize( + ["deg", "include_bias", "interaction_only", "dtype"], + [ + (1, True, False, int), + (2, True, False, int), + (2, True, False, np.float32), + (2, True, False, np.float64), + (3, False, False, np.float64), + (3, False, True, np.float64), + ], +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_polynomial_features_csr_X( + deg, include_bias, interaction_only, dtype, csr_container +): + rng = np.random.RandomState(0) + X = rng.randint(0, 2, (100, 2)) + X_csr = csr_container(X) + + est = PolynomialFeatures( + deg, include_bias=include_bias, interaction_only=interaction_only + ) + Xt_csr = est.fit_transform(X_csr.astype(dtype)) + Xt_dense = est.fit_transform(X.astype(dtype, copy=False)) + + assert sparse.issparse(Xt_csr) and Xt_csr.format == "csr" + assert Xt_csr.dtype == Xt_dense.dtype + assert_array_almost_equal(Xt_csr.toarray(), Xt_dense) + + +@pytest.mark.parametrize("n_features", [1, 4, 5]) +@pytest.mark.parametrize( + "min_degree, max_degree", [(0, 1), (0, 2), (1, 3), (0, 4), (3, 4)] +) +@pytest.mark.parametrize("interaction_only", [True, False]) +@pytest.mark.parametrize("include_bias", [True, False]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_num_combinations( + n_features, min_degree, max_degree, interaction_only, include_bias, csr_container +): + """ + Test that n_output_features_ is calculated correctly. + """ + x = csr_container(([1], ([0], [n_features - 1]))) + est = PolynomialFeatures( + degree=max_degree, + interaction_only=interaction_only, + include_bias=include_bias, + ) + est.fit(x) + num_combos = est.n_output_features_ + + combos = PolynomialFeatures._combinations( + n_features=n_features, + min_degree=0, + max_degree=max_degree, + interaction_only=interaction_only, + include_bias=include_bias, + ) + assert num_combos == sum([1 for _ in combos]) + + +@pytest.mark.parametrize( + ["deg", "include_bias", "interaction_only", "dtype"], + [ + (2, True, False, np.float32), + (2, True, False, np.float64), + (3, False, False, np.float64), + (3, False, True, np.float64), + ], +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_polynomial_features_csr_X_floats( + deg, include_bias, interaction_only, dtype, csr_container +): + X_csr = csr_container(sparse_random(1000, 10, 0.5, random_state=0)) + X = X_csr.toarray() + + est = PolynomialFeatures( + deg, include_bias=include_bias, interaction_only=interaction_only + ) + Xt_csr = est.fit_transform(X_csr.astype(dtype)) + Xt_dense = est.fit_transform(X.astype(dtype)) + + assert sparse.issparse(Xt_csr) and Xt_csr.format == "csr" + assert Xt_csr.dtype == Xt_dense.dtype + assert_array_almost_equal(Xt_csr.toarray(), Xt_dense) + + +@pytest.mark.parametrize( + ["zero_row_index", "deg", "interaction_only"], + [ + (0, 2, True), + (1, 2, True), + (2, 2, True), + (0, 3, True), + (1, 3, True), + (2, 3, True), + (0, 2, False), + (1, 2, False), + (2, 2, False), + (0, 3, False), + (1, 3, False), + (2, 3, False), + ], +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_polynomial_features_csr_X_zero_row( + zero_row_index, deg, interaction_only, csr_container +): + X_csr = csr_container(sparse_random(3, 10, 1.0, random_state=0)) + X_csr[zero_row_index, :] = 0.0 + X = X_csr.toarray() + + est = PolynomialFeatures(deg, include_bias=False, interaction_only=interaction_only) + Xt_csr = est.fit_transform(X_csr) + Xt_dense = est.fit_transform(X) + + assert sparse.issparse(Xt_csr) and Xt_csr.format == "csr" + assert Xt_csr.dtype == Xt_dense.dtype + assert_array_almost_equal(Xt_csr.toarray(), Xt_dense) + + +# This degree should always be one more than the highest degree supported by +# _csr_expansion. +@pytest.mark.parametrize( + ["include_bias", "interaction_only"], + [(True, True), (True, False), (False, True), (False, False)], +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_polynomial_features_csr_X_degree_4( + include_bias, interaction_only, csr_container +): + X_csr = csr_container(sparse_random(1000, 10, 0.5, random_state=0)) + X = X_csr.toarray() + + est = PolynomialFeatures( + 4, include_bias=include_bias, interaction_only=interaction_only + ) + Xt_csr = est.fit_transform(X_csr) + Xt_dense = est.fit_transform(X) + + assert sparse.issparse(Xt_csr) and Xt_csr.format == "csr" + assert Xt_csr.dtype == Xt_dense.dtype + assert_array_almost_equal(Xt_csr.toarray(), Xt_dense) + + +@pytest.mark.parametrize( + ["deg", "dim", "interaction_only"], + [ + (2, 1, True), + (2, 2, True), + (3, 1, True), + (3, 2, True), + (3, 3, True), + (2, 1, False), + (2, 2, False), + (3, 1, False), + (3, 2, False), + (3, 3, False), + ], +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_polynomial_features_csr_X_dim_edges(deg, dim, interaction_only, csr_container): + X_csr = csr_container(sparse_random(1000, dim, 0.5, random_state=0)) + X = X_csr.toarray() + + est = PolynomialFeatures(deg, interaction_only=interaction_only) + Xt_csr = est.fit_transform(X_csr) + Xt_dense = est.fit_transform(X) + + assert sparse.issparse(Xt_csr) and Xt_csr.format == "csr" + assert Xt_csr.dtype == Xt_dense.dtype + assert_array_almost_equal(Xt_csr.toarray(), Xt_dense) + + +@pytest.mark.parametrize("interaction_only", [True, False]) +@pytest.mark.parametrize("include_bias", [True, False]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_csr_polynomial_expansion_index_overflow_non_regression( + interaction_only, include_bias, csr_container +): + """Check the automatic index dtype promotion to `np.int64` when needed. + + This ensures that sufficiently large input configurations get + properly promoted to use `np.int64` for index and indptr representation + while preserving data integrity. Non-regression test for gh-16803. + + Note that this is only possible for Python runtimes with a 64 bit address + space. On 32 bit platforms, a `ValueError` is raised instead. + """ + + def degree_2_calc(d, i, j): + if interaction_only: + return d * i - (i**2 + 3 * i) // 2 - 1 + j + else: + return d * i - (i**2 + i) // 2 + j + + n_samples = 13 + n_features = 120001 + data_dtype = np.float32 + data = np.arange(1, 5, dtype=np.int64) + row = np.array([n_samples - 2, n_samples - 2, n_samples - 1, n_samples - 1]) + # An int64 dtype is required to avoid overflow error on Windows within the + # `degree_2_calc` function. + col = np.array( + [n_features - 2, n_features - 1, n_features - 2, n_features - 1], dtype=np.int64 + ) + X = csr_container( + (data, (row, col)), + shape=(n_samples, n_features), + dtype=data_dtype, + ) + pf = PolynomialFeatures( + interaction_only=interaction_only, include_bias=include_bias, degree=2 + ) + + # Calculate the number of combinations a-priori, and if needed check for + # the correct ValueError and terminate the test early. + num_combinations = pf._num_combinations( + n_features=n_features, + min_degree=0, + max_degree=2, + interaction_only=pf.interaction_only, + include_bias=pf.include_bias, + ) + if num_combinations > np.iinfo(np.intp).max: + msg = ( + r"The output that would result from the current configuration would have" + r" \d* features which is too large to be indexed" + ) + with pytest.raises(ValueError, match=msg): + pf.fit(X) + return + X_trans = pf.fit_transform(X) + row_nonzero, col_nonzero = X_trans.nonzero() + n_degree_1_features_out = n_features + include_bias + max_degree_2_idx = ( + degree_2_calc(n_features, col[int(not interaction_only)], col[1]) + + n_degree_1_features_out + ) + + # Account for bias of all samples except last one which will be handled + # separately since there are distinct data values before it + data_target = [1] * (n_samples - 2) if include_bias else [] + col_nonzero_target = [0] * (n_samples - 2) if include_bias else [] + + for i in range(2): + x = data[2 * i] + y = data[2 * i + 1] + x_idx = col[2 * i] + y_idx = col[2 * i + 1] + if include_bias: + data_target.append(1) + col_nonzero_target.append(0) + data_target.extend([x, y]) + col_nonzero_target.extend( + [x_idx + int(include_bias), y_idx + int(include_bias)] + ) + if not interaction_only: + data_target.extend([x * x, x * y, y * y]) + col_nonzero_target.extend( + [ + degree_2_calc(n_features, x_idx, x_idx) + n_degree_1_features_out, + degree_2_calc(n_features, x_idx, y_idx) + n_degree_1_features_out, + degree_2_calc(n_features, y_idx, y_idx) + n_degree_1_features_out, + ] + ) + else: + data_target.extend([x * y]) + col_nonzero_target.append( + degree_2_calc(n_features, x_idx, y_idx) + n_degree_1_features_out + ) + + nnz_per_row = int(include_bias) + 3 + 2 * int(not interaction_only) + + assert pf.n_output_features_ == max_degree_2_idx + 1 + assert X_trans.dtype == data_dtype + assert X_trans.shape == (n_samples, max_degree_2_idx + 1) + assert X_trans.indptr.dtype == X_trans.indices.dtype == np.int64 + # Ensure that dtype promotion was actually required: + assert X_trans.indices.max() > np.iinfo(np.int32).max + + row_nonzero_target = list(range(n_samples - 2)) if include_bias else [] + row_nonzero_target.extend( + [n_samples - 2] * nnz_per_row + [n_samples - 1] * nnz_per_row + ) + + assert_allclose(X_trans.data, data_target) + assert_array_equal(row_nonzero, row_nonzero_target) + assert_array_equal(col_nonzero, col_nonzero_target) + + +@pytest.mark.parametrize( + "degree, n_features", + [ + # Needs promotion to int64 when interaction_only=False + (2, 65535), + (3, 2344), + # This guarantees that the intermediate operation when calculating + # output columns would overflow a C-long, hence checks that python- + # longs are being used. + (2, int(np.sqrt(np.iinfo(np.int64).max) + 1)), + (3, 65535), + # This case tests the second clause of the overflow check which + # takes into account the value of `n_features` itself. + (2, int(np.sqrt(np.iinfo(np.int64).max))), + ], +) +@pytest.mark.parametrize("interaction_only", [True, False]) +@pytest.mark.parametrize("include_bias", [True, False]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_csr_polynomial_expansion_index_overflow( + degree, n_features, interaction_only, include_bias, csr_container +): + """Tests known edge-cases to the dtype promotion strategy and custom + Cython code, including a current bug in the upstream + `scipy.sparse.hstack`. + """ + data = [1.0] + row = [0] + col = [n_features - 1] + + # First degree index + expected_indices = [ + n_features - 1 + int(include_bias), + ] + # Second degree index + expected_indices.append(n_features * (n_features + 1) // 2 + expected_indices[0]) + # Third degree index + expected_indices.append( + n_features * (n_features + 1) * (n_features + 2) // 6 + expected_indices[1] + ) + + X = csr_container((data, (row, col))) + pf = PolynomialFeatures( + interaction_only=interaction_only, include_bias=include_bias, degree=degree + ) + + # Calculate the number of combinations a-priori, and if needed check for + # the correct ValueError and terminate the test early. + num_combinations = pf._num_combinations( + n_features=n_features, + min_degree=0, + max_degree=degree, + interaction_only=pf.interaction_only, + include_bias=pf.include_bias, + ) + if num_combinations > np.iinfo(np.intp).max: + msg = ( + r"The output that would result from the current configuration would have" + r" \d* features which is too large to be indexed" + ) + with pytest.raises(ValueError, match=msg): + pf.fit(X) + return + + # In SciPy < 1.8, a bug occurs when an intermediate matrix in + # `to_stack` in `hstack` fits within int32 however would require int64 when + # combined with all previous matrices in `to_stack`. + if sp_version < parse_version("1.8.0"): + has_bug = False + max_int32 = np.iinfo(np.int32).max + cumulative_size = n_features + include_bias + for deg in range(2, degree + 1): + max_indptr = _calc_total_nnz(X.indptr, interaction_only, deg) + max_indices = _calc_expanded_nnz(n_features, interaction_only, deg) - 1 + cumulative_size += max_indices + 1 + needs_int64 = max(max_indices, max_indptr) > max_int32 + has_bug |= not needs_int64 and cumulative_size > max_int32 + if has_bug: + msg = r"In scipy versions `<1.8.0`, the function `scipy.sparse.hstack`" + with pytest.raises(ValueError, match=msg): + X_trans = pf.fit_transform(X) + return + + # When `n_features>=65535`, `scipy.sparse.hstack` may not use the right + # dtype for representing indices and indptr if `n_features` is still + # small enough so that each block matrix's indices and indptr arrays + # can be represented with `np.int32`. We test `n_features==65535` + # since it is guaranteed to run into this bug. + if ( + sp_version < parse_version("1.9.2") + and n_features == 65535 + and degree == 2 + and not interaction_only + ): # pragma: no cover + msg = r"In scipy versions `<1.9.2`, the function `scipy.sparse.hstack`" + with pytest.raises(ValueError, match=msg): + X_trans = pf.fit_transform(X) + return + X_trans = pf.fit_transform(X) + + expected_dtype = np.int64 if num_combinations > np.iinfo(np.int32).max else np.int32 + # Terms higher than first degree + non_bias_terms = 1 + (degree - 1) * int(not interaction_only) + expected_nnz = int(include_bias) + non_bias_terms + assert X_trans.dtype == X.dtype + assert X_trans.shape == (1, pf.n_output_features_) + assert X_trans.indptr.dtype == X_trans.indices.dtype == expected_dtype + assert X_trans.nnz == expected_nnz + + if include_bias: + assert X_trans[0, 0] == pytest.approx(1.0) + for idx in range(non_bias_terms): + assert X_trans[0, expected_indices[idx]] == pytest.approx(1.0) + + offset = interaction_only * n_features + if degree == 3: + offset *= 1 + n_features + assert pf.n_output_features_ == expected_indices[degree - 1] + 1 - offset + + +@pytest.mark.parametrize("interaction_only", [True, False]) +@pytest.mark.parametrize("include_bias", [True, False]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_csr_polynomial_expansion_too_large_to_index( + interaction_only, include_bias, csr_container +): + n_features = np.iinfo(np.int64).max // 2 + data = [1.0] + row = [0] + col = [n_features - 1] + X = csr_container((data, (row, col))) + pf = PolynomialFeatures( + interaction_only=interaction_only, include_bias=include_bias, degree=(2, 2) + ) + msg = ( + r"The output that would result from the current configuration would have \d*" + r" features which is too large to be indexed" + ) + with pytest.raises(ValueError, match=msg): + pf.fit(X) + with pytest.raises(ValueError, match=msg): + pf.fit_transform(X) + + +@pytest.mark.parametrize("sparse_container", CSR_CONTAINERS + CSC_CONTAINERS) +def test_polynomial_features_behaviour_on_zero_degree(sparse_container): + """Check that PolynomialFeatures raises error when degree=0 and include_bias=False, + and output a single constant column when include_bias=True + """ + X = np.ones((10, 2)) + poly = PolynomialFeatures(degree=0, include_bias=False) + err_msg = ( + "Setting degree to zero and include_bias to False would result in" + " an empty output array." + ) + with pytest.raises(ValueError, match=err_msg): + poly.fit_transform(X) + + poly = PolynomialFeatures(degree=(0, 0), include_bias=False) + err_msg = ( + "Setting both min_degree and max_degree to zero and include_bias to" + " False would result in an empty output array." + ) + with pytest.raises(ValueError, match=err_msg): + poly.fit_transform(X) + + for _X in [X, sparse_container(X)]: + poly = PolynomialFeatures(degree=0, include_bias=True) + output = poly.fit_transform(_X) + # convert to dense array if needed + if sparse.issparse(output): + output = output.toarray() + assert_array_equal(output, np.ones((X.shape[0], 1))) + + +def test_sizeof_LARGEST_INT_t(): + # On Windows, scikit-learn is typically compiled with MSVC that + # does not support int128 arithmetic (at the time of writing): + # https://stackoverflow.com/a/6761962/163740 + if sys.platform == "win32" or ( + sys.maxsize <= 2**32 and sys.platform != "emscripten" + ): + expected_size = 8 + else: + expected_size = 16 + + assert _get_sizeof_LARGEST_INT_t() == expected_size + + +@pytest.mark.xfail( + sys.platform == "win32", + reason=( + "On Windows, scikit-learn is typically compiled with MSVC that does not support" + " int128 arithmetic (at the time of writing)" + ), + run=True, +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_csr_polynomial_expansion_windows_fail(csr_container): + # Minimum needed to ensure integer overflow occurs while guaranteeing an + # int64-indexable output. + n_features = int(np.iinfo(np.int64).max ** (1 / 3) + 3) + data = [1.0] + row = [0] + col = [n_features - 1] + + # First degree index + expected_indices = [ + n_features - 1, + ] + # Second degree index + expected_indices.append( + int(n_features * (n_features + 1) // 2 + expected_indices[0]) + ) + # Third degree index + expected_indices.append( + int(n_features * (n_features + 1) * (n_features + 2) // 6 + expected_indices[1]) + ) + + X = csr_container((data, (row, col))) + pf = PolynomialFeatures(interaction_only=False, include_bias=False, degree=3) + if sys.maxsize <= 2**32: + msg = ( + r"The output that would result from the current configuration would" + r" have \d*" + r" features which is too large to be indexed" + ) + with pytest.raises(ValueError, match=msg): + pf.fit_transform(X) + else: + X_trans = pf.fit_transform(X) + for idx in range(3): + assert X_trans[0, expected_indices[idx]] == pytest.approx(1.0) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_target_encoder.py b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_target_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..81b0f32d04d685883f8b2cad08e7df02bcc77edd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/preprocessing/tests/test_target_encoder.py @@ -0,0 +1,716 @@ +import re + +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_equal + +from sklearn.ensemble import RandomForestRegressor +from sklearn.linear_model import Ridge +from sklearn.model_selection import ( + KFold, + ShuffleSplit, + StratifiedKFold, + cross_val_score, + train_test_split, +) +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import ( + KBinsDiscretizer, + LabelBinarizer, + LabelEncoder, + TargetEncoder, +) + + +def _encode_target(X_ordinal, y_numeric, n_categories, smooth): + """Simple Python implementation of target encoding.""" + cur_encodings = np.zeros(n_categories, dtype=np.float64) + y_mean = np.mean(y_numeric) + + if smooth == "auto": + y_variance = np.var(y_numeric) + for c in range(n_categories): + y_subset = y_numeric[X_ordinal == c] + n_i = y_subset.shape[0] + + if n_i == 0: + cur_encodings[c] = y_mean + continue + + y_subset_variance = np.var(y_subset) + m = y_subset_variance / y_variance + lambda_ = n_i / (n_i + m) + + cur_encodings[c] = lambda_ * np.mean(y_subset) + (1 - lambda_) * y_mean + return cur_encodings + else: # float + for c in range(n_categories): + y_subset = y_numeric[X_ordinal == c] + current_sum = np.sum(y_subset) + y_mean * smooth + current_cnt = y_subset.shape[0] + smooth + cur_encodings[c] = current_sum / current_cnt + return cur_encodings + + +@pytest.mark.parametrize( + "categories, unknown_value", + [ + ([np.array([0, 1, 2], dtype=np.int64)], 4), + ([np.array([1.0, 3.0, np.nan], dtype=np.float64)], 6.0), + ([np.array(["cat", "dog", "snake"], dtype=object)], "bear"), + ("auto", 3), + ], +) +@pytest.mark.parametrize("smooth", [5.0, "auto"]) +@pytest.mark.parametrize("target_type", ["binary", "continuous"]) +def test_encoding(categories, unknown_value, global_random_seed, smooth, target_type): + """Check encoding for binary and continuous targets. + + Compare the values returned by `TargetEncoder.fit_transform` against the + expected encodings for cv splits from a naive reference Python + implementation in _encode_target. + """ + + n_categories = 3 + X_train_int_array = np.array([[0] * 20 + [1] * 30 + [2] * 40], dtype=np.int64).T + X_test_int_array = np.array([[0, 1, 2]], dtype=np.int64).T + n_samples = X_train_int_array.shape[0] + + if categories == "auto": + X_train = X_train_int_array + X_test = X_test_int_array + else: + X_train = categories[0][X_train_int_array] + X_test = categories[0][X_test_int_array] + + X_test = np.concatenate((X_test, [[unknown_value]])) + + data_rng = np.random.RandomState(global_random_seed) + n_splits = 3 + if target_type == "binary": + y_numeric = data_rng.randint(low=0, high=2, size=n_samples) + target_names = np.array(["cat", "dog"], dtype=object) + y_train = target_names[y_numeric] + + else: + assert target_type == "continuous" + y_numeric = data_rng.uniform(low=-10, high=20, size=n_samples) + y_train = y_numeric + + shuffled_idx = data_rng.permutation(n_samples) + X_train_int_array = X_train_int_array[shuffled_idx] + X_train = X_train[shuffled_idx] + y_train = y_train[shuffled_idx] + y_numeric = y_numeric[shuffled_idx] + + # Define our CV splitting strategy + if target_type == "binary": + cv = StratifiedKFold( + n_splits=n_splits, random_state=global_random_seed, shuffle=True + ) + else: + cv = KFold(n_splits=n_splits, random_state=global_random_seed, shuffle=True) + + # Compute the expected values using our reference Python implementation of + # target encoding: + expected_X_fit_transform = np.empty_like(X_train_int_array, dtype=np.float64) + + for train_idx, test_idx in cv.split(X_train_int_array, y_train): + X_, y_ = X_train_int_array[train_idx, 0], y_numeric[train_idx] + cur_encodings = _encode_target(X_, y_, n_categories, smooth) + expected_X_fit_transform[test_idx, 0] = cur_encodings[ + X_train_int_array[test_idx, 0] + ] + + # Check that we can obtain the same encodings by calling `fit_transform` on + # the estimator with the same CV parameters: + target_encoder = TargetEncoder( + smooth=smooth, + categories=categories, + cv=n_splits, + random_state=global_random_seed, + ) + + X_fit_transform = target_encoder.fit_transform(X_train, y_train) + + assert target_encoder.target_type_ == target_type + assert_allclose(X_fit_transform, expected_X_fit_transform) + assert len(target_encoder.encodings_) == 1 + if target_type == "binary": + assert_array_equal(target_encoder.classes_, target_names) + else: + assert target_encoder.classes_ is None + + # compute encodings for all data to validate `transform` + y_mean = np.mean(y_numeric) + expected_encodings = _encode_target( + X_train_int_array[:, 0], y_numeric, n_categories, smooth + ) + assert_allclose(target_encoder.encodings_[0], expected_encodings) + assert target_encoder.target_mean_ == pytest.approx(y_mean) + + # Transform on test data, the last value is unknown so it is encoded as the target + # mean + expected_X_test_transform = np.concatenate( + (expected_encodings, np.array([y_mean])) + ).reshape(-1, 1) + + X_test_transform = target_encoder.transform(X_test) + assert_allclose(X_test_transform, expected_X_test_transform) + + +@pytest.mark.parametrize( + "categories, unknown_values", + [ + ([np.array([0, 1, 2], dtype=np.int64)], "auto"), + ([np.array(["cat", "dog", "snake"], dtype=object)], ["bear", "rabbit"]), + ], +) +@pytest.mark.parametrize( + "target_labels", [np.array([1, 2, 3]), np.array(["a", "b", "c"])] +) +@pytest.mark.parametrize("smooth", [5.0, "auto"]) +def test_encoding_multiclass( + global_random_seed, categories, unknown_values, target_labels, smooth +): + """Check encoding for multiclass targets.""" + rng = np.random.RandomState(global_random_seed) + + n_samples = 80 + n_features = 2 + feat_1_int = np.array(rng.randint(low=0, high=2, size=n_samples)) + feat_2_int = np.array(rng.randint(low=0, high=3, size=n_samples)) + feat_1 = categories[0][feat_1_int] + feat_2 = categories[0][feat_2_int] + X_train = np.column_stack((feat_1, feat_2)) + X_train_int = np.column_stack((feat_1_int, feat_2_int)) + categories_ = [[0, 1], [0, 1, 2]] + + n_classes = 3 + y_train_int = np.array(rng.randint(low=0, high=n_classes, size=n_samples)) + y_train = target_labels[y_train_int] + y_train_enc = LabelBinarizer().fit_transform(y_train) + + n_splits = 3 + cv = StratifiedKFold( + n_splits=n_splits, random_state=global_random_seed, shuffle=True + ) + + # Manually compute encodings for cv splits to validate `fit_transform` + expected_X_fit_transform = np.empty( + (X_train_int.shape[0], X_train_int.shape[1] * n_classes), + dtype=np.float64, + ) + for f_idx, cats in enumerate(categories_): + for c_idx in range(n_classes): + for train_idx, test_idx in cv.split(X_train, y_train): + y_class = y_train_enc[:, c_idx] + X_, y_ = X_train_int[train_idx, f_idx], y_class[train_idx] + current_encoding = _encode_target(X_, y_, len(cats), smooth) + # f_idx: 0, 0, 0, 1, 1, 1 + # c_idx: 0, 1, 2, 0, 1, 2 + # exp_idx: 0, 1, 2, 3, 4, 5 + exp_idx = c_idx + (f_idx * n_classes) + expected_X_fit_transform[test_idx, exp_idx] = current_encoding[ + X_train_int[test_idx, f_idx] + ] + + target_encoder = TargetEncoder( + smooth=smooth, + cv=n_splits, + random_state=global_random_seed, + ) + X_fit_transform = target_encoder.fit_transform(X_train, y_train) + + assert target_encoder.target_type_ == "multiclass" + assert_allclose(X_fit_transform, expected_X_fit_transform) + + # Manually compute encoding to validate `transform` + expected_encodings = [] + for f_idx, cats in enumerate(categories_): + for c_idx in range(n_classes): + y_class = y_train_enc[:, c_idx] + current_encoding = _encode_target( + X_train_int[:, f_idx], y_class, len(cats), smooth + ) + expected_encodings.append(current_encoding) + + assert len(target_encoder.encodings_) == n_features * n_classes + for i in range(n_features * n_classes): + assert_allclose(target_encoder.encodings_[i], expected_encodings[i]) + assert_array_equal(target_encoder.classes_, target_labels) + + # Include unknown values at the end + X_test_int = np.array([[0, 1], [1, 2], [4, 5]]) + if unknown_values == "auto": + X_test = X_test_int + else: + X_test = np.empty_like(X_test_int[:-1, :], dtype=object) + for column_idx in range(X_test_int.shape[1]): + X_test[:, column_idx] = categories[0][X_test_int[:-1, column_idx]] + # Add unknown values at end + X_test = np.vstack((X_test, unknown_values)) + + y_mean = np.mean(y_train_enc, axis=0) + expected_X_test_transform = np.empty( + (X_test_int.shape[0], X_test_int.shape[1] * n_classes), + dtype=np.float64, + ) + n_rows = X_test_int.shape[0] + f_idx = [0, 0, 0, 1, 1, 1] + # Last row are unknowns, dealt with later + for row_idx in range(n_rows - 1): + for i, enc in enumerate(expected_encodings): + expected_X_test_transform[row_idx, i] = enc[X_test_int[row_idx, f_idx[i]]] + + # Unknowns encoded as target mean for each class + # `y_mean` contains target mean for each class, thus cycle through mean of + # each class, `n_features` times + mean_idx = [0, 1, 2, 0, 1, 2] + for i in range(n_classes * n_features): + expected_X_test_transform[n_rows - 1, i] = y_mean[mean_idx[i]] + + X_test_transform = target_encoder.transform(X_test) + assert_allclose(X_test_transform, expected_X_test_transform) + + +@pytest.mark.parametrize( + "X, categories", + [ + ( + np.array([[0] * 10 + [1] * 10 + [3]], dtype=np.int64).T, # 3 is unknown + [[0, 1, 2]], + ), + ( + np.array( + [["cat"] * 10 + ["dog"] * 10 + ["snake"]], dtype=object + ).T, # snake is unknown + [["dog", "cat", "cow"]], + ), + ], +) +@pytest.mark.parametrize("smooth", [4.0, "auto"]) +def test_custom_categories(X, categories, smooth): + """Custom categories with unknown categories that are not in training data.""" + rng = np.random.RandomState(0) + y = rng.uniform(low=-10, high=20, size=X.shape[0]) + enc = TargetEncoder(categories=categories, smooth=smooth, random_state=0).fit(X, y) + + # The last element is unknown and encoded as the mean + y_mean = y.mean() + X_trans = enc.transform(X[-1:]) + assert X_trans[0, 0] == pytest.approx(y_mean) + + assert len(enc.encodings_) == 1 + # custom category that is not in training data + assert enc.encodings_[0][-1] == pytest.approx(y_mean) + + +@pytest.mark.parametrize( + "y, msg", + [ + ([1, 2, 0, 1], "Found input variables with inconsistent"), + ( + np.array([[1, 2, 0], [1, 2, 3]]).T, + "Target type was inferred to be 'multiclass-multioutput'", + ), + ], +) +def test_errors(y, msg): + """Check invalidate input.""" + X = np.array([[1, 0, 1]]).T + + enc = TargetEncoder() + with pytest.raises(ValueError, match=msg): + enc.fit_transform(X, y) + + +def test_use_regression_target(): + """Check inferred and specified `target_type` on regression target.""" + X = np.array([[0, 1, 0, 1, 0, 1]]).T + y = np.array([1.0, 2.0, 3.0, 2.0, 3.0, 4.0]) + + enc = TargetEncoder(cv=2) + with pytest.warns( + UserWarning, + match=re.escape( + "The least populated class in y has only 1 members, which is less than" + " n_splits=2." + ), + ): + enc.fit_transform(X, y) + assert enc.target_type_ == "multiclass" + + enc = TargetEncoder(cv=2, target_type="continuous") + enc.fit_transform(X, y) + assert enc.target_type_ == "continuous" + + +@pytest.mark.parametrize( + "y, feature_names", + [ + ([1, 2] * 10, ["A", "B"]), + ([1, 2, 3] * 6 + [1, 2], ["A_1", "A_2", "A_3", "B_1", "B_2", "B_3"]), + ( + ["y1", "y2", "y3"] * 6 + ["y1", "y2"], + ["A_y1", "A_y2", "A_y3", "B_y1", "B_y2", "B_y3"], + ), + ], +) +def test_feature_names_out_set_output(y, feature_names): + """Check TargetEncoder works with set_output.""" + pd = pytest.importorskip("pandas") + + X_df = pd.DataFrame({"A": ["a", "b"] * 10, "B": [1, 2] * 10}) + + enc_default = TargetEncoder(cv=2, smooth=3.0, random_state=0) + enc_default.set_output(transform="default") + enc_pandas = TargetEncoder(cv=2, smooth=3.0, random_state=0) + enc_pandas.set_output(transform="pandas") + + X_default = enc_default.fit_transform(X_df, y) + X_pandas = enc_pandas.fit_transform(X_df, y) + + assert_allclose(X_pandas.to_numpy(), X_default) + assert_array_equal(enc_pandas.get_feature_names_out(), feature_names) + assert_array_equal(enc_pandas.get_feature_names_out(), X_pandas.columns) + + +@pytest.mark.parametrize("to_pandas", [True, False]) +@pytest.mark.parametrize("smooth", [1.0, "auto"]) +@pytest.mark.parametrize("target_type", ["binary-ints", "binary-str", "continuous"]) +def test_multiple_features_quick(to_pandas, smooth, target_type): + """Check target encoder with multiple features.""" + X_ordinal = np.array( + [[1, 1], [0, 1], [1, 1], [2, 1], [1, 0], [0, 1], [1, 0], [0, 0]], dtype=np.int64 + ) + if target_type == "binary-str": + y_train = np.array(["a", "b", "a", "a", "b", "b", "a", "b"]) + y_integer = LabelEncoder().fit_transform(y_train) + cv = StratifiedKFold(2, random_state=0, shuffle=True) + elif target_type == "binary-ints": + y_train = np.array([3, 4, 3, 3, 3, 4, 4, 4]) + y_integer = LabelEncoder().fit_transform(y_train) + cv = StratifiedKFold(2, random_state=0, shuffle=True) + else: + y_train = np.array([3.0, 5.1, 2.4, 3.5, 4.1, 5.5, 10.3, 7.3], dtype=np.float32) + y_integer = y_train + cv = KFold(2, random_state=0, shuffle=True) + y_mean = np.mean(y_integer) + categories = [[0, 1, 2], [0, 1]] + + X_test = np.array( + [ + [0, 1], + [3, 0], # 3 is unknown + [1, 10], # 10 is unknown + ], + dtype=np.int64, + ) + + if to_pandas: + pd = pytest.importorskip("pandas") + # convert second feature to an object + X_train = pd.DataFrame( + { + "feat0": X_ordinal[:, 0], + "feat1": np.array(["cat", "dog"], dtype=object)[X_ordinal[:, 1]], + } + ) + # "snake" is unknown + X_test = pd.DataFrame({"feat0": X_test[:, 0], "feat1": ["dog", "cat", "snake"]}) + else: + X_train = X_ordinal + + # manually compute encoding for fit_transform + expected_X_fit_transform = np.empty_like(X_ordinal, dtype=np.float64) + for f_idx, cats in enumerate(categories): + for train_idx, test_idx in cv.split(X_ordinal, y_integer): + X_, y_ = X_ordinal[train_idx, f_idx], y_integer[train_idx] + current_encoding = _encode_target(X_, y_, len(cats), smooth) + expected_X_fit_transform[test_idx, f_idx] = current_encoding[ + X_ordinal[test_idx, f_idx] + ] + + # manually compute encoding for transform + expected_encodings = [] + for f_idx, cats in enumerate(categories): + current_encoding = _encode_target( + X_ordinal[:, f_idx], y_integer, len(cats), smooth + ) + expected_encodings.append(current_encoding) + + expected_X_test_transform = np.array( + [ + [expected_encodings[0][0], expected_encodings[1][1]], + [y_mean, expected_encodings[1][0]], + [expected_encodings[0][1], y_mean], + ], + dtype=np.float64, + ) + + enc = TargetEncoder(smooth=smooth, cv=2, random_state=0) + X_fit_transform = enc.fit_transform(X_train, y_train) + assert_allclose(X_fit_transform, expected_X_fit_transform) + + assert len(enc.encodings_) == 2 + for i in range(2): + assert_allclose(enc.encodings_[i], expected_encodings[i]) + + X_test_transform = enc.transform(X_test) + assert_allclose(X_test_transform, expected_X_test_transform) + + +@pytest.mark.parametrize( + "y, y_mean", + [ + (np.array([3.4] * 20), 3.4), + (np.array([0] * 20), 0), + (np.array(["a"] * 20, dtype=object), 0), + ], + ids=["continuous", "binary", "binary-string"], +) +@pytest.mark.parametrize("smooth", ["auto", 4.0, 0.0]) +def test_constant_target_and_feature(y, y_mean, smooth): + """Check edge case where feature and target is constant.""" + X = np.array([[1] * 20]).T + n_samples = X.shape[0] + + enc = TargetEncoder(cv=2, smooth=smooth, random_state=0) + X_trans = enc.fit_transform(X, y) + assert_allclose(X_trans, np.repeat([[y_mean]], n_samples, axis=0)) + assert enc.encodings_[0][0] == pytest.approx(y_mean) + assert enc.target_mean_ == pytest.approx(y_mean) + + X_test = np.array([[1], [0]]) + X_test_trans = enc.transform(X_test) + assert_allclose(X_test_trans, np.repeat([[y_mean]], 2, axis=0)) + + +def test_fit_transform_not_associated_with_y_if_ordinal_categorical_is_not( + global_random_seed, +): + cardinality = 30 # not too large, otherwise we need a very large n_samples + n_samples = 3000 + rng = np.random.RandomState(global_random_seed) + y_train = rng.normal(size=n_samples) + X_train = rng.randint(0, cardinality, size=n_samples).reshape(-1, 1) + + # Sort by y_train to attempt to cause a leak + y_sorted_indices = y_train.argsort() + y_train = y_train[y_sorted_indices] + X_train = X_train[y_sorted_indices] + + target_encoder = TargetEncoder(shuffle=True, random_state=global_random_seed) + X_encoded_train_shuffled = target_encoder.fit_transform(X_train, y_train) + + target_encoder = TargetEncoder(shuffle=False) + X_encoded_train_no_shuffled = target_encoder.fit_transform(X_train, y_train) + + # Check that no information about y_train has leaked into X_train: + regressor = RandomForestRegressor( + n_estimators=10, min_samples_leaf=20, random_state=global_random_seed + ) + + # It's impossible to learn a good predictive model on the training set when + # using the original representation X_train or the target encoded + # representation with shuffled inner CV. For the latter, no information + # about y_train has inadvertently leaked into the prior used to generate + # `X_encoded_train_shuffled`: + cv = ShuffleSplit(n_splits=50, random_state=global_random_seed) + assert cross_val_score(regressor, X_train, y_train, cv=cv).mean() < 0.1 + assert ( + cross_val_score(regressor, X_encoded_train_shuffled, y_train, cv=cv).mean() + < 0.1 + ) + + # Without the inner CV shuffling, a lot of information about y_train goes into the + # the per-fold y_train.mean() priors: shrinkage is no longer effective in this + # case and would no longer be able to prevent downstream over-fitting. + assert ( + cross_val_score(regressor, X_encoded_train_no_shuffled, y_train, cv=cv).mean() + > 0.5 + ) + + +def test_smooth_zero(): + """Check edge case with zero smoothing and cv does not contain category.""" + X = np.array([[0, 0, 0, 0, 0, 1, 1, 1, 1, 1]]).T + y = np.array([2.1, 4.3, 1.2, 3.1, 1.0, 9.0, 10.3, 14.2, 13.3, 15.0]) + + enc = TargetEncoder(smooth=0.0, shuffle=False, cv=2) + X_trans = enc.fit_transform(X, y) + + # With cv = 2, category 0 does not exist in the second half, thus + # it will be encoded as the mean of the second half + assert_allclose(X_trans[0], np.mean(y[5:])) + + # category 1 does not exist in the first half, thus it will be encoded as + # the mean of the first half + assert_allclose(X_trans[-1], np.mean(y[:5])) + + +@pytest.mark.parametrize("smooth", [0.0, 1e3, "auto"]) +def test_invariance_of_encoding_under_label_permutation(smooth, global_random_seed): + # Check that the encoding does not depend on the integer of the value of + # the integer labels. This is quite a trivial property but it is helpful + # to understand the following test. + rng = np.random.RandomState(global_random_seed) + + # Random y and informative categorical X to make the test non-trivial when + # using smoothing. + y = rng.normal(size=1000) + n_categories = 30 + X = KBinsDiscretizer(n_bins=n_categories, encode="ordinal").fit_transform( + y.reshape(-1, 1) + ) + + X_train, X_test, y_train, y_test = train_test_split( + X, y, random_state=global_random_seed + ) + + # Shuffle the labels to make sure that the encoding is invariant to the + # permutation of the labels + permutated_labels = rng.permutation(n_categories) + X_train_permuted = permutated_labels[X_train.astype(np.int32)] + X_test_permuted = permutated_labels[X_test.astype(np.int32)] + + target_encoder = TargetEncoder(smooth=smooth, random_state=global_random_seed) + X_train_encoded = target_encoder.fit_transform(X_train, y_train) + X_test_encoded = target_encoder.transform(X_test) + + X_train_permuted_encoded = target_encoder.fit_transform(X_train_permuted, y_train) + X_test_permuted_encoded = target_encoder.transform(X_test_permuted) + + assert_allclose(X_train_encoded, X_train_permuted_encoded) + assert_allclose(X_test_encoded, X_test_permuted_encoded) + + +# TODO(1.5) remove warning filter when kbd's subsample default is changed +@pytest.mark.filterwarnings("ignore:In version 1.5 onwards, subsample=200_000") +@pytest.mark.parametrize("smooth", [0.0, "auto"]) +def test_target_encoding_for_linear_regression(smooth, global_random_seed): + # Check some expected statistical properties when fitting a linear + # regression model on target encoded features depending on their relation + # with that target. + + # In this test, we use the Ridge class with the "lsqr" solver and a little + # bit of regularization to implement a linear regression model that + # converges quickly for large `n_samples` and robustly in case of + # correlated features. Since we will fit this model on a mean centered + # target, we do not need to fit an intercept and this will help simplify + # the analysis with respect to the expected coefficients. + linear_regression = Ridge(alpha=1e-6, solver="lsqr", fit_intercept=False) + + # Construct a random target variable. We need a large number of samples for + # this test to be stable across all values of the random seed. + n_samples = 50_000 + rng = np.random.RandomState(global_random_seed) + y = rng.randn(n_samples) + + # Generate a single informative ordinal feature with medium cardinality. + # Inject some irreducible noise to make it harder for a multivariate model + # to identify the informative feature from other pure noise features. + noise = 0.8 * rng.randn(n_samples) + n_categories = 100 + X_informative = KBinsDiscretizer( + n_bins=n_categories, + encode="ordinal", + strategy="uniform", + random_state=rng, + ).fit_transform((y + noise).reshape(-1, 1)) + + # Let's permute the labels to hide the fact that this feature is + # informative to naive linear regression model trained on the raw ordinal + # values. As highlighted in the previous test, the target encoding should be + # invariant to such a permutation. + permutated_labels = rng.permutation(n_categories) + X_informative = permutated_labels[X_informative.astype(np.int32)] + + # Generate a shuffled copy of the informative feature to destroy the + # relationship with the target. + X_shuffled = rng.permutation(X_informative) + + # Also include a very high cardinality categorical feature that is by + # itself independent of the target variable: target encoding such a feature + # without internal cross-validation should cause catastrophic overfitting + # for the downstream regressor, even with shrinkage. This kind of features + # typically represents near unique identifiers of samples. In general they + # should be removed from a machine learning datasets but here we want to + # study the ability of the default behavior of TargetEncoder to mitigate + # them automatically. + X_near_unique_categories = rng.choice( + int(0.9 * n_samples), size=n_samples, replace=True + ).reshape(-1, 1) + + # Assemble the dataset and do a train-test split: + X = np.concatenate( + [X_informative, X_shuffled, X_near_unique_categories], + axis=1, + ) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + + # Let's first check that a linear regression model trained on the raw + # features underfits because of the meaning-less ordinal encoding of the + # labels. + raw_model = linear_regression.fit(X_train, y_train) + assert raw_model.score(X_train, y_train) < 0.1 + assert raw_model.score(X_test, y_test) < 0.1 + + # Now do the same with target encoding using the internal CV mechanism + # implemented when using fit_transform. + model_with_cv = make_pipeline( + TargetEncoder(smooth=smooth, random_state=rng), linear_regression + ).fit(X_train, y_train) + + # This model should be able to fit the data well and also generalise to the + # test data (assuming that the binning is fine-grained enough). The R2 + # scores are not perfect because of the noise injected during the + # generation of the unique informative feature. + coef = model_with_cv[-1].coef_ + assert model_with_cv.score(X_train, y_train) > 0.5, coef + assert model_with_cv.score(X_test, y_test) > 0.5, coef + + # The target encoder recovers the linear relationship with slope 1 between + # the target encoded unique informative predictor and the target. Since the + # target encoding of the 2 other features is not informative thanks to the + # use of internal cross-validation, the multivariate linear regressor + # assigns a coef of 1 to the first feature and 0 to the other 2. + assert coef[0] == pytest.approx(1, abs=1e-2) + assert (np.abs(coef[1:]) < 0.2).all() + + # Let's now disable the internal cross-validation by calling fit and then + # transform separately on the training set: + target_encoder = TargetEncoder(smooth=smooth, random_state=rng).fit( + X_train, y_train + ) + X_enc_no_cv_train = target_encoder.transform(X_train) + X_enc_no_cv_test = target_encoder.transform(X_test) + model_no_cv = linear_regression.fit(X_enc_no_cv_train, y_train) + + # The linear regression model should always overfit because it assigns + # too much weight to the extremely high cardinality feature relatively to + # the informative feature. Note that this is the case even when using + # the empirical Bayes smoothing which is not enough to prevent such + # overfitting alone. + coef = model_no_cv.coef_ + assert model_no_cv.score(X_enc_no_cv_train, y_train) > 0.7, coef + assert model_no_cv.score(X_enc_no_cv_test, y_test) < 0.5, coef + + # The model overfits because it assigns too much weight to the high + # cardinality yet non-informative feature instead of the lower + # cardinality yet informative feature: + assert abs(coef[0]) < abs(coef[2]) + + +def test_pandas_copy_on_write(): + """ + Test target-encoder cython code when y is read-only. + + The numpy array underlying df["y"] is read-only when copy-on-write is enabled. + Non-regression test for gh-27879. + """ + pd = pytest.importorskip("pandas", minversion="2.0") + with pd.option_context("mode.copy_on_write", True): + df = pd.DataFrame({"x": ["a", "b", "b"], "y": [4.0, 5.0, 6.0]}) + TargetEncoder(target_type="continuous").fit(df[["x"]], df["y"]) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99845e7bdcbd1bcb93c1a984e4640bd75e8689f0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_arpack.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_arpack.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33a07f473d1ea8c0fa4db8f42225a2d21adbf389 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_arpack.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_array_api.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_array_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1121ea4e021aad9c8db5fb99d8c571aa9f524b5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_array_api.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_arrayfuncs.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_arrayfuncs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..274b95621a314d5350b28f52425926ec092c23c2 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_arrayfuncs.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_bunch.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_bunch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55330befda43c53f94050b8e2da33a90879671e0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_bunch.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_class_weight.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_class_weight.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..942e3172c312ea41aac8b6874c13a68c762e7fa2 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_class_weight.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_blas.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_blas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad833d0814398d74aea662ef523161f02562859a Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_blas.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_templating.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_templating.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae0333ded5574ed720f58cf0b2a0ada1b919bb6e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_templating.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_deprecation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e3bceefcb522a4a36d02b4703707d0766d3aac2 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_deprecation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_encode.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_encode.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a69705c00efe0d44449da3c0faaf85bc5e85a8fc Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_encode.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d207cad7b565038906612a17470f989ffbe2270 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_html_repr.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_html_repr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f57e98f8569db263e0e4788d2bda8299e56c2c5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_html_repr.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_extmath.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_extmath.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ab47b31c3a1ede2eb2801ee3d48883845c07acf Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_extmath.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_fast_dict.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_fast_dict.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbb363244af4c3ee2f0ede9ecf09bc88d4c3dd7f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_fast_dict.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_fixes.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_fixes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dce40948bcfaaf5673f153cbc74e26b1c32b3ca6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_fixes.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_graph.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_graph.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a468d73fc358dec30f6d115caefd9e24ecaa0cb1 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_graph.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_metaestimators.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_metaestimators.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7de7f003aa0dea45e02e9351844b9240c6143ecf Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_metaestimators.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_mocking.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_mocking.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1bd406899563c44136d97c4bae9da8f419905d9 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_mocking.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_multiclass.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_multiclass.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3511bdd8700b0e7005c5f0ee5a68745ea8286ae2 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_multiclass.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_murmurhash.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_murmurhash.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f2d841754238f68cbd5629a9fe648491cec916b Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_murmurhash.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bade57114f03ef1fd8788623e009f603f518d7df Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_parallel.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_parallel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6bb2ed94323666f55a295df2bd145d5aa0ddadf Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_parallel.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e18b647067c76b61ffdb4fa7ef898c310c209fc5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_plotting.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_plotting.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..001ac47eb6159c882688184f3625d1bf3096b1e4 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_plotting.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_pprint.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_pprint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a90ea1220b9c638168156dcb88a5d792ac71c0d2 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_pprint.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_random.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_random.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90f53420be2ae5bf0d2e99e50327b9900d2bd95d Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_random.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_response.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_response.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11c76d3976e675c60e78168d1ce3be6e15fc0f50 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_response.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc58fdd78f64fc09c60d66bb54aac36ef6cdcd57 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_set_output.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_set_output.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5100b82fe5dcb2fc3b0de62d06a63e10f1119f6c Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_set_output.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_shortest_path.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_shortest_path.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d59a7dd545225429c880ad190eaff314f847f9f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_shortest_path.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85a8f43d73ecfb94b73353755994e8b6dc9980f0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_sparsefuncs.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_sparsefuncs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7078dde7d749151092617290781b0c7a70f1ce7 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_sparsefuncs.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_stats.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_stats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0122ad68fad459ea4a9aa32e2282c0535feb4d47 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_stats.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_tags.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_tags.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62aad4505ad0d4f8626db9df4d23c9d068e4c2a0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_tags.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_testing.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..432b20f93cbf4764714fc445389b6104894ae0f5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_testing.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_typedefs.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_typedefs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0732083318b7a7ce7f1d01447d20231f957fa194 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_typedefs.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_utils.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0491b6183ef3e3c5bc97df3f8957435948d7dd5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_utils.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_validation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5092109dc66eaf494363bd3d571f03716651dec5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_validation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0397956df496962f1a7a45e561a3225d88ac486 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_arpack.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_arpack.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1d622d51a08eca5ecf526b77d1bbeab17737f6 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_arpack.py @@ -0,0 +1,16 @@ +import pytest +from numpy.testing import assert_allclose + +from sklearn.utils import check_random_state +from sklearn.utils._arpack import _init_arpack_v0 + + +@pytest.mark.parametrize("seed", range(100)) +def test_init_arpack_v0(seed): + # check that the initialization a sampling from an uniform distribution + # where we can fix the random state + size = 1000 + v0 = _init_arpack_v0(size, seed) + + rng = check_random_state(seed) + assert_allclose(v0, rng.uniform(-1, 1, size=size)) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_class_weight.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_class_weight.py new file mode 100644 index 0000000000000000000000000000000000000000..b98ce6be056584697da799e4dbe631c1845cff1d --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_class_weight.py @@ -0,0 +1,316 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose + +from sklearn.datasets import make_blobs +from sklearn.linear_model import LogisticRegression +from sklearn.tree import DecisionTreeClassifier +from sklearn.utils._testing import assert_almost_equal, assert_array_almost_equal +from sklearn.utils.class_weight import compute_class_weight, compute_sample_weight +from sklearn.utils.fixes import CSC_CONTAINERS + + +def test_compute_class_weight(): + # Test (and demo) compute_class_weight. + y = np.asarray([2, 2, 2, 3, 3, 4]) + classes = np.unique(y) + + cw = compute_class_weight("balanced", classes=classes, y=y) + # total effect of samples is preserved + class_counts = np.bincount(y)[2:] + assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) + assert cw[0] < cw[1] < cw[2] + + +@pytest.mark.parametrize( + "y_type, class_weight, classes, err_msg", + [ + ( + "numeric", + "balanced", + np.arange(4), + "classes should have valid labels that are in y", + ), + # Non-regression for https://github.com/scikit-learn/scikit-learn/issues/8312 + ( + "numeric", + {"label_not_present": 1.0}, + np.arange(4), + r"The classes, \[0, 1, 2, 3\], are not in class_weight", + ), + ( + "numeric", + "balanced", + np.arange(2), + "classes should include all valid labels", + ), + ( + "numeric", + {0: 1.0, 1: 2.0}, + np.arange(2), + "classes should include all valid labels", + ), + ( + "string", + {"dogs": 3, "cat": 2}, + np.array(["dog", "cat"]), + r"The classes, \['dog'\], are not in class_weight", + ), + ], +) +def test_compute_class_weight_not_present(y_type, class_weight, classes, err_msg): + # Raise error when y does not contain all class labels + y = ( + np.asarray([0, 0, 0, 1, 1, 2]) + if y_type == "numeric" + else np.asarray(["dog", "cat", "dog"]) + ) + + print(y) + with pytest.raises(ValueError, match=err_msg): + compute_class_weight(class_weight, classes=classes, y=y) + + +def test_compute_class_weight_dict(): + classes = np.arange(3) + class_weights = {0: 1.0, 1: 2.0, 2: 3.0} + y = np.asarray([0, 0, 1, 2]) + cw = compute_class_weight(class_weights, classes=classes, y=y) + + # When the user specifies class weights, compute_class_weights should just + # return them. + assert_array_almost_equal(np.asarray([1.0, 2.0, 3.0]), cw) + + # When a class weight is specified that isn't in classes, the weight is ignored + class_weights = {0: 1.0, 1: 2.0, 2: 3.0, 4: 1.5} + cw = compute_class_weight(class_weights, classes=classes, y=y) + assert_allclose([1.0, 2.0, 3.0], cw) + + class_weights = {-1: 5.0, 0: 4.0, 1: 2.0, 2: 3.0} + cw = compute_class_weight(class_weights, classes=classes, y=y) + assert_allclose([4.0, 2.0, 3.0], cw) + + +def test_compute_class_weight_invariance(): + # Test that results with class_weight="balanced" is invariant wrt + # class imbalance if the number of samples is identical. + # The test uses a balanced two class dataset with 100 datapoints. + # It creates three versions, one where class 1 is duplicated + # resulting in 150 points of class 1 and 50 of class 0, + # one where there are 50 points in class 1 and 150 in class 0, + # and one where there are 100 points of each class (this one is balanced + # again). + # With balancing class weights, all three should give the same model. + X, y = make_blobs(centers=2, random_state=0) + # create dataset where class 1 is duplicated twice + X_1 = np.vstack([X] + [X[y == 1]] * 2) + y_1 = np.hstack([y] + [y[y == 1]] * 2) + # create dataset where class 0 is duplicated twice + X_0 = np.vstack([X] + [X[y == 0]] * 2) + y_0 = np.hstack([y] + [y[y == 0]] * 2) + # duplicate everything + X_ = np.vstack([X] * 2) + y_ = np.hstack([y] * 2) + # results should be identical + logreg1 = LogisticRegression(class_weight="balanced").fit(X_1, y_1) + logreg0 = LogisticRegression(class_weight="balanced").fit(X_0, y_0) + logreg = LogisticRegression(class_weight="balanced").fit(X_, y_) + assert_array_almost_equal(logreg1.coef_, logreg0.coef_) + assert_array_almost_equal(logreg.coef_, logreg0.coef_) + + +def test_compute_class_weight_balanced_negative(): + # Test compute_class_weight when labels are negative + # Test with balanced class labels. + classes = np.array([-2, -1, 0]) + y = np.asarray([-1, -1, 0, 0, -2, -2]) + + cw = compute_class_weight("balanced", classes=classes, y=y) + assert len(cw) == len(classes) + assert_array_almost_equal(cw, np.array([1.0, 1.0, 1.0])) + + # Test with unbalanced class labels. + y = np.asarray([-1, 0, 0, -2, -2, -2]) + + cw = compute_class_weight("balanced", classes=classes, y=y) + assert len(cw) == len(classes) + class_counts = np.bincount(y + 2) + assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) + assert_array_almost_equal(cw, [2.0 / 3, 2.0, 1.0]) + + +def test_compute_class_weight_balanced_unordered(): + # Test compute_class_weight when classes are unordered + classes = np.array([1, 0, 3]) + y = np.asarray([1, 0, 0, 3, 3, 3]) + + cw = compute_class_weight("balanced", classes=classes, y=y) + class_counts = np.bincount(y)[classes] + assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) + assert_array_almost_equal(cw, [2.0, 1.0, 2.0 / 3]) + + +def test_compute_class_weight_default(): + # Test for the case where no weight is given for a present class. + # Current behaviour is to assign the unweighted classes a weight of 1. + y = np.asarray([2, 2, 2, 3, 3, 4]) + classes = np.unique(y) + classes_len = len(classes) + + # Test for non specified weights + cw = compute_class_weight(None, classes=classes, y=y) + assert len(cw) == classes_len + assert_array_almost_equal(cw, np.ones(3)) + + # Tests for partly specified weights + cw = compute_class_weight({2: 1.5}, classes=classes, y=y) + assert len(cw) == classes_len + assert_array_almost_equal(cw, [1.5, 1.0, 1.0]) + + cw = compute_class_weight({2: 1.5, 4: 0.5}, classes=classes, y=y) + assert len(cw) == classes_len + assert_array_almost_equal(cw, [1.5, 1.0, 0.5]) + + +def test_compute_sample_weight(): + # Test (and demo) compute_sample_weight. + # Test with balanced classes + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with user-defined weights + sample_weight = compute_sample_weight({1: 2, 2: 1}, y) + assert_array_almost_equal(sample_weight, [2.0, 2.0, 2.0, 1.0, 1.0, 1.0]) + + # Test with column vector of balanced classes + y = np.asarray([[1], [1], [1], [2], [2], [2]]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with unbalanced classes + y = np.asarray([1, 1, 1, 2, 2, 2, 3]) + sample_weight = compute_sample_weight("balanced", y) + expected_balanced = np.array( + [0.7777, 0.7777, 0.7777, 0.7777, 0.7777, 0.7777, 2.3333] + ) + assert_array_almost_equal(sample_weight, expected_balanced, decimal=4) + + # Test with `None` weights + sample_weight = compute_sample_weight(None, y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with multi-output of balanced classes + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with multi-output with user-defined weights + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight([{1: 2, 2: 1}, {0: 1, 1: 2}], y) + assert_array_almost_equal(sample_weight, [2.0, 2.0, 2.0, 2.0, 2.0, 2.0]) + + # Test with multi-output of unbalanced classes + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [3, -1]]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, expected_balanced**2, decimal=3) + + +def test_compute_sample_weight_with_subsample(): + # Test compute_sample_weight with subsamples specified. + # Test with balanced classes and all samples present + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with column vector of balanced classes and all samples present + y = np.asarray([[1], [1], [1], [2], [2], [2]]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with a subsample + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y, indices=range(4)) + assert_array_almost_equal(sample_weight, [2.0 / 3, 2.0 / 3, 2.0 / 3, 2.0, 2.0, 2.0]) + + # Test with a bootstrap subsample + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y, indices=[0, 1, 1, 2, 2, 3]) + expected_balanced = np.asarray([0.6, 0.6, 0.6, 3.0, 3.0, 3.0]) + assert_array_almost_equal(sample_weight, expected_balanced) + + # Test with a bootstrap subsample for multi-output + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight("balanced", y, indices=[0, 1, 1, 2, 2, 3]) + assert_array_almost_equal(sample_weight, expected_balanced**2) + + # Test with a missing class + y = np.asarray([1, 1, 1, 2, 2, 2, 3]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]) + + # Test with a missing class for multi-output + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [2, 2]]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]) + + +@pytest.mark.parametrize( + "y_type, class_weight, indices, err_msg", + [ + ( + "single-output", + {1: 2, 2: 1}, + range(4), + "The only valid class_weight for subsampling is 'balanced'.", + ), + ( + "multi-output", + {1: 2, 2: 1}, + None, + "For multi-output, class_weight should be a list of dicts, or the string", + ), + ( + "multi-output", + [{1: 2, 2: 1}], + None, + r"Got 1 element\(s\) while having 2 outputs", + ), + ], +) +def test_compute_sample_weight_errors(y_type, class_weight, indices, err_msg): + # Test compute_sample_weight raises errors expected. + # Invalid preset string + y_single_output = np.asarray([1, 1, 1, 2, 2, 2]) + y_multi_output = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + + y = y_single_output if y_type == "single-output" else y_multi_output + with pytest.raises(ValueError, match=err_msg): + compute_sample_weight(class_weight, y, indices=indices) + + +def test_compute_sample_weight_more_than_32(): + # Non-regression smoke test for #12146 + y = np.arange(50) # more than 32 distinct classes + indices = np.arange(50) # use subsampling + weight = compute_sample_weight("balanced", y, indices=indices) + assert_array_almost_equal(weight, np.ones(y.shape[0])) + + +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]) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +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]) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_deprecation.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..4d04b48da2f0b799dcf4f801865dd2b375dea01b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_deprecation.py @@ -0,0 +1,88 @@ +# Authors: Raghav RV +# License: BSD 3 clause + + +import pickle + +import pytest + +from sklearn.utils.deprecation import _is_deprecated, deprecated + + +@deprecated("qwerty") +class MockClass1: + pass + + +class MockClass2: + @deprecated("mockclass2_method") + def method(self): + pass + + @deprecated("n_features_ is deprecated") # type: ignore + @property + def n_features_(self): + """Number of input features.""" + return 10 + + +class MockClass3: + @deprecated() + def __init__(self): + pass + + +class MockClass4: + pass + + +class MockClass5(MockClass1): + """Inherit from deprecated class but does not call super().__init__.""" + + def __init__(self, a): + self.a = a + + +@deprecated("a message") +class MockClass6: + """A deprecated class that overrides __new__.""" + + def __new__(cls, *args, **kwargs): + assert len(args) > 0 + return super().__new__(cls) + + +@deprecated() +def mock_function(): + return 10 + + +def test_deprecated(): + with pytest.warns(FutureWarning, match="qwerty"): + MockClass1() + with pytest.warns(FutureWarning, match="mockclass2_method"): + MockClass2().method() + with pytest.warns(FutureWarning, match="deprecated"): + MockClass3() + with pytest.warns(FutureWarning, match="qwerty"): + MockClass5(42) + with pytest.warns(FutureWarning, match="a message"): + MockClass6(42) + with pytest.warns(FutureWarning, match="deprecated"): + val = mock_function() + assert val == 10 + + +def test_is_deprecated(): + # Test if _is_deprecated helper identifies wrapping via deprecated + # NOTE it works only for class methods and functions + assert _is_deprecated(MockClass1.__new__) + assert _is_deprecated(MockClass2().method) + assert _is_deprecated(MockClass3.__init__) + assert not _is_deprecated(MockClass4.__init__) + assert _is_deprecated(MockClass5.__new__) + assert _is_deprecated(mock_function) + + +def test_pickle(): + pickle.loads(pickle.dumps(mock_function)) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_encode.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_encode.py new file mode 100644 index 0000000000000000000000000000000000000000..9118eb56f0ba4bbc5227b6c57450af891876acfa --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_encode.py @@ -0,0 +1,274 @@ +import pickle + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +from sklearn.utils._encode import _check_unknown, _encode, _get_counts, _unique + + +@pytest.mark.parametrize( + "values, expected", + [ + (np.array([2, 1, 3, 1, 3], dtype="int64"), np.array([1, 2, 3], dtype="int64")), + ( + np.array([2, 1, np.nan, 1, np.nan], dtype="float32"), + np.array([1, 2, np.nan], dtype="float32"), + ), + ( + np.array(["b", "a", "c", "a", "c"], dtype=object), + np.array(["a", "b", "c"], dtype=object), + ), + ( + np.array(["b", "a", None, "a", None], dtype=object), + np.array(["a", "b", None], dtype=object), + ), + (np.array(["b", "a", "c", "a", "c"]), np.array(["a", "b", "c"])), + ], + ids=["int64", "float32-nan", "object", "object-None", "str"], +) +def test_encode_util(values, expected): + uniques = _unique(values) + assert_array_equal(uniques, expected) + + result, encoded = _unique(values, return_inverse=True) + assert_array_equal(result, expected) + assert_array_equal(encoded, np.array([1, 0, 2, 0, 2])) + + encoded = _encode(values, uniques=uniques) + assert_array_equal(encoded, np.array([1, 0, 2, 0, 2])) + + result, counts = _unique(values, return_counts=True) + assert_array_equal(result, expected) + assert_array_equal(counts, np.array([2, 1, 2])) + + result, encoded, counts = _unique(values, return_inverse=True, return_counts=True) + assert_array_equal(result, expected) + assert_array_equal(encoded, np.array([1, 0, 2, 0, 2])) + assert_array_equal(counts, np.array([2, 1, 2])) + + +def test_encode_with_check_unknown(): + # test for the check_unknown parameter of _encode() + uniques = np.array([1, 2, 3]) + values = np.array([1, 2, 3, 4]) + + # Default is True, raise error + with pytest.raises(ValueError, match="y contains previously unseen labels"): + _encode(values, uniques=uniques, check_unknown=True) + + # dont raise error if False + _encode(values, uniques=uniques, check_unknown=False) + + # parameter is ignored for object dtype + uniques = np.array(["a", "b", "c"], dtype=object) + values = np.array(["a", "b", "c", "d"], dtype=object) + with pytest.raises(ValueError, match="y contains previously unseen labels"): + _encode(values, uniques=uniques, check_unknown=False) + + +def _assert_check_unknown(values, uniques, expected_diff, expected_mask): + diff = _check_unknown(values, uniques) + assert_array_equal(diff, expected_diff) + + diff, valid_mask = _check_unknown(values, uniques, return_mask=True) + assert_array_equal(diff, expected_diff) + assert_array_equal(valid_mask, expected_mask) + + +@pytest.mark.parametrize( + "values, uniques, expected_diff, expected_mask", + [ + (np.array([1, 2, 3, 4]), np.array([1, 2, 3]), [4], [True, True, True, False]), + (np.array([2, 1, 4, 5]), np.array([2, 5, 1]), [4], [True, True, False, True]), + (np.array([2, 1, np.nan]), np.array([2, 5, 1]), [np.nan], [True, True, False]), + ( + np.array([2, 1, 4, np.nan]), + np.array([2, 5, 1, np.nan]), + [4], + [True, True, False, True], + ), + ( + np.array([2, 1, 4, np.nan]), + np.array([2, 5, 1]), + [4, np.nan], + [True, True, False, False], + ), + ( + np.array([2, 1, 4, 5]), + np.array([2, 5, 1, np.nan]), + [4], + [True, True, False, True], + ), + ( + np.array(["a", "b", "c", "d"], dtype=object), + np.array(["a", "b", "c"], dtype=object), + np.array(["d"], dtype=object), + [True, True, True, False], + ), + ( + np.array(["d", "c", "a", "b"], dtype=object), + np.array(["a", "c", "b"], dtype=object), + np.array(["d"], dtype=object), + [False, True, True, True], + ), + ( + np.array(["a", "b", "c", "d"]), + np.array(["a", "b", "c"]), + np.array(["d"]), + [True, True, True, False], + ), + ( + np.array(["d", "c", "a", "b"]), + np.array(["a", "c", "b"]), + np.array(["d"]), + [False, True, True, True], + ), + ], +) +def test_check_unknown(values, uniques, expected_diff, expected_mask): + _assert_check_unknown(values, uniques, expected_diff, expected_mask) + + +@pytest.mark.parametrize("missing_value", [None, np.nan, float("nan")]) +@pytest.mark.parametrize("pickle_uniques", [True, False]) +def test_check_unknown_missing_values(missing_value, pickle_uniques): + # check for check_unknown with missing values with object dtypes + values = np.array(["d", "c", "a", "b", missing_value], dtype=object) + uniques = np.array(["c", "a", "b", missing_value], dtype=object) + if pickle_uniques: + uniques = pickle.loads(pickle.dumps(uniques)) + + expected_diff = ["d"] + expected_mask = [False, True, True, True, True] + _assert_check_unknown(values, uniques, expected_diff, expected_mask) + + values = np.array(["d", "c", "a", "b", missing_value], dtype=object) + uniques = np.array(["c", "a", "b"], dtype=object) + if pickle_uniques: + uniques = pickle.loads(pickle.dumps(uniques)) + + expected_diff = ["d", missing_value] + + expected_mask = [False, True, True, True, False] + _assert_check_unknown(values, uniques, expected_diff, expected_mask) + + values = np.array(["a", missing_value], dtype=object) + uniques = np.array(["a", "b", "z"], dtype=object) + if pickle_uniques: + uniques = pickle.loads(pickle.dumps(uniques)) + + expected_diff = [missing_value] + expected_mask = [True, False] + _assert_check_unknown(values, uniques, expected_diff, expected_mask) + + +@pytest.mark.parametrize("missing_value", [np.nan, None, float("nan")]) +@pytest.mark.parametrize("pickle_uniques", [True, False]) +def test_unique_util_missing_values_objects(missing_value, pickle_uniques): + # check for _unique and _encode with missing values with object dtypes + values = np.array(["a", "c", "c", missing_value, "b"], dtype=object) + expected_uniques = np.array(["a", "b", "c", missing_value], dtype=object) + + uniques = _unique(values) + + if missing_value is None: + assert_array_equal(uniques, expected_uniques) + else: # missing_value == np.nan + assert_array_equal(uniques[:-1], expected_uniques[:-1]) + assert np.isnan(uniques[-1]) + + if pickle_uniques: + uniques = pickle.loads(pickle.dumps(uniques)) + + encoded = _encode(values, uniques=uniques) + assert_array_equal(encoded, np.array([0, 2, 2, 3, 1])) + + +def test_unique_util_missing_values_numeric(): + # Check missing values in numerical values + values = np.array([3, 1, np.nan, 5, 3, np.nan], dtype=float) + expected_uniques = np.array([1, 3, 5, np.nan], dtype=float) + expected_inverse = np.array([1, 0, 3, 2, 1, 3]) + + uniques = _unique(values) + assert_array_equal(uniques, expected_uniques) + + uniques, inverse = _unique(values, return_inverse=True) + assert_array_equal(uniques, expected_uniques) + assert_array_equal(inverse, expected_inverse) + + encoded = _encode(values, uniques=uniques) + assert_array_equal(encoded, expected_inverse) + + +def test_unique_util_with_all_missing_values(): + # test for all types of missing values for object dtype + values = np.array([np.nan, "a", "c", "c", None, float("nan"), None], dtype=object) + + uniques = _unique(values) + assert_array_equal(uniques[:-1], ["a", "c", None]) + # last value is nan + assert np.isnan(uniques[-1]) + + expected_inverse = [3, 0, 1, 1, 2, 3, 2] + _, inverse = _unique(values, return_inverse=True) + assert_array_equal(inverse, expected_inverse) + + +def test_check_unknown_with_both_missing_values(): + # test for both types of missing values for object dtype + values = np.array([np.nan, "a", "c", "c", None, np.nan, None], dtype=object) + + diff = _check_unknown(values, known_values=np.array(["a", "c"], dtype=object)) + assert diff[0] is None + assert np.isnan(diff[1]) + + diff, valid_mask = _check_unknown( + values, known_values=np.array(["a", "c"], dtype=object), return_mask=True + ) + + assert diff[0] is None + assert np.isnan(diff[1]) + assert_array_equal(valid_mask, [False, True, True, True, False, False, False]) + + +@pytest.mark.parametrize( + "values, uniques, expected_counts", + [ + (np.array([1] * 10 + [2] * 4 + [3] * 15), np.array([1, 2, 3]), [10, 4, 15]), + ( + np.array([1] * 10 + [2] * 4 + [3] * 15), + np.array([1, 2, 3, 5]), + [10, 4, 15, 0], + ), + ( + np.array([np.nan] * 10 + [2] * 4 + [3] * 15), + np.array([2, 3, np.nan]), + [4, 15, 10], + ), + ( + np.array(["b"] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["a", "b", "c"], + [16, 4, 20], + ), + ( + np.array(["b"] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["c", "b", "a"], + [20, 4, 16], + ), + ( + np.array([np.nan] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["c", np.nan, "a"], + [20, 4, 16], + ), + ( + np.array(["b"] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["a", "b", "c", "e"], + [16, 4, 20, 0], + ), + ], +) +def test_get_counts(values, uniques, expected_counts): + counts = _get_counts(values, uniques) + assert_array_equal(counts, expected_counts) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_checks.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..f52ef27df4015fb5bcb4b0280fce5800ec2b969e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_checks.py @@ -0,0 +1,1260 @@ +# We can not use pytest here, because we run +# build_tools/azure/test_pytest_soft_dependency.sh on these +# tests to make sure estimator_checks works without pytest. + +import importlib +import sys +import unittest +import warnings +from numbers import Integral, Real + +import joblib +import numpy as np +import scipy.sparse as sp + +from sklearn import config_context, get_config +from sklearn.base import BaseEstimator, ClassifierMixin, OutlierMixin +from sklearn.cluster import MiniBatchKMeans +from sklearn.datasets import make_multilabel_classification +from sklearn.decomposition import PCA +from sklearn.ensemble import ExtraTreesClassifier +from sklearn.exceptions import ConvergenceWarning, SkipTestWarning +from sklearn.linear_model import ( + LinearRegression, + LogisticRegression, + MultiTaskElasticNet, + SGDClassifier, +) +from sklearn.mixture import GaussianMixture +from sklearn.neighbors import KNeighborsRegressor +from sklearn.svm import SVC, NuSVC +from sklearn.utils import _array_api, all_estimators, deprecated +from sklearn.utils._param_validation import Interval, StrOptions +from sklearn.utils._testing import ( + MinimalClassifier, + MinimalRegressor, + MinimalTransformer, + SkipTest, + ignore_warnings, + raises, +) +from sklearn.utils.estimator_checks import ( + _NotAnArray, + _set_checking_parameters, + _yield_all_checks, + check_array_api_input, + check_class_weight_balanced_linear_classifier, + check_classifier_data_not_an_array, + check_classifiers_multilabel_output_format_decision_function, + check_classifiers_multilabel_output_format_predict, + check_classifiers_multilabel_output_format_predict_proba, + check_dataframe_column_names_consistency, + check_decision_proba_consistency, + check_estimator, + check_estimator_get_tags_default_keys, + check_estimators_unfitted, + check_fit_check_is_fitted, + check_fit_score_takes_y, + check_methods_sample_order_invariance, + check_methods_subset_invariance, + check_no_attributes_set_in_init, + check_outlier_contamination, + check_outlier_corruption, + check_regressor_data_not_an_array, + check_requires_y_none, + set_random_state, +) +from sklearn.utils.fixes import CSR_CONTAINERS +from sklearn.utils.metaestimators import available_if +from sklearn.utils.validation import check_array, check_is_fitted, check_X_y + + +class CorrectNotFittedError(ValueError): + """Exception class to raise if estimator is used before fitting. + + Like NotFittedError, it inherits from ValueError, but not from + AttributeError. Used for testing only. + """ + + +class BaseBadClassifier(ClassifierMixin, BaseEstimator): + def fit(self, X, y): + return self + + def predict(self, X): + return np.ones(X.shape[0]) + + +class ChangesDict(BaseEstimator): + def __init__(self, key=0): + self.key = key + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + def predict(self, X): + X = check_array(X) + self.key = 1000 + return np.ones(X.shape[0]) + + +class SetsWrongAttribute(BaseEstimator): + def __init__(self, acceptable_key=0): + self.acceptable_key = acceptable_key + + def fit(self, X, y=None): + self.wrong_attribute = 0 + X, y = self._validate_data(X, y) + return self + + +class ChangesWrongAttribute(BaseEstimator): + def __init__(self, wrong_attribute=0): + self.wrong_attribute = wrong_attribute + + def fit(self, X, y=None): + self.wrong_attribute = 1 + X, y = self._validate_data(X, y) + return self + + +class ChangesUnderscoreAttribute(BaseEstimator): + def fit(self, X, y=None): + self._good_attribute = 1 + X, y = self._validate_data(X, y) + return self + + +class RaisesErrorInSetParams(BaseEstimator): + def __init__(self, p=0): + self.p = p + + def set_params(self, **kwargs): + if "p" in kwargs: + p = kwargs.pop("p") + if p < 0: + raise ValueError("p can't be less than 0") + self.p = p + return super().set_params(**kwargs) + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + +class HasMutableParameters(BaseEstimator): + def __init__(self, p=object()): + self.p = p + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + +class HasImmutableParameters(BaseEstimator): + # Note that object is an uninitialized class, thus immutable. + def __init__(self, p=42, q=np.int32(42), r=object): + self.p = p + self.q = q + self.r = r + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + +class ModifiesValueInsteadOfRaisingError(BaseEstimator): + def __init__(self, p=0): + self.p = p + + def set_params(self, **kwargs): + if "p" in kwargs: + p = kwargs.pop("p") + if p < 0: + p = 0 + self.p = p + return super().set_params(**kwargs) + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + +class ModifiesAnotherValue(BaseEstimator): + def __init__(self, a=0, b="method1"): + self.a = a + self.b = b + + def set_params(self, **kwargs): + if "a" in kwargs: + a = kwargs.pop("a") + self.a = a + if a is None: + kwargs.pop("b") + self.b = "method2" + return super().set_params(**kwargs) + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + +class NoCheckinPredict(BaseBadClassifier): + def fit(self, X, y): + X, y = self._validate_data(X, y) + return self + + +class NoSparseClassifier(BaseBadClassifier): + def fit(self, X, y): + X, y = self._validate_data(X, y, accept_sparse=["csr", "csc"]) + if sp.issparse(X): + raise ValueError("Nonsensical Error") + return self + + def predict(self, X): + X = check_array(X) + return np.ones(X.shape[0]) + + +class CorrectNotFittedErrorClassifier(BaseBadClassifier): + def fit(self, X, y): + X, y = self._validate_data(X, y) + self.coef_ = np.ones(X.shape[1]) + return self + + def predict(self, X): + check_is_fitted(self) + X = check_array(X) + return np.ones(X.shape[0]) + + +class NoSampleWeightPandasSeriesType(BaseEstimator): + def fit(self, X, y, sample_weight=None): + # Convert data + X, y = self._validate_data( + X, y, accept_sparse=("csr", "csc"), multi_output=True, y_numeric=True + ) + # Function is only called after we verify that pandas is installed + from pandas import Series + + if isinstance(sample_weight, Series): + raise ValueError( + "Estimator does not accept 'sample_weight'of type pandas.Series" + ) + return self + + def predict(self, X): + X = check_array(X) + return np.ones(X.shape[0]) + + +class BadBalancedWeightsClassifier(BaseBadClassifier): + def __init__(self, class_weight=None): + self.class_weight = class_weight + + def fit(self, X, y): + from sklearn.preprocessing import LabelEncoder + from sklearn.utils import compute_class_weight + + label_encoder = LabelEncoder().fit(y) + classes = label_encoder.classes_ + class_weight = compute_class_weight(self.class_weight, classes=classes, y=y) + + # Intentionally modify the balanced class_weight + # to simulate a bug and raise an exception + if self.class_weight == "balanced": + class_weight += 1.0 + + # Simply assigning coef_ to the class_weight + self.coef_ = class_weight + return self + + +class BadTransformerWithoutMixin(BaseEstimator): + def fit(self, X, y=None): + X = self._validate_data(X) + return self + + def transform(self, X): + X = check_array(X) + return X + + +class NotInvariantPredict(BaseEstimator): + def fit(self, X, y): + # Convert data + X, y = self._validate_data( + X, y, accept_sparse=("csr", "csc"), multi_output=True, y_numeric=True + ) + return self + + def predict(self, X): + # return 1 if X has more than one element else return 0 + X = check_array(X) + if X.shape[0] > 1: + return np.ones(X.shape[0]) + return np.zeros(X.shape[0]) + + +class NotInvariantSampleOrder(BaseEstimator): + def fit(self, X, y): + X, y = self._validate_data( + X, y, accept_sparse=("csr", "csc"), multi_output=True, y_numeric=True + ) + # store the original X to check for sample order later + self._X = X + return self + + def predict(self, X): + X = check_array(X) + # if the input contains the same elements but different sample order, + # then just return zeros. + if ( + np.array_equiv(np.sort(X, axis=0), np.sort(self._X, axis=0)) + and (X != self._X).any() + ): + return np.zeros(X.shape[0]) + return X[:, 0] + + +class OneClassSampleErrorClassifier(BaseBadClassifier): + """Classifier allowing to trigger different behaviors when `sample_weight` reduces + the number of classes to 1.""" + + def __init__(self, raise_when_single_class=False): + self.raise_when_single_class = raise_when_single_class + + def fit(self, X, y, sample_weight=None): + X, y = check_X_y( + X, y, accept_sparse=("csr", "csc"), multi_output=True, y_numeric=True + ) + + self.has_single_class_ = False + self.classes_, y = np.unique(y, return_inverse=True) + n_classes_ = self.classes_.shape[0] + if n_classes_ < 2 and self.raise_when_single_class: + self.has_single_class_ = True + raise ValueError("normal class error") + + # find the number of class after trimming + if sample_weight is not None: + if isinstance(sample_weight, np.ndarray) and len(sample_weight) > 0: + n_classes_ = np.count_nonzero(np.bincount(y, sample_weight)) + if n_classes_ < 2: + self.has_single_class_ = True + raise ValueError("Nonsensical Error") + + return self + + def predict(self, X): + check_is_fitted(self) + X = check_array(X) + if self.has_single_class_: + return np.zeros(X.shape[0]) + return np.ones(X.shape[0]) + + +class LargeSparseNotSupportedClassifier(BaseEstimator): + def fit(self, X, y): + X, y = self._validate_data( + X, + y, + accept_sparse=("csr", "csc", "coo"), + accept_large_sparse=True, + multi_output=True, + y_numeric=True, + ) + if sp.issparse(X): + if X.getformat() == "coo": + if X.row.dtype == "int64" or X.col.dtype == "int64": + raise ValueError("Estimator doesn't support 64-bit indices") + elif X.getformat() in ["csc", "csr"]: + assert "int64" not in ( + X.indices.dtype, + X.indptr.dtype, + ), "Estimator doesn't support 64-bit indices" + + return self + + +class SparseTransformer(BaseEstimator): + def __init__(self, sparse_container=None): + self.sparse_container = sparse_container + + def fit(self, X, y=None): + self.X_shape_ = self._validate_data(X).shape + return self + + def fit_transform(self, X, y=None): + return self.fit(X, y).transform(X) + + def transform(self, X): + X = check_array(X) + if X.shape[1] != self.X_shape_[1]: + raise ValueError("Bad number of features") + return self.sparse_container(X) + + +class EstimatorInconsistentForPandas(BaseEstimator): + def fit(self, X, y): + try: + from pandas import DataFrame + + if isinstance(X, DataFrame): + self.value_ = X.iloc[0, 0] + else: + X = check_array(X) + self.value_ = X[1, 0] + return self + + except ImportError: + X = check_array(X) + self.value_ = X[1, 0] + return self + + def predict(self, X): + X = check_array(X) + return np.array([self.value_] * X.shape[0]) + + +class UntaggedBinaryClassifier(SGDClassifier): + # Toy classifier that only supports binary classification, will fail tests. + def fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None): + super().fit(X, y, coef_init, intercept_init, sample_weight) + if len(self.classes_) > 2: + raise ValueError("Only 2 classes are supported") + return self + + def partial_fit(self, X, y, classes=None, sample_weight=None): + super().partial_fit(X=X, y=y, classes=classes, sample_weight=sample_weight) + if len(self.classes_) > 2: + raise ValueError("Only 2 classes are supported") + return self + + +class TaggedBinaryClassifier(UntaggedBinaryClassifier): + # Toy classifier that only supports binary classification. + def _more_tags(self): + return {"binary_only": True} + + +class EstimatorMissingDefaultTags(BaseEstimator): + def _get_tags(self): + tags = super()._get_tags().copy() + del tags["allow_nan"] + return tags + + +class RequiresPositiveXRegressor(LinearRegression): + def fit(self, X, y): + X, y = self._validate_data(X, y, multi_output=True) + if (X < 0).any(): + raise ValueError("negative X values not supported!") + return super().fit(X, y) + + def _more_tags(self): + return {"requires_positive_X": True} + + +class RequiresPositiveYRegressor(LinearRegression): + def fit(self, X, y): + X, y = self._validate_data(X, y, multi_output=True) + if (y <= 0).any(): + raise ValueError("negative y values not supported!") + return super().fit(X, y) + + def _more_tags(self): + return {"requires_positive_y": True} + + +class PoorScoreLogisticRegression(LogisticRegression): + def decision_function(self, X): + return super().decision_function(X) + 1 + + def _more_tags(self): + return {"poor_score": True} + + +class PartialFitChecksName(BaseEstimator): + def fit(self, X, y): + self._validate_data(X, y) + return self + + def partial_fit(self, X, y): + reset = not hasattr(self, "_fitted") + self._validate_data(X, y, reset=reset) + self._fitted = True + return self + + +class BrokenArrayAPI(BaseEstimator): + """Make different predictions when using Numpy and the Array API""" + + def fit(self, X, y): + return self + + def predict(self, X): + enabled = get_config()["array_api_dispatch"] + xp, _ = _array_api.get_namespace(X) + if enabled: + return xp.asarray([1, 2, 3]) + else: + return np.array([3, 2, 1]) + + +def test_check_array_api_input(): + try: + importlib.import_module("array_api_compat") + except ModuleNotFoundError: + raise SkipTest("array_api_compat is required to run this test") + try: + importlib.import_module("numpy.array_api") + except ModuleNotFoundError: # pragma: nocover + raise SkipTest("numpy.array_api is required to run this test") + + with raises(AssertionError, match="Not equal to tolerance"): + check_array_api_input( + "BrokenArrayAPI", + BrokenArrayAPI(), + array_namespace="numpy.array_api", + check_values=True, + ) + + +def test_not_an_array_array_function(): + not_array = _NotAnArray(np.ones(10)) + msg = "Don't want to call array_function sum!" + with raises(TypeError, match=msg): + np.sum(not_array) + # always returns True + assert np.may_share_memory(not_array, None) + + +def test_check_fit_score_takes_y_works_on_deprecated_fit(): + # Tests that check_fit_score_takes_y works on a class with + # a deprecated fit method + + class TestEstimatorWithDeprecatedFitMethod(BaseEstimator): + @deprecated("Deprecated for the purpose of testing check_fit_score_takes_y") + def fit(self, X, y): + return self + + check_fit_score_takes_y("test", TestEstimatorWithDeprecatedFitMethod()) + + +def test_check_estimator(): + # tests that the estimator actually fails on "bad" estimators. + # not a complete test of all checks, which are very extensive. + + # check that we have a set_params and can clone + msg = "Passing a class was deprecated" + with raises(TypeError, match=msg): + check_estimator(object) + 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_estimator(HasImmutableParameters()) # should pass + with raises(AssertionError, match=msg): + check_estimator(HasMutableParameters()) + # 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_estimator(ModifiesValueInsteadOfRaisingError()) + with warnings.catch_warnings(record=True) as records: + check_estimator(RaisesErrorInSetParams()) + assert UserWarning in [rec.category for rec in records] + + with raises(AssertionError, match=msg): + check_estimator(ModifiesAnotherValue()) + # check that we have a fit method + msg = "object has no attribute 'fit'" + with raises(AttributeError, match=msg): + check_estimator(BaseEstimator()) + # check that fit does input validation + msg = "Did not raise" + with raises(AssertionError, match=msg): + check_estimator(BaseBadClassifier()) + # check that sample_weights in fit accepts pandas.Series type + try: + from pandas import Series # noqa + + msg = ( + "Estimator NoSampleWeightPandasSeriesType raises error if " + "'sample_weight' parameter is of type pandas.Series" + ) + with raises(ValueError, match=msg): + check_estimator(NoSampleWeightPandasSeriesType()) + except ImportError: + pass + # check that predict does input validation (doesn't accept dicts in input) + msg = "Estimator NoCheckinPredict doesn't check for NaN and inf in predict" + with raises(AssertionError, match=msg): + check_estimator(NoCheckinPredict()) + # check that estimator state does not change + # at transform/predict/predict_proba time + msg = "Estimator changes __dict__ during predict" + with raises(AssertionError, match=msg): + check_estimator(ChangesDict()) + # check that `fit` only changes attributes that + # are private (start with an _ or end with a _). + msg = ( + "Estimator ChangesWrongAttribute should not change or mutate " + "the parameter wrong_attribute from 0 to 1 during fit." + ) + with raises(AssertionError, match=msg): + check_estimator(ChangesWrongAttribute()) + check_estimator(ChangesUnderscoreAttribute()) + # check that `fit` doesn't add any public attribute + msg = ( + r"Estimator adds public attribute\(s\) during the fit method." + " Estimators are only allowed to add private attributes" + " either started with _ or ended" + " with _ but wrong_attribute added" + ) + with raises(AssertionError, match=msg): + check_estimator(SetsWrongAttribute()) + # check for sample order invariance + name = NotInvariantSampleOrder.__name__ + method = "predict" + msg = ( + "{method} of {name} is not invariant when applied to a dataset" + "with different sample order." + ).format(method=method, name=name) + with raises(AssertionError, match=msg): + check_estimator(NotInvariantSampleOrder()) + # check for invariant method + name = NotInvariantPredict.__name__ + method = "predict" + msg = ("{method} of {name} is not invariant when applied to a subset.").format( + method=method, name=name + ) + with raises(AssertionError, match=msg): + check_estimator(NotInvariantPredict()) + # check for sparse matrix input handling + name = NoSparseClassifier.__name__ + msg = "Estimator %s doesn't seem to fail gracefully on sparse data" % name + with raises(AssertionError, match=msg): + check_estimator(NoSparseClassifier()) + + # check for classifiers reducing to less than two classes via sample weights + name = OneClassSampleErrorClassifier.__name__ + msg = ( + f"{name} failed when fitted on one label after sample_weight " + "trimming. Error message is not explicit, it should have " + "'class'." + ) + with raises(AssertionError, match=msg): + check_estimator(OneClassSampleErrorClassifier()) + + # Large indices test on bad estimator + msg = ( + "Estimator LargeSparseNotSupportedClassifier doesn't seem to " + r"support \S{3}_64 matrix, and is not failing gracefully.*" + ) + with raises(AssertionError, match=msg): + check_estimator(LargeSparseNotSupportedClassifier()) + + # does error on binary_only untagged estimator + msg = "Only 2 classes are supported" + with raises(ValueError, match=msg): + check_estimator(UntaggedBinaryClassifier()) + + for csr_container in CSR_CONTAINERS: + # non-regression test for estimators transforming to sparse data + check_estimator(SparseTransformer(sparse_container=csr_container)) + + # doesn't error on actual estimator + check_estimator(LogisticRegression()) + check_estimator(LogisticRegression(C=0.01)) + check_estimator(MultiTaskElasticNet()) + + # doesn't error on binary_only tagged estimator + check_estimator(TaggedBinaryClassifier()) + check_estimator(RequiresPositiveXRegressor()) + + # Check regressor with requires_positive_y estimator tag + msg = "negative y values not supported!" + with raises(ValueError, match=msg): + check_estimator(RequiresPositiveYRegressor()) + + # Does not raise error on classifier with poor_score tag + check_estimator(PoorScoreLogisticRegression()) + + +def test_check_outlier_corruption(): + # should raise AssertionError + decision = np.array([0.0, 1.0, 1.5, 2.0]) + with raises(AssertionError): + check_outlier_corruption(1, 2, decision) + # should pass + decision = np.array([0.0, 1.0, 1.0, 2.0]) + check_outlier_corruption(1, 2, decision) + + +def test_check_estimator_transformer_no_mixin(): + # check that TransformerMixin is not required for transformer tests to run + with raises(AttributeError, ".*fit_transform.*"): + check_estimator(BadTransformerWithoutMixin()) + + +def test_check_estimator_clones(): + # check that check_estimator doesn't modify the estimator it receives + from sklearn.datasets import load_iris + + iris = load_iris() + + for Estimator in [ + GaussianMixture, + LinearRegression, + SGDClassifier, + PCA, + ExtraTreesClassifier, + MiniBatchKMeans, + ]: + # without fitting + with ignore_warnings(category=ConvergenceWarning): + est = Estimator() + _set_checking_parameters(est) + set_random_state(est) + old_hash = joblib.hash(est) + check_estimator(est) + assert old_hash == joblib.hash(est) + + # with fitting + with ignore_warnings(category=ConvergenceWarning): + est = Estimator() + _set_checking_parameters(est) + set_random_state(est) + est.fit(iris.data + 10, iris.target) + old_hash = joblib.hash(est) + check_estimator(est) + assert old_hash == joblib.hash(est) + + +def test_check_estimators_unfitted(): + # check that a ValueError/AttributeError is raised when calling predict + # on an unfitted estimator + msg = "Did not raise" + with raises(AssertionError, match=msg): + check_estimators_unfitted("estimator", NoSparseClassifier()) + + # check that CorrectNotFittedError inherit from either ValueError + # or AttributeError + check_estimators_unfitted("estimator", CorrectNotFittedErrorClassifier()) + + +def test_check_no_attributes_set_in_init(): + class NonConformantEstimatorPrivateSet(BaseEstimator): + def __init__(self): + self.you_should_not_set_this_ = None + + class NonConformantEstimatorNoParamSet(BaseEstimator): + def __init__(self, you_should_set_this_=None): + pass + + class ConformantEstimatorClassAttribute(BaseEstimator): + # making sure our __metadata_request__* class attributes are okay! + __metadata_request__fit = {"foo": True} + + msg = ( + "Estimator estimator_name should not set any" + " attribute apart from parameters during init." + r" Found attributes \['you_should_not_set_this_'\]." + ) + with raises(AssertionError, match=msg): + check_no_attributes_set_in_init( + "estimator_name", NonConformantEstimatorPrivateSet() + ) + + msg = ( + "Estimator estimator_name should store all parameters as an attribute" + " during init" + ) + with raises(AttributeError, match=msg): + check_no_attributes_set_in_init( + "estimator_name", NonConformantEstimatorNoParamSet() + ) + + # a private class attribute is okay! + check_no_attributes_set_in_init( + "estimator_name", ConformantEstimatorClassAttribute() + ) + # also check if cloning an estimator which has non-default set requests is + # fine. Setting a non-default value via `set_{method}_request` sets the + # private _metadata_request instance attribute which is copied in `clone`. + with config_context(enable_metadata_routing=True): + check_no_attributes_set_in_init( + "estimator_name", + ConformantEstimatorClassAttribute().set_fit_request(foo=True), + ) + + +def test_check_estimator_pairwise(): + # check that check_estimator() works on estimator with _pairwise + # kernel or metric + + # test precomputed kernel + est = SVC(kernel="precomputed") + check_estimator(est) + + # test precomputed metric + est = KNeighborsRegressor(metric="precomputed") + check_estimator(est) + + +def test_check_classifier_data_not_an_array(): + with raises(AssertionError, match="Not equal to tolerance"): + check_classifier_data_not_an_array( + "estimator_name", EstimatorInconsistentForPandas() + ) + + +def test_check_regressor_data_not_an_array(): + with raises(AssertionError, match="Not equal to tolerance"): + check_regressor_data_not_an_array( + "estimator_name", EstimatorInconsistentForPandas() + ) + + +def test_check_estimator_get_tags_default_keys(): + estimator = EstimatorMissingDefaultTags() + err_msg = ( + r"EstimatorMissingDefaultTags._get_tags\(\) is missing entries" + r" for the following default tags: {'allow_nan'}" + ) + with raises(AssertionError, match=err_msg): + check_estimator_get_tags_default_keys(estimator.__class__.__name__, estimator) + + # noop check when _get_tags is not available + estimator = MinimalTransformer() + check_estimator_get_tags_default_keys(estimator.__class__.__name__, estimator) + + +def test_check_dataframe_column_names_consistency(): + err_msg = "Estimator does not have a feature_names_in_" + with raises(ValueError, match=err_msg): + check_dataframe_column_names_consistency("estimator_name", BaseBadClassifier()) + check_dataframe_column_names_consistency("estimator_name", PartialFitChecksName()) + + lr = LogisticRegression() + check_dataframe_column_names_consistency(lr.__class__.__name__, lr) + lr.__doc__ = "Docstring that does not document the estimator's attributes" + err_msg = ( + "Estimator LogisticRegression does not document its feature_names_in_ attribute" + ) + with raises(ValueError, match=err_msg): + check_dataframe_column_names_consistency(lr.__class__.__name__, lr) + + +class _BaseMultiLabelClassifierMock(ClassifierMixin, BaseEstimator): + def __init__(self, response_output): + self.response_output = response_output + + def fit(self, X, y): + return self + + def _more_tags(self): + return {"multilabel": True} + + +def test_check_classifiers_multilabel_output_format_predict(): + n_samples, test_size, n_outputs = 100, 25, 5 + _, y = make_multilabel_classification( + n_samples=n_samples, + n_features=2, + n_classes=n_outputs, + n_labels=3, + length=50, + allow_unlabeled=True, + random_state=0, + ) + y_test = y[-test_size:] + + class MultiLabelClassifierPredict(_BaseMultiLabelClassifierMock): + def predict(self, X): + return self.response_output + + # 1. inconsistent array type + clf = MultiLabelClassifierPredict(response_output=y_test.tolist()) + err_msg = ( + r"MultiLabelClassifierPredict.predict is expected to output a " + r"NumPy array. Got instead." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict(clf.__class__.__name__, clf) + # 2. inconsistent shape + clf = MultiLabelClassifierPredict(response_output=y_test[:, :-1]) + err_msg = ( + r"MultiLabelClassifierPredict.predict outputs a NumPy array of " + r"shape \(25, 4\) instead of \(25, 5\)." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict(clf.__class__.__name__, clf) + # 3. inconsistent dtype + clf = MultiLabelClassifierPredict(response_output=y_test.astype(np.float64)) + err_msg = ( + r"MultiLabelClassifierPredict.predict does not output the same " + r"dtype than the targets." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict(clf.__class__.__name__, clf) + + +def test_check_classifiers_multilabel_output_format_predict_proba(): + n_samples, test_size, n_outputs = 100, 25, 5 + _, y = make_multilabel_classification( + n_samples=n_samples, + n_features=2, + n_classes=n_outputs, + n_labels=3, + length=50, + allow_unlabeled=True, + random_state=0, + ) + y_test = y[-test_size:] + + class MultiLabelClassifierPredictProba(_BaseMultiLabelClassifierMock): + def predict_proba(self, X): + return self.response_output + + for csr_container in CSR_CONTAINERS: + # 1. unknown output type + clf = MultiLabelClassifierPredictProba(response_output=csr_container(y_test)) + err_msg = ( + f"Unknown returned type .*{csr_container.__name__}.* by " + r"MultiLabelClassifierPredictProba.predict_proba. A list or a Numpy " + r"array is expected." + ) + with raises(ValueError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 2. for list output + # 2.1. inconsistent length + clf = MultiLabelClassifierPredictProba(response_output=y_test.tolist()) + err_msg = ( + "When MultiLabelClassifierPredictProba.predict_proba returns a list, " + "the list should be of length n_outputs and contain NumPy arrays. Got " + f"length of {test_size} instead of {n_outputs}." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 2.2. array of inconsistent shape + response_output = [np.ones_like(y_test) for _ in range(n_outputs)] + clf = MultiLabelClassifierPredictProba(response_output=response_output) + err_msg = ( + r"When MultiLabelClassifierPredictProba.predict_proba returns a list, " + r"this list should contain NumPy arrays of shape \(n_samples, 2\). Got " + r"NumPy arrays of shape \(25, 5\) instead of \(25, 2\)." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 2.3. array of inconsistent dtype + response_output = [ + np.ones(shape=(y_test.shape[0], 2), dtype=np.int64) for _ in range(n_outputs) + ] + clf = MultiLabelClassifierPredictProba(response_output=response_output) + err_msg = ( + "When MultiLabelClassifierPredictProba.predict_proba returns a list, " + "it should contain NumPy arrays with floating dtype." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 2.4. array does not contain probability (each row should sum to 1) + response_output = [ + np.ones(shape=(y_test.shape[0], 2), dtype=np.float64) for _ in range(n_outputs) + ] + clf = MultiLabelClassifierPredictProba(response_output=response_output) + err_msg = ( + r"When MultiLabelClassifierPredictProba.predict_proba returns a list, " + r"each NumPy array should contain probabilities for each class and " + r"thus each row should sum to 1" + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 3 for array output + # 3.1. array of inconsistent shape + clf = MultiLabelClassifierPredictProba(response_output=y_test[:, :-1]) + err_msg = ( + r"When MultiLabelClassifierPredictProba.predict_proba returns a NumPy " + r"array, the expected shape is \(n_samples, n_outputs\). Got \(25, 4\)" + r" instead of \(25, 5\)." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 3.2. array of inconsistent dtype + response_output = np.zeros_like(y_test, dtype=np.int64) + clf = MultiLabelClassifierPredictProba(response_output=response_output) + err_msg = ( + r"When MultiLabelClassifierPredictProba.predict_proba returns a NumPy " + r"array, the expected data type is floating." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 4. array does not contain probabilities + clf = MultiLabelClassifierPredictProba(response_output=y_test * 2.0) + err_msg = ( + r"When MultiLabelClassifierPredictProba.predict_proba returns a NumPy " + r"array, this array is expected to provide probabilities of the " + r"positive class and should therefore contain values between 0 and 1." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + + +def test_check_classifiers_multilabel_output_format_decision_function(): + n_samples, test_size, n_outputs = 100, 25, 5 + _, y = make_multilabel_classification( + n_samples=n_samples, + n_features=2, + n_classes=n_outputs, + n_labels=3, + length=50, + allow_unlabeled=True, + random_state=0, + ) + y_test = y[-test_size:] + + class MultiLabelClassifierDecisionFunction(_BaseMultiLabelClassifierMock): + def decision_function(self, X): + return self.response_output + + # 1. inconsistent array type + clf = MultiLabelClassifierDecisionFunction(response_output=y_test.tolist()) + err_msg = ( + r"MultiLabelClassifierDecisionFunction.decision_function is expected " + r"to output a NumPy array. Got instead." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_decision_function( + clf.__class__.__name__, + clf, + ) + # 2. inconsistent shape + clf = MultiLabelClassifierDecisionFunction(response_output=y_test[:, :-1]) + err_msg = ( + r"MultiLabelClassifierDecisionFunction.decision_function is expected " + r"to provide a NumPy array of shape \(n_samples, n_outputs\). Got " + r"\(25, 4\) instead of \(25, 5\)" + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_decision_function( + clf.__class__.__name__, + clf, + ) + # 3. inconsistent dtype + clf = MultiLabelClassifierDecisionFunction(response_output=y_test) + err_msg = ( + r"MultiLabelClassifierDecisionFunction.decision_function is expected " + r"to output a floating dtype." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_decision_function( + clf.__class__.__name__, + clf, + ) + + +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) + + +def test_check_class_weight_balanced_linear_classifier(): + # check that ill-computed balanced weights raises an exception + msg = "Classifier estimator_name is not computing class_weight=balanced properly" + with raises(AssertionError, match=msg): + check_class_weight_balanced_linear_classifier( + "estimator_name", BadBalancedWeightsClassifier + ) + + +def test_all_estimators_all_public(): + # all_estimator should not fail when pytest is not installed and return + # only public estimators + with warnings.catch_warnings(record=True) as record: + estimators = all_estimators() + # no warnings are raised + assert not record + for est in estimators: + assert not est.__class__.__name__.startswith("_") + + +if __name__ == "__main__": + # This module is run as a script to check that we have no dependency on + # pytest for estimator checks. + run_tests_without_pytest() + + +def test_xfail_ignored_in_check_estimator(): + # Make sure checks marked as xfail are just ignored and not run by + # check_estimator(), but still raise a warning. + with warnings.catch_warnings(record=True) as records: + check_estimator(NuSVC()) + assert SkipTestWarning in [rec.category for rec in records] + + +# FIXME: this test should be uncommented when the checks will be granular +# enough. In 0.24, these tests fail due to low estimator performance. +def test_minimal_class_implementation_checks(): + # Check that third-party library can run tests without inheriting from + # BaseEstimator. + # FIXME + raise SkipTest + minimal_estimators = [MinimalTransformer(), MinimalRegressor(), MinimalClassifier()] + for estimator in minimal_estimators: + check_estimator(estimator) + + +def test_check_fit_check_is_fitted(): + class Estimator(BaseEstimator): + def __init__(self, behavior="attribute"): + self.behavior = behavior + + def fit(self, X, y, **kwargs): + if self.behavior == "attribute": + self.is_fitted_ = True + elif self.behavior == "method": + self._is_fitted = True + return self + + @available_if(lambda self: self.behavior in {"method", "always-true"}) + def __sklearn_is_fitted__(self): + if self.behavior == "always-true": + return True + return hasattr(self, "_is_fitted") + + with raises(Exception, match="passes check_is_fitted before being fit"): + check_fit_check_is_fitted("estimator", Estimator(behavior="always-true")) + + check_fit_check_is_fitted("estimator", Estimator(behavior="method")) + check_fit_check_is_fitted("estimator", Estimator(behavior="attribute")) + + +def test_check_requires_y_none(): + class Estimator(BaseEstimator): + def fit(self, X, y): + X, y = check_X_y(X, y) + + with warnings.catch_warnings(record=True) as record: + check_requires_y_none("estimator", Estimator()) + + # no warnings are raised + assert not [r.message for r in record] + + +def test_non_deterministic_estimator_skip_tests(): + # check estimators with non_deterministic tag set to True + # will skip certain tests, refer to issue #22313 for details + for est in [MinimalTransformer, MinimalRegressor, MinimalClassifier]: + all_tests = list(_yield_all_checks(est())) + assert check_methods_sample_order_invariance in all_tests + assert check_methods_subset_invariance in all_tests + + class Estimator(est): + def _more_tags(self): + return {"non_deterministic": True} + + all_tests = list(_yield_all_checks(Estimator())) + assert check_methods_sample_order_invariance not in all_tests + assert check_methods_subset_invariance not in all_tests + + +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) + + +def test_decision_proba_tie_ranking(): + """Check that in case with some probabilities ties, we relax the + ranking comparison with the decision function. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/24025 + """ + estimator = SGDClassifier(loss="log_loss") + check_decision_proba_consistency("SGDClassifier", estimator) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_extmath.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_extmath.py new file mode 100644 index 0000000000000000000000000000000000000000..fc2eab70f007b0e365e4dc6b8793a5dd262ec701 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_extmath.py @@ -0,0 +1,1064 @@ +# Authors: Olivier Grisel +# Mathieu Blondel +# Denis Engemann +# +# License: BSD 3 clause +import numpy as np +import pytest +from scipy import linalg, sparse +from scipy.linalg import eigh +from scipy.sparse.linalg import eigsh +from scipy.special import expit + +from sklearn.datasets import make_low_rank_matrix, make_sparse_spd_matrix +from sklearn.utils import gen_batches +from sklearn.utils._arpack import _init_arpack_v0 +from sklearn.utils._testing import ( + assert_allclose, + assert_allclose_dense_sparse, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, + skip_if_32bit, +) +from sklearn.utils.extmath import ( + _deterministic_vector_sign_flip, + _incremental_mean_and_var, + _randomized_eigsh, + _safe_accumulator_op, + cartesian, + density, + log_logistic, + randomized_svd, + row_norms, + safe_sparse_dot, + softmax, + stable_cumsum, + svd_flip, + weighted_mode, +) +from sklearn.utils.fixes import ( + COO_CONTAINERS, + CSC_CONTAINERS, + CSR_CONTAINERS, + DOK_CONTAINERS, + LIL_CONTAINERS, + _mode, +) + + +@pytest.mark.parametrize( + "sparse_container", + COO_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS + LIL_CONTAINERS, +) +def test_density(sparse_container): + rng = np.random.RandomState(0) + X = rng.randint(10, size=(10, 5)) + X[1, 2] = 0 + X[5, 3] = 0 + + assert density(sparse_container(X)) == density(X) + + +def test_uniform_weights(): + # with uniform weights, results should be identical to stats.mode + rng = np.random.RandomState(0) + x = rng.randint(10, size=(10, 5)) + weights = np.ones(x.shape) + + for axis in (None, 0, 1): + mode, score = _mode(x, axis) + mode2, score2 = weighted_mode(x, weights, axis=axis) + + assert_array_equal(mode, mode2) + assert_array_equal(score, score2) + + +def test_random_weights(): + # set this up so that each row should have a weighted mode of 6, + # with a score that is easily reproduced + mode_result = 6 + + rng = np.random.RandomState(0) + x = rng.randint(mode_result, size=(100, 10)) + w = rng.random_sample(x.shape) + + x[:, :5] = mode_result + w[:, :5] += 1 + + mode, score = weighted_mode(x, w, axis=1) + + assert_array_equal(mode, mode_result) + assert_array_almost_equal(score.ravel(), w[:, :5].sum(1)) + + +@pytest.mark.parametrize("dtype", (np.int32, np.int64, np.float32, np.float64)) +def test_randomized_svd_low_rank_all_dtypes(dtype): + # Check that extmath.randomized_svd is consistent with linalg.svd + n_samples = 100 + n_features = 500 + rank = 5 + k = 10 + decimal = 5 if dtype == np.float32 else 7 + dtype = np.dtype(dtype) + + # generate a matrix X of approximate effective rank `rank` and no noise + # component (very structured signal): + X = make_low_rank_matrix( + n_samples=n_samples, + n_features=n_features, + effective_rank=rank, + tail_strength=0.0, + random_state=0, + ).astype(dtype, copy=False) + assert X.shape == (n_samples, n_features) + + # compute the singular values of X using the slow exact method + U, s, Vt = linalg.svd(X, full_matrices=False) + + # Convert the singular values to the specific dtype + U = U.astype(dtype, copy=False) + s = s.astype(dtype, copy=False) + Vt = Vt.astype(dtype, copy=False) + + for normalizer in ["auto", "LU", "QR"]: # 'none' would not be stable + # compute the singular values of X using the fast approximate method + Ua, sa, Va = randomized_svd( + X, k, power_iteration_normalizer=normalizer, random_state=0 + ) + + # If the input dtype is float, then the output dtype is float of the + # same bit size (f32 is not upcast to f64) + # But if the input dtype is int, the output dtype is float64 + if dtype.kind == "f": + assert Ua.dtype == dtype + assert sa.dtype == dtype + assert Va.dtype == dtype + else: + assert Ua.dtype == np.float64 + assert sa.dtype == np.float64 + assert Va.dtype == np.float64 + + assert Ua.shape == (n_samples, k) + assert sa.shape == (k,) + assert Va.shape == (k, n_features) + + # ensure that the singular values of both methods are equal up to the + # real rank of the matrix + assert_almost_equal(s[:k], sa, decimal=decimal) + + # check the singular vectors too (while not checking the sign) + assert_almost_equal( + np.dot(U[:, :k], Vt[:k, :]), np.dot(Ua, Va), decimal=decimal + ) + + # check the sparse matrix representation + for csr_container in CSR_CONTAINERS: + X = csr_container(X) + + # compute the singular values of X using the fast approximate method + Ua, sa, Va = randomized_svd( + X, k, power_iteration_normalizer=normalizer, random_state=0 + ) + if dtype.kind == "f": + assert Ua.dtype == dtype + assert sa.dtype == dtype + assert Va.dtype == dtype + else: + assert Ua.dtype.kind == "f" + assert sa.dtype.kind == "f" + assert Va.dtype.kind == "f" + + assert_almost_equal(s[:rank], sa[:rank], decimal=decimal) + + +@pytest.mark.parametrize("dtype", (np.int32, np.int64, np.float32, np.float64)) +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") + + +@pytest.mark.parametrize("k", (10, 50, 100, 199, 200)) +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) + + +@pytest.mark.parametrize( + "n,rank", + [ + (10, 7), + (100, 10), + (100, 80), + (500, 10), + (500, 250), + (500, 400), + ], +) +def test_randomized_eigsh_reconst_low_rank(n, rank): + """Check that randomized_eigsh is able to reconstruct a low rank psd matrix + + Tests that the decomposition provided by `_randomized_eigsh` leads to + orthonormal eigenvectors, and that a low rank PSD matrix can be effectively + reconstructed with good accuracy using it. + """ + assert rank < n + + # create a low rank PSD + rng = np.random.RandomState(69) + X = rng.randn(n, rank) + A = X @ X.T + + # approximate A with the "right" number of components + S, V = _randomized_eigsh(A, n_components=rank, random_state=rng) + # orthonormality checks + assert_array_almost_equal(np.linalg.norm(V, axis=0), np.ones(S.shape)) + assert_array_almost_equal(V.T @ V, np.diag(np.ones(S.shape))) + # reconstruction + A_reconstruct = V @ np.diag(S) @ V.T + + # test that the approximation is good + assert_array_almost_equal(A_reconstruct, A, decimal=6) + + +@pytest.mark.parametrize("dtype", (np.float32, np.float64)) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_row_norms(dtype, csr_container): + X = np.random.RandomState(42).randn(100, 100) + if dtype is np.float32: + precision = 4 + else: + precision = 5 + + X = X.astype(dtype, copy=False) + sq_norm = (X**2).sum(axis=1) + + assert_array_almost_equal(sq_norm, row_norms(X, squared=True), precision) + assert_array_almost_equal(np.sqrt(sq_norm), row_norms(X), precision) + + for csr_index_dtype in [np.int32, np.int64]: + Xcsr = csr_container(X, dtype=dtype) + # csr_matrix will use int32 indices by default, + # up-casting those to int64 when necessary + if csr_index_dtype is np.int64: + Xcsr.indptr = Xcsr.indptr.astype(csr_index_dtype, copy=False) + Xcsr.indices = Xcsr.indices.astype(csr_index_dtype, copy=False) + assert Xcsr.indices.dtype == csr_index_dtype + assert Xcsr.indptr.dtype == csr_index_dtype + assert_array_almost_equal(sq_norm, row_norms(Xcsr, squared=True), precision) + assert_array_almost_equal(np.sqrt(sq_norm), row_norms(Xcsr), precision) + + +def test_randomized_svd_low_rank_with_noise(): + # Check that extmath.randomized_svd can handle noisy matrices + n_samples = 100 + n_features = 500 + rank = 5 + k = 10 + + # generate a matrix X wity structure approximate rank `rank` and an + # important noisy component + X = make_low_rank_matrix( + n_samples=n_samples, + n_features=n_features, + effective_rank=rank, + tail_strength=0.1, + random_state=0, + ) + assert X.shape == (n_samples, n_features) + + # compute the singular values of X using the slow exact method + _, s, _ = linalg.svd(X, full_matrices=False) + + for normalizer in ["auto", "none", "LU", "QR"]: + # compute the singular values of X using the fast approximate + # method without the iterated power method + _, sa, _ = randomized_svd( + X, k, n_iter=0, power_iteration_normalizer=normalizer, random_state=0 + ) + + # the approximation does not tolerate the noise: + assert np.abs(s[:k] - sa).max() > 0.01 + + # compute the singular values of X using the fast approximate + # method with iterated power method + _, sap, _ = randomized_svd( + X, k, power_iteration_normalizer=normalizer, random_state=0 + ) + + # the iterated power method is helping getting rid of the noise: + assert_almost_equal(s[:k], sap, decimal=3) + + +def test_randomized_svd_infinite_rank(): + # Check that extmath.randomized_svd can handle noisy matrices + n_samples = 100 + n_features = 500 + rank = 5 + k = 10 + + # let us try again without 'low_rank component': just regularly but slowly + # decreasing singular values: the rank of the data matrix is infinite + X = make_low_rank_matrix( + n_samples=n_samples, + n_features=n_features, + effective_rank=rank, + tail_strength=1.0, + random_state=0, + ) + assert X.shape == (n_samples, n_features) + + # compute the singular values of X using the slow exact method + _, s, _ = linalg.svd(X, full_matrices=False) + for normalizer in ["auto", "none", "LU", "QR"]: + # compute the singular values of X using the fast approximate method + # without the iterated power method + _, sa, _ = randomized_svd( + X, k, n_iter=0, power_iteration_normalizer=normalizer, random_state=0 + ) + + # the approximation does not tolerate the noise: + assert np.abs(s[:k] - sa).max() > 0.1 + + # compute the singular values of X using the fast approximate method + # with iterated power method + _, sap, _ = randomized_svd( + X, k, n_iter=5, power_iteration_normalizer=normalizer, random_state=0 + ) + + # the iterated power method is still managing to get most of the + # structure at the requested rank + assert_almost_equal(s[:k], sap, decimal=3) + + +def test_randomized_svd_transpose_consistency(): + # Check that transposing the design matrix has limited impact + n_samples = 100 + n_features = 500 + rank = 4 + k = 10 + + X = make_low_rank_matrix( + n_samples=n_samples, + n_features=n_features, + effective_rank=rank, + tail_strength=0.5, + random_state=0, + ) + assert X.shape == (n_samples, n_features) + + U1, s1, V1 = randomized_svd(X, k, n_iter=3, transpose=False, random_state=0) + U2, s2, V2 = randomized_svd(X, k, n_iter=3, transpose=True, random_state=0) + U3, s3, V3 = randomized_svd(X, k, n_iter=3, transpose="auto", random_state=0) + U4, s4, V4 = linalg.svd(X, full_matrices=False) + + assert_almost_equal(s1, s4[:k], decimal=3) + assert_almost_equal(s2, s4[:k], decimal=3) + assert_almost_equal(s3, s4[:k], decimal=3) + + assert_almost_equal(np.dot(U1, V1), np.dot(U4[:, :k], V4[:k, :]), decimal=2) + assert_almost_equal(np.dot(U2, V2), np.dot(U4[:, :k], V4[:k, :]), decimal=2) + + # in this case 'auto' is equivalent to transpose + assert_almost_equal(s2, s3) + + +def test_randomized_svd_power_iteration_normalizer(): + # randomized_svd with power_iteration_normalized='none' diverges for + # large number of power iterations on this dataset + rng = np.random.RandomState(42) + X = make_low_rank_matrix(100, 500, effective_rank=50, random_state=rng) + X += 3 * rng.randint(0, 2, size=X.shape) + n_components = 50 + + # Check that it diverges with many (non-normalized) power iterations + U, s, Vt = randomized_svd( + X, n_components, n_iter=2, power_iteration_normalizer="none", random_state=0 + ) + A = X - U.dot(np.diag(s).dot(Vt)) + error_2 = linalg.norm(A, ord="fro") + U, s, Vt = randomized_svd( + X, n_components, n_iter=20, power_iteration_normalizer="none", random_state=0 + ) + A = X - U.dot(np.diag(s).dot(Vt)) + error_20 = linalg.norm(A, ord="fro") + assert np.abs(error_2 - error_20) > 100 + + for normalizer in ["LU", "QR", "auto"]: + U, s, Vt = randomized_svd( + X, + n_components, + n_iter=2, + power_iteration_normalizer=normalizer, + random_state=0, + ) + A = X - U.dot(np.diag(s).dot(Vt)) + error_2 = linalg.norm(A, ord="fro") + + for i in [5, 10, 50]: + U, s, Vt = randomized_svd( + X, + n_components, + n_iter=i, + power_iteration_normalizer=normalizer, + random_state=0, + ) + A = X - U.dot(np.diag(s).dot(Vt)) + error = linalg.norm(A, ord="fro") + assert 15 > np.abs(error_2 - error) + + +@pytest.mark.parametrize("sparse_container", DOK_CONTAINERS + LIL_CONTAINERS) +def test_randomized_svd_sparse_warnings(sparse_container): + # randomized_svd throws a warning for lil and dok matrix + rng = np.random.RandomState(42) + X = make_low_rank_matrix(50, 20, effective_rank=10, random_state=rng) + n_components = 5 + + X = sparse_container(X) + warn_msg = ( + "Calculating SVD of a {} is expensive. csr_matrix is more efficient.".format( + sparse_container.__name__ + ) + ) + with pytest.warns(sparse.SparseEfficiencyWarning, match=warn_msg): + randomized_svd(X, n_components, n_iter=1, power_iteration_normalizer="none") + + +def test_svd_flip(): + # Check that svd_flip works in both situations, and reconstructs input. + rs = np.random.RandomState(1999) + n_samples = 20 + n_features = 10 + X = rs.randn(n_samples, n_features) + + # Check matrix reconstruction + U, S, Vt = linalg.svd(X, full_matrices=False) + U1, V1 = svd_flip(U, Vt, u_based_decision=False) + assert_almost_equal(np.dot(U1 * S, V1), X, decimal=6) + + # Check transposed matrix reconstruction + XT = X.T + U, S, Vt = linalg.svd(XT, full_matrices=False) + U2, V2 = svd_flip(U, Vt, u_based_decision=True) + assert_almost_equal(np.dot(U2 * S, V2), XT, decimal=6) + + # Check that different flip methods are equivalent under reconstruction + U_flip1, V_flip1 = svd_flip(U, Vt, u_based_decision=True) + assert_almost_equal(np.dot(U_flip1 * S, V_flip1), XT, decimal=6) + U_flip2, V_flip2 = svd_flip(U, Vt, u_based_decision=False) + assert_almost_equal(np.dot(U_flip2 * S, V_flip2), XT, decimal=6) + + +@pytest.mark.parametrize("n_samples, n_features", [(3, 4), (4, 3)]) +def test_svd_flip_max_abs_cols(n_samples, n_features, global_random_seed): + rs = np.random.RandomState(global_random_seed) + X = rs.randn(n_samples, n_features) + U, _, Vt = linalg.svd(X, full_matrices=False) + + U1, _ = svd_flip(U, Vt, u_based_decision=True) + max_abs_U1_row_idx_for_col = np.argmax(np.abs(U1), axis=0) + assert (U1[max_abs_U1_row_idx_for_col, np.arange(U1.shape[1])] >= 0).all() + + _, V2 = svd_flip(U, Vt, u_based_decision=False) + max_abs_V2_col_idx_for_row = np.argmax(np.abs(V2), axis=1) + assert (V2[np.arange(V2.shape[0]), max_abs_V2_col_idx_for_row] >= 0).all() + + +def test_randomized_svd_sign_flip(): + a = np.array([[2.0, 0.0], [0.0, 1.0]]) + u1, s1, v1 = randomized_svd(a, 2, flip_sign=True, random_state=41) + for seed in range(10): + u2, s2, v2 = randomized_svd(a, 2, flip_sign=True, random_state=seed) + assert_almost_equal(u1, u2) + assert_almost_equal(v1, v2) + assert_almost_equal(np.dot(u2 * s2, v2), a) + assert_almost_equal(np.dot(u2.T, u2), np.eye(2)) + assert_almost_equal(np.dot(v2.T, v2), np.eye(2)) + + +def test_randomized_svd_sign_flip_with_transpose(): + # Check if the randomized_svd sign flipping is always done based on u + # irrespective of transpose. + # See https://github.com/scikit-learn/scikit-learn/issues/5608 + # for more details. + def max_loading_is_positive(u, v): + """ + returns bool tuple indicating if the values maximising np.abs + are positive across all rows for u and across all columns for v. + """ + u_based = (np.abs(u).max(axis=0) == u.max(axis=0)).all() + v_based = (np.abs(v).max(axis=1) == v.max(axis=1)).all() + return u_based, v_based + + mat = np.arange(10 * 8).reshape(10, -1) + + # Without transpose + u_flipped, _, v_flipped = randomized_svd(mat, 3, flip_sign=True, random_state=0) + u_based, v_based = max_loading_is_positive(u_flipped, v_flipped) + assert u_based + assert not v_based + + # With transpose + u_flipped_with_transpose, _, v_flipped_with_transpose = randomized_svd( + mat, 3, flip_sign=True, transpose=True, random_state=0 + ) + u_based, v_based = max_loading_is_positive( + u_flipped_with_transpose, v_flipped_with_transpose + ) + assert u_based + assert not v_based + + +@pytest.mark.parametrize("n", [50, 100, 300]) +@pytest.mark.parametrize("m", [50, 100, 300]) +@pytest.mark.parametrize("k", [10, 20, 50]) +@pytest.mark.parametrize("seed", range(5)) +def test_randomized_svd_lapack_driver(n, m, k, seed): + # Check that different SVD drivers provide consistent results + + # Matrix being compressed + rng = np.random.RandomState(seed) + X = rng.rand(n, m) + + # Number of components + u1, s1, vt1 = randomized_svd(X, k, svd_lapack_driver="gesdd", random_state=0) + u2, s2, vt2 = randomized_svd(X, k, svd_lapack_driver="gesvd", random_state=0) + + # Check shape and contents + assert u1.shape == u2.shape + assert_allclose(u1, u2, atol=0, rtol=1e-3) + + assert s1.shape == s2.shape + assert_allclose(s1, s2, atol=0, rtol=1e-3) + + assert vt1.shape == vt2.shape + assert_allclose(vt1, vt2, atol=0, rtol=1e-3) + + +def test_cartesian(): + # Check if cartesian product delivers the right results + + axes = (np.array([1, 2, 3]), np.array([4, 5]), np.array([6, 7])) + + true_out = np.array( + [ + [1, 4, 6], + [1, 4, 7], + [1, 5, 6], + [1, 5, 7], + [2, 4, 6], + [2, 4, 7], + [2, 5, 6], + [2, 5, 7], + [3, 4, 6], + [3, 4, 7], + [3, 5, 6], + [3, 5, 7], + ] + ) + + out = cartesian(axes) + assert_array_equal(true_out, out) + + # check single axis + x = np.arange(3) + assert_array_equal(x[:, np.newaxis], cartesian((x,))) + + +@pytest.mark.parametrize( + "arrays, output_dtype", + [ + ( + [np.array([1, 2, 3], dtype=np.int32), np.array([4, 5], dtype=np.int64)], + np.dtype(np.int64), + ), + ( + [np.array([1, 2, 3], dtype=np.int32), np.array([4, 5], dtype=np.float64)], + np.dtype(np.float64), + ), + ( + [np.array([1, 2, 3], dtype=np.int32), np.array(["x", "y"], dtype=object)], + np.dtype(object), + ), + ], +) +def test_cartesian_mix_types(arrays, output_dtype): + """Check that the cartesian product works with mixed types.""" + output = cartesian(arrays) + + assert output.dtype == output_dtype + + +# TODO(1.6): remove this test +def test_logistic_sigmoid(): + # Check correctness and robustness of logistic sigmoid implementation + def naive_log_logistic(x): + return np.log(expit(x)) + + x = np.linspace(-2, 2, 50) + warn_msg = "`log_logistic` is deprecated and will be removed" + with pytest.warns(FutureWarning, match=warn_msg): + assert_array_almost_equal(log_logistic(x), naive_log_logistic(x)) + + extreme_x = np.array([-100.0, 100.0]) + with pytest.warns(FutureWarning, match=warn_msg): + assert_array_almost_equal(log_logistic(extreme_x), [-100, 0]) + + +@pytest.fixture() +def rng(): + return np.random.RandomState(42) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_incremental_weighted_mean_and_variance_simple(rng, dtype): + mult = 10 + X = rng.rand(1000, 20).astype(dtype) * mult + sample_weight = rng.rand(X.shape[0]) * mult + mean, var, _ = _incremental_mean_and_var(X, 0, 0, 0, sample_weight=sample_weight) + + expected_mean = np.average(X, weights=sample_weight, axis=0) + expected_var = ( + np.average(X**2, weights=sample_weight, axis=0) - expected_mean**2 + ) + assert_almost_equal(mean, expected_mean) + assert_almost_equal(var, expected_var) + + +@pytest.mark.parametrize("mean", [0, 1e7, -1e7]) +@pytest.mark.parametrize("var", [1, 1e-8, 1e5]) +@pytest.mark.parametrize( + "weight_loc, weight_scale", [(0, 1), (0, 1e-8), (1, 1e-8), (10, 1), (1e7, 1)] +) +def test_incremental_weighted_mean_and_variance( + mean, var, weight_loc, weight_scale, rng +): + # Testing of correctness and numerical stability + def _assert(X, sample_weight, expected_mean, expected_var): + n = X.shape[0] + for chunk_size in [1, n // 10 + 1, n // 4 + 1, n // 2 + 1, n]: + last_mean, last_weight_sum, last_var = 0, 0, 0 + for batch in gen_batches(n, chunk_size): + last_mean, last_var, last_weight_sum = _incremental_mean_and_var( + X[batch], + last_mean, + last_var, + last_weight_sum, + sample_weight=sample_weight[batch], + ) + assert_allclose(last_mean, expected_mean) + assert_allclose(last_var, expected_var, atol=1e-6) + + size = (100, 20) + weight = rng.normal(loc=weight_loc, scale=weight_scale, size=size[0]) + + # Compare to weighted average: np.average + X = rng.normal(loc=mean, scale=var, size=size) + expected_mean = _safe_accumulator_op(np.average, X, weights=weight, axis=0) + expected_var = _safe_accumulator_op( + np.average, (X - expected_mean) ** 2, weights=weight, axis=0 + ) + _assert(X, weight, expected_mean, expected_var) + + # Compare to unweighted mean: np.mean + X = rng.normal(loc=mean, scale=var, size=size) + ones_weight = np.ones(size[0]) + expected_mean = _safe_accumulator_op(np.mean, X, axis=0) + expected_var = _safe_accumulator_op(np.var, X, axis=0) + _assert(X, ones_weight, expected_mean, expected_var) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_incremental_weighted_mean_and_variance_ignore_nan(dtype): + old_means = np.array([535.0, 535.0, 535.0, 535.0]) + old_variances = np.array([4225.0, 4225.0, 4225.0, 4225.0]) + old_weight_sum = np.array([2, 2, 2, 2], dtype=np.int32) + sample_weights_X = np.ones(3) + sample_weights_X_nan = np.ones(4) + + X = np.array( + [[170, 170, 170, 170], [430, 430, 430, 430], [300, 300, 300, 300]] + ).astype(dtype) + + X_nan = np.array( + [ + [170, np.nan, 170, 170], + [np.nan, 170, 430, 430], + [430, 430, np.nan, 300], + [300, 300, 300, np.nan], + ] + ).astype(dtype) + + X_means, X_variances, X_count = _incremental_mean_and_var( + X, old_means, old_variances, old_weight_sum, sample_weight=sample_weights_X + ) + X_nan_means, X_nan_variances, X_nan_count = _incremental_mean_and_var( + X_nan, + old_means, + old_variances, + old_weight_sum, + sample_weight=sample_weights_X_nan, + ) + + assert_allclose(X_nan_means, X_means) + assert_allclose(X_nan_variances, X_variances) + assert_allclose(X_nan_count, X_count) + + +def test_incremental_variance_update_formulas(): + # Test Youngs and Cramer incremental variance formulas. + # Doggie data from https://www.mathsisfun.com/data/standard-deviation.html + A = np.array( + [ + [600, 470, 170, 430, 300], + [600, 470, 170, 430, 300], + [600, 470, 170, 430, 300], + [600, 470, 170, 430, 300], + ] + ).T + idx = 2 + X1 = A[:idx, :] + X2 = A[idx:, :] + + old_means = X1.mean(axis=0) + old_variances = X1.var(axis=0) + old_sample_count = np.full(X1.shape[1], X1.shape[0], dtype=np.int32) + final_means, final_variances, final_count = _incremental_mean_and_var( + X2, old_means, old_variances, old_sample_count + ) + assert_almost_equal(final_means, A.mean(axis=0), 6) + assert_almost_equal(final_variances, A.var(axis=0), 6) + assert_almost_equal(final_count, A.shape[0]) + + +def test_incremental_mean_and_variance_ignore_nan(): + old_means = np.array([535.0, 535.0, 535.0, 535.0]) + old_variances = np.array([4225.0, 4225.0, 4225.0, 4225.0]) + old_sample_count = np.array([2, 2, 2, 2], dtype=np.int32) + + X = np.array([[170, 170, 170, 170], [430, 430, 430, 430], [300, 300, 300, 300]]) + + X_nan = np.array( + [ + [170, np.nan, 170, 170], + [np.nan, 170, 430, 430], + [430, 430, np.nan, 300], + [300, 300, 300, np.nan], + ] + ) + + X_means, X_variances, X_count = _incremental_mean_and_var( + X, old_means, old_variances, old_sample_count + ) + X_nan_means, X_nan_variances, X_nan_count = _incremental_mean_and_var( + X_nan, old_means, old_variances, old_sample_count + ) + + assert_allclose(X_nan_means, X_means) + assert_allclose(X_nan_variances, X_variances) + assert_allclose(X_nan_count, X_count) + + +@skip_if_32bit +def test_incremental_variance_numerical_stability(): + # Test Youngs and Cramer incremental variance formulas. + + def np_var(A): + return A.var(axis=0) + + # Naive one pass variance computation - not numerically stable + # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance + def one_pass_var(X): + n = X.shape[0] + exp_x2 = (X**2).sum(axis=0) / n + expx_2 = (X.sum(axis=0) / n) ** 2 + return exp_x2 - expx_2 + + # Two-pass algorithm, stable. + # We use it as a benchmark. It is not an online algorithm + # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Two-pass_algorithm + def two_pass_var(X): + mean = X.mean(axis=0) + Y = X.copy() + return np.mean((Y - mean) ** 2, axis=0) + + # Naive online implementation + # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm + # This works only for chunks for size 1 + def naive_mean_variance_update(x, last_mean, last_variance, last_sample_count): + updated_sample_count = last_sample_count + 1 + samples_ratio = last_sample_count / float(updated_sample_count) + updated_mean = x / updated_sample_count + last_mean * samples_ratio + updated_variance = ( + last_variance * samples_ratio + + (x - last_mean) * (x - updated_mean) / updated_sample_count + ) + return updated_mean, updated_variance, updated_sample_count + + # We want to show a case when one_pass_var has error > 1e-3 while + # _batch_mean_variance_update has less. + tol = 200 + n_features = 2 + n_samples = 10000 + x1 = np.array(1e8, dtype=np.float64) + x2 = np.log(1e-5, dtype=np.float64) + A0 = np.full((n_samples // 2, n_features), x1, dtype=np.float64) + A1 = np.full((n_samples // 2, n_features), x2, dtype=np.float64) + A = np.vstack((A0, A1)) + + # Naive one pass var: >tol (=1063) + assert np.abs(np_var(A) - one_pass_var(A)).max() > tol + + # Starting point for online algorithms: after A0 + + # Naive implementation: >tol (436) + mean, var, n = A0[0, :], np.zeros(n_features), n_samples // 2 + for i in range(A1.shape[0]): + mean, var, n = naive_mean_variance_update(A1[i, :], mean, var, n) + assert n == A.shape[0] + # the mean is also slightly unstable + assert np.abs(A.mean(axis=0) - mean).max() > 1e-6 + assert np.abs(np_var(A) - var).max() > tol + + # Robust implementation: np.abs(np_var(A) - var).max() + + +def test_incremental_variance_ddof(): + # Test that degrees of freedom parameter for calculations are correct. + rng = np.random.RandomState(1999) + X = rng.randn(50, 10) + n_samples, n_features = X.shape + for batch_size in [11, 20, 37]: + steps = np.arange(0, X.shape[0], batch_size) + if steps[-1] != X.shape[0]: + steps = np.hstack([steps, n_samples]) + + for i, j in zip(steps[:-1], steps[1:]): + batch = X[i:j, :] + if i == 0: + incremental_means = batch.mean(axis=0) + incremental_variances = batch.var(axis=0) + # Assign this twice so that the test logic is consistent + incremental_count = batch.shape[0] + sample_count = np.full(batch.shape[1], batch.shape[0], dtype=np.int32) + else: + result = _incremental_mean_and_var( + batch, incremental_means, incremental_variances, sample_count + ) + (incremental_means, incremental_variances, incremental_count) = result + sample_count += batch.shape[0] + + calculated_means = np.mean(X[:j], axis=0) + calculated_variances = np.var(X[:j], axis=0) + assert_almost_equal(incremental_means, calculated_means, 6) + assert_almost_equal(incremental_variances, calculated_variances, 6) + assert_array_equal(incremental_count, sample_count) + + +def test_vector_sign_flip(): + # Testing that sign flip is working & largest value has positive sign + data = np.random.RandomState(36).randn(5, 5) + max_abs_rows = np.argmax(np.abs(data), axis=1) + data_flipped = _deterministic_vector_sign_flip(data) + max_rows = np.argmax(data_flipped, axis=1) + assert_array_equal(max_abs_rows, max_rows) + signs = np.sign(data[range(data.shape[0]), max_abs_rows]) + assert_array_equal(data, data_flipped * signs[:, np.newaxis]) + + +def test_softmax(): + rng = np.random.RandomState(0) + X = rng.randn(3, 5) + exp_X = np.exp(X) + sum_exp_X = np.sum(exp_X, axis=1).reshape((-1, 1)) + assert_array_almost_equal(softmax(X), exp_X / sum_exp_X) + + +def test_stable_cumsum(): + assert_array_equal(stable_cumsum([1, 2, 3]), np.cumsum([1, 2, 3])) + r = np.random.RandomState(0).rand(100000) + with pytest.warns(RuntimeWarning): + stable_cumsum(r, rtol=0, atol=0) + + # test axis parameter + A = np.random.RandomState(36).randint(1000, size=(5, 5, 5)) + assert_array_equal(stable_cumsum(A, axis=0), np.cumsum(A, axis=0)) + assert_array_equal(stable_cumsum(A, axis=1), np.cumsum(A, axis=1)) + assert_array_equal(stable_cumsum(A, axis=2), np.cumsum(A, axis=2)) + + +@pytest.mark.parametrize( + "A_container", + [np.array, *CSR_CONTAINERS], + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +@pytest.mark.parametrize( + "B_container", + [np.array, *CSR_CONTAINERS], + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +def test_safe_sparse_dot_2d(A_container, B_container): + rng = np.random.RandomState(0) + + A = rng.random_sample((30, 10)) + B = rng.random_sample((10, 20)) + expected = np.dot(A, B) + + A = A_container(A) + B = B_container(B) + actual = safe_sparse_dot(A, B, dense_output=True) + + assert_allclose(actual, expected) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_safe_sparse_dot_nd(csr_container): + rng = np.random.RandomState(0) + + # dense ND / sparse + A = rng.random_sample((2, 3, 4, 5, 6)) + B = rng.random_sample((6, 7)) + expected = np.dot(A, B) + B = csr_container(B) + actual = safe_sparse_dot(A, B) + assert_allclose(actual, expected) + + # sparse / dense ND + A = rng.random_sample((2, 3)) + B = rng.random_sample((4, 5, 3, 6)) + expected = np.dot(A, B) + A = csr_container(A) + actual = safe_sparse_dot(A, B) + assert_allclose(actual, expected) + + +@pytest.mark.parametrize( + "container", + [np.array, *CSR_CONTAINERS], + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +def test_safe_sparse_dot_2d_1d(container): + rng = np.random.RandomState(0) + B = rng.random_sample((10)) + + # 2D @ 1D + A = rng.random_sample((30, 10)) + expected = np.dot(A, B) + actual = safe_sparse_dot(container(A), B) + assert_allclose(actual, expected) + + # 1D @ 2D + A = rng.random_sample((10, 30)) + expected = np.dot(B, A) + actual = safe_sparse_dot(B, container(A)) + assert_allclose(actual, expected) + + +@pytest.mark.parametrize("dense_output", [True, False]) +def test_safe_sparse_dot_dense_output(dense_output): + rng = np.random.RandomState(0) + + A = sparse.random(30, 10, density=0.1, random_state=rng) + B = sparse.random(10, 20, density=0.1, random_state=rng) + + expected = A.dot(B) + actual = safe_sparse_dot(A, B, dense_output=dense_output) + + assert sparse.issparse(actual) == (not dense_output) + + if dense_output: + expected = expected.toarray() + assert_allclose_dense_sparse(actual, expected) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_fast_dict.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_fast_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..8fada45db3f52ca47da44162609b9c23f7222361 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_fast_dict.py @@ -0,0 +1,47 @@ +""" Test fast_dict. +""" +import numpy as np +from numpy.testing import assert_allclose, assert_array_equal + +from sklearn.utils._fast_dict import IntFloatDict, argmin + + +def test_int_float_dict(): + rng = np.random.RandomState(0) + keys = np.unique(rng.randint(100, size=10).astype(np.intp)) + values = rng.rand(len(keys)) + + d = IntFloatDict(keys, values) + for key, value in zip(keys, values): + assert d[key] == value + assert len(d) == len(keys) + + d.append(120, 3.0) + assert d[120] == 3.0 + assert len(d) == len(keys) + 1 + for i in range(2000): + d.append(i + 1000, 4.0) + assert d[1100] == 4.0 + + +def test_int_float_dict_argmin(): + # Test the argmin implementation on the IntFloatDict + keys = np.arange(100, dtype=np.intp) + values = np.arange(100, dtype=np.float64) + d = IntFloatDict(keys, values) + assert argmin(d) == (0, 0) + + +def test_to_arrays(): + # Test that an IntFloatDict is converted into arrays + # of keys and values correctly + keys_in = np.array([1, 2, 3], dtype=np.intp) + values_in = np.array([4, 5, 6], dtype=np.float64) + + d = IntFloatDict(keys_in, values_in) + keys_out, values_out = d.to_arrays() + + assert keys_out.dtype == keys_in.dtype + assert values_in.dtype == values_out.dtype + assert_array_equal(keys_out, keys_in) + assert_allclose(values_out, values_in) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_graph.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..d64108a40d8ab4a919b5f0e8b86749232fc4b79e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_graph.py @@ -0,0 +1,80 @@ +import numpy as np +import pytest +from scipy.sparse.csgraph import connected_components + +from sklearn.metrics.pairwise import pairwise_distances +from sklearn.neighbors import kneighbors_graph +from sklearn.utils.graph import _fix_connected_components + + +def test_fix_connected_components(): + # Test that _fix_connected_components reduces the number of component to 1. + X = np.array([0, 1, 2, 5, 6, 7])[:, None] + graph = kneighbors_graph(X, n_neighbors=2, mode="distance") + + n_connected_components, labels = connected_components(graph) + assert n_connected_components > 1 + + graph = _fix_connected_components(X, graph, n_connected_components, labels) + + n_connected_components, labels = connected_components(graph) + assert n_connected_components == 1 + + +def test_fix_connected_components_precomputed(): + # Test that _fix_connected_components accepts precomputed distance matrix. + X = np.array([0, 1, 2, 5, 6, 7])[:, None] + graph = kneighbors_graph(X, n_neighbors=2, mode="distance") + + n_connected_components, labels = connected_components(graph) + assert n_connected_components > 1 + + distances = pairwise_distances(X) + graph = _fix_connected_components( + distances, graph, n_connected_components, labels, metric="precomputed" + ) + + n_connected_components, labels = connected_components(graph) + assert n_connected_components == 1 + + # but it does not work with precomputed neighbors graph + with pytest.raises(RuntimeError, match="does not work with a sparse"): + _fix_connected_components( + graph, graph, n_connected_components, labels, metric="precomputed" + ) + + +def test_fix_connected_components_wrong_mode(): + # Test that the an error is raised if the mode string is incorrect. + X = np.array([0, 1, 2, 5, 6, 7])[:, None] + graph = kneighbors_graph(X, n_neighbors=2, mode="distance") + n_connected_components, labels = connected_components(graph) + + with pytest.raises(ValueError, match="Unknown mode"): + graph = _fix_connected_components( + X, graph, n_connected_components, labels, mode="foo" + ) + + +def test_fix_connected_components_connectivity_mode(): + # Test that the connectivity mode fill new connections with ones. + X = np.array([0, 1, 6, 7])[:, None] + graph = kneighbors_graph(X, n_neighbors=1, mode="connectivity") + n_connected_components, labels = connected_components(graph) + graph = _fix_connected_components( + X, graph, n_connected_components, labels, mode="connectivity" + ) + assert np.all(graph.data == 1) + + +def test_fix_connected_components_distance_mode(): + # Test that the distance mode does not fill new connections with ones. + X = np.array([0, 1, 6, 7])[:, None] + graph = kneighbors_graph(X, n_neighbors=1, mode="distance") + assert np.all(graph.data == 1) + + n_connected_components, labels = connected_components(graph) + graph = _fix_connected_components( + X, graph, n_connected_components, labels, mode="distance" + ) + assert not np.all(graph.data == 1) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_metaestimators.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_metaestimators.py new file mode 100644 index 0000000000000000000000000000000000000000..8e6d4eec35973e8d21c14af76264ca9fd88480f9 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_metaestimators.py @@ -0,0 +1,63 @@ +import pickle + +import pytest + +from sklearn.utils.metaestimators import available_if + + +class AvailableParameterEstimator: + """This estimator's `available` parameter toggles the presence of a method""" + + def __init__(self, available=True, return_value=1): + self.available = available + self.return_value = return_value + + @available_if(lambda est: est.available) + def available_func(self): + """This is a mock available_if function""" + return self.return_value + + +def test_available_if_docstring(): + assert "This is a mock available_if function" in str( + AvailableParameterEstimator.__dict__["available_func"].__doc__ + ) + assert "This is a mock available_if function" in str( + AvailableParameterEstimator.available_func.__doc__ + ) + assert "This is a mock available_if function" in str( + AvailableParameterEstimator().available_func.__doc__ + ) + + +def test_available_if(): + assert hasattr(AvailableParameterEstimator(), "available_func") + assert not hasattr(AvailableParameterEstimator(available=False), "available_func") + + +def test_available_if_unbound_method(): + # This is a non regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/20614 + # to make sure that decorated functions can be used as an unbound method, + # for instance when monkeypatching. + est = AvailableParameterEstimator() + AvailableParameterEstimator.available_func(est) + + est = AvailableParameterEstimator(available=False) + with pytest.raises( + AttributeError, + match="This 'AvailableParameterEstimator' has no attribute 'available_func'", + ): + AvailableParameterEstimator.available_func(est) + + +def test_available_if_methods_can_be_pickled(): + """Check that available_if methods can be pickled. + + Non-regression test for #21344. + """ + return_value = 10 + est = AvailableParameterEstimator(available=True, return_value=return_value) + pickled_bytes = pickle.dumps(est.available_func) + unpickled_func = pickle.loads(pickled_bytes) + assert unpickled_func() == return_value diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_multiclass.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_multiclass.py new file mode 100644 index 0000000000000000000000000000000000000000..6603aca206e667ed4521c208a845468726a127e4 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_multiclass.py @@ -0,0 +1,597 @@ +from itertools import product + +import numpy as np +import pytest +from scipy.sparse import issparse + +from sklearn import config_context, datasets +from sklearn.model_selection import ShuffleSplit +from sklearn.svm import SVC +from sklearn.utils._array_api import yield_namespace_device_dtype_combinations +from sklearn.utils._testing import ( + _array_api_for_tests, + assert_allclose, + assert_array_almost_equal, + assert_array_equal, +) +from sklearn.utils.estimator_checks import _NotAnArray +from sklearn.utils.fixes import ( + COO_CONTAINERS, + CSC_CONTAINERS, + CSR_CONTAINERS, + DOK_CONTAINERS, + LIL_CONTAINERS, +) +from sklearn.utils.metaestimators import _safe_split +from sklearn.utils.multiclass import ( + _ovr_decision_function, + check_classification_targets, + class_distribution, + is_multilabel, + type_of_target, + unique_labels, +) + +multilabel_explicit_zero = np.array([[0, 1], [1, 0]]) +multilabel_explicit_zero[:, 0] = 0 + + +def _generate_sparse( + data, + sparse_containers=tuple( + COO_CONTAINERS + + CSC_CONTAINERS + + CSR_CONTAINERS + + DOK_CONTAINERS + + LIL_CONTAINERS + ), + dtypes=(bool, int, np.int8, np.uint8, float, np.float32), +): + return [ + sparse_container(data, dtype=dtype) + for sparse_container in sparse_containers + for dtype in dtypes + ] + + +EXAMPLES = { + "multilabel-indicator": [ + # valid when the data is formatted as sparse or dense, identified + # by CSR format when the testing takes place + *_generate_sparse( + np.random.RandomState(42).randint(2, size=(10, 10)), + sparse_containers=CSR_CONTAINERS, + dtypes=(int,), + ), + [[0, 1], [1, 0]], + [[0, 1]], + *_generate_sparse( + multilabel_explicit_zero, sparse_containers=CSC_CONTAINERS, dtypes=(int,) + ), + *_generate_sparse([[0, 1], [1, 0]]), + *_generate_sparse([[0, 0], [0, 0]]), + *_generate_sparse([[0, 1]]), + # Only valid when data is dense + [[-1, 1], [1, -1]], + np.array([[-1, 1], [1, -1]]), + np.array([[-3, 3], [3, -3]]), + _NotAnArray(np.array([[-3, 3], [3, -3]])), + ], + "multiclass": [ + [1, 0, 2, 2, 1, 4, 2, 4, 4, 4], + np.array([1, 0, 2]), + np.array([1, 0, 2], dtype=np.int8), + np.array([1, 0, 2], dtype=np.uint8), + np.array([1, 0, 2], dtype=float), + np.array([1, 0, 2], dtype=np.float32), + np.array([[1], [0], [2]]), + _NotAnArray(np.array([1, 0, 2])), + [0, 1, 2], + ["a", "b", "c"], + np.array(["a", "b", "c"]), + np.array(["a", "b", "c"], dtype=object), + np.array(["a", "b", "c"], dtype=object), + ], + "multiclass-multioutput": [ + [[1, 0, 2, 2], [1, 4, 2, 4]], + [["a", "b"], ["c", "d"]], + np.array([[1, 0, 2, 2], [1, 4, 2, 4]]), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.int8), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.uint8), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=float), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.float32), + *_generate_sparse( + [[1, 0, 2, 2], [1, 4, 2, 4]], + sparse_containers=CSC_CONTAINERS + CSR_CONTAINERS, + dtypes=(int, np.int8, np.uint8, float, np.float32), + ), + np.array([["a", "b"], ["c", "d"]]), + np.array([["a", "b"], ["c", "d"]]), + np.array([["a", "b"], ["c", "d"]], dtype=object), + np.array([[1, 0, 2]]), + _NotAnArray(np.array([[1, 0, 2]])), + ], + "binary": [ + [0, 1], + [1, 1], + [], + [0], + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1]), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=bool), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.int8), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.uint8), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=float), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.float32), + np.array([[0], [1]]), + _NotAnArray(np.array([[0], [1]])), + [1, -1], + [3, 5], + ["a"], + ["a", "b"], + ["abc", "def"], + np.array(["abc", "def"]), + ["a", "b"], + np.array(["abc", "def"], dtype=object), + ], + "continuous": [ + [1e-5], + [0, 0.5], + np.array([[0], [0.5]]), + np.array([[0], [0.5]], dtype=np.float32), + ], + "continuous-multioutput": [ + np.array([[0, 0.5], [0.5, 0]]), + np.array([[0, 0.5], [0.5, 0]], dtype=np.float32), + np.array([[0, 0.5]]), + *_generate_sparse( + [[0, 0.5], [0.5, 0]], + sparse_containers=CSC_CONTAINERS + CSR_CONTAINERS, + dtypes=(float, np.float32), + ), + *_generate_sparse( + [[0, 0.5]], + sparse_containers=CSC_CONTAINERS + CSR_CONTAINERS, + dtypes=(float, np.float32), + ), + ], + "unknown": [ + [[]], + np.array([[]], dtype=object), + [()], + # sequence of sequences that weren't supported even before deprecation + np.array([np.array([]), np.array([1, 2, 3])], dtype=object), + [np.array([]), np.array([1, 2, 3])], + [{1, 2, 3}, {1, 2}], + [frozenset([1, 2, 3]), frozenset([1, 2])], + # and also confusable as sequences of sequences + [{0: "a", 1: "b"}, {0: "a"}], + # ndim 0 + np.array(0), + # empty second dimension + np.array([[], []]), + # 3d + np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]), + ], +} + +ARRAY_API_EXAMPLES = { + "multilabel-indicator": [ + np.random.RandomState(42).randint(2, size=(10, 10)), + [[0, 1], [1, 0]], + [[0, 1]], + multilabel_explicit_zero, + [[0, 0], [0, 0]], + [[-1, 1], [1, -1]], + np.array([[-1, 1], [1, -1]]), + np.array([[-3, 3], [3, -3]]), + _NotAnArray(np.array([[-3, 3], [3, -3]])), + ], + "multiclass": [ + [1, 0, 2, 2, 1, 4, 2, 4, 4, 4], + np.array([1, 0, 2]), + np.array([1, 0, 2], dtype=np.int8), + np.array([1, 0, 2], dtype=np.uint8), + np.array([1, 0, 2], dtype=float), + np.array([1, 0, 2], dtype=np.float32), + np.array([[1], [0], [2]]), + _NotAnArray(np.array([1, 0, 2])), + [0, 1, 2], + ], + "multiclass-multioutput": [ + [[1, 0, 2, 2], [1, 4, 2, 4]], + np.array([[1, 0, 2, 2], [1, 4, 2, 4]]), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.int8), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.uint8), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=float), + np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.float32), + np.array([[1, 0, 2]]), + _NotAnArray(np.array([[1, 0, 2]])), + ], + "binary": [ + [0, 1], + [1, 1], + [], + [0], + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1]), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=bool), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.int8), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.uint8), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=float), + np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.float32), + np.array([[0], [1]]), + _NotAnArray(np.array([[0], [1]])), + [1, -1], + [3, 5], + ], + "continuous": [ + [1e-5], + [0, 0.5], + np.array([[0], [0.5]]), + np.array([[0], [0.5]], dtype=np.float32), + ], + "continuous-multioutput": [ + np.array([[0, 0.5], [0.5, 0]]), + np.array([[0, 0.5], [0.5, 0]], dtype=np.float32), + np.array([[0, 0.5]]), + ], + "unknown": [ + [[]], + [()], + np.array(0), + np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]), + ], +} + + +NON_ARRAY_LIKE_EXAMPLES = [ + {1, 2, 3}, + {0: "a", 1: "b"}, + {0: [5], 1: [5]}, + "abc", + frozenset([1, 2, 3]), + None, +] + +MULTILABEL_SEQUENCES = [ + [[1], [2], [0, 1]], + [(), (2), (0, 1)], + np.array([[], [1, 2]], dtype="object"), + _NotAnArray(np.array([[], [1, 2]], dtype="object")), +] + + +def test_unique_labels(): + # Empty iterable + with pytest.raises(ValueError): + unique_labels() + + # Multiclass problem + assert_array_equal(unique_labels(range(10)), np.arange(10)) + assert_array_equal(unique_labels(np.arange(10)), np.arange(10)) + assert_array_equal(unique_labels([4, 0, 2]), np.array([0, 2, 4])) + + # Multilabel indicator + assert_array_equal( + unique_labels(np.array([[0, 0, 1], [1, 0, 1], [0, 0, 0]])), np.arange(3) + ) + + assert_array_equal(unique_labels(np.array([[0, 0, 1], [0, 0, 0]])), np.arange(3)) + + # Several arrays passed + assert_array_equal(unique_labels([4, 0, 2], range(5)), np.arange(5)) + assert_array_equal(unique_labels((0, 1, 2), (0,), (2, 1)), np.arange(3)) + + # Border line case with binary indicator matrix + with pytest.raises(ValueError): + unique_labels([4, 0, 2], np.ones((5, 5))) + with pytest.raises(ValueError): + unique_labels(np.ones((5, 4)), np.ones((5, 5))) + + assert_array_equal(unique_labels(np.ones((4, 5)), np.ones((5, 5))), np.arange(5)) + + +def test_unique_labels_non_specific(): + # Test unique_labels with a variety of collected examples + + # Smoke test for all supported format + for format in ["binary", "multiclass", "multilabel-indicator"]: + for y in EXAMPLES[format]: + unique_labels(y) + + # We don't support those format at the moment + for example in NON_ARRAY_LIKE_EXAMPLES: + with pytest.raises(ValueError): + unique_labels(example) + + for y_type in [ + "unknown", + "continuous", + "continuous-multioutput", + "multiclass-multioutput", + ]: + for example in EXAMPLES[y_type]: + with pytest.raises(ValueError): + unique_labels(example) + + +def test_unique_labels_mixed_types(): + # Mix with binary or multiclass and multilabel + mix_clf_format = product( + EXAMPLES["multilabel-indicator"], EXAMPLES["multiclass"] + EXAMPLES["binary"] + ) + + for y_multilabel, y_multiclass in mix_clf_format: + with pytest.raises(ValueError): + unique_labels(y_multiclass, y_multilabel) + with pytest.raises(ValueError): + unique_labels(y_multilabel, y_multiclass) + + with pytest.raises(ValueError): + unique_labels([[1, 2]], [["a", "d"]]) + + with pytest.raises(ValueError): + unique_labels(["1", 2]) + + with pytest.raises(ValueError): + unique_labels([["1", 2], [1, 3]]) + + with pytest.raises(ValueError): + unique_labels([["1", "2"], [2, 3]]) + + +def test_is_multilabel(): + for group, group_examples in EXAMPLES.items(): + dense_exp = group == "multilabel-indicator" + + for example in group_examples: + # Only mark explicitly defined sparse examples as valid sparse + # multilabel-indicators + sparse_exp = dense_exp and issparse(example) + + if issparse(example) or ( + hasattr(example, "__array__") + and np.asarray(example).ndim == 2 + and np.asarray(example).dtype.kind in "biuf" + and np.asarray(example).shape[1] > 0 + ): + examples_sparse = [ + sparse_container(example) + for sparse_container in ( + COO_CONTAINERS + + CSC_CONTAINERS + + CSR_CONTAINERS + + DOK_CONTAINERS + + LIL_CONTAINERS + ) + ] + for exmpl_sparse in examples_sparse: + assert sparse_exp == is_multilabel( + exmpl_sparse + ), f"is_multilabel({exmpl_sparse!r}) should be {sparse_exp}" + + # Densify sparse examples before testing + if issparse(example): + example = example.toarray() + + assert dense_exp == is_multilabel( + example + ), f"is_multilabel({example!r}) should be {dense_exp}" + + +@pytest.mark.parametrize( + "array_namespace, device, dtype_name", + yield_namespace_device_dtype_combinations(), +) +def test_is_multilabel_array_api_compliance(array_namespace, device, dtype_name): + xp = _array_api_for_tests(array_namespace, device) + + for group, group_examples in ARRAY_API_EXAMPLES.items(): + dense_exp = group == "multilabel-indicator" + for example in group_examples: + if np.asarray(example).dtype.kind == "f": + example = np.asarray(example, dtype=dtype_name) + else: + example = np.asarray(example) + example = xp.asarray(example, device=device) + + with config_context(array_api_dispatch=True): + assert dense_exp == is_multilabel( + example + ), f"is_multilabel({example!r}) should be {dense_exp}" + + +def test_check_classification_targets(): + for y_type in EXAMPLES.keys(): + if y_type in ["unknown", "continuous", "continuous-multioutput"]: + for example in EXAMPLES[y_type]: + msg = "Unknown label type: " + with pytest.raises(ValueError, match=msg): + check_classification_targets(example) + else: + for example in EXAMPLES[y_type]: + check_classification_targets(example) + + +# @ignore_warnings +def test_type_of_target(): + for group, group_examples in EXAMPLES.items(): + for example in group_examples: + assert ( + type_of_target(example) == group + ), "type_of_target(%r) should be %r, got %r" % ( + example, + group, + type_of_target(example), + ) + + for example in NON_ARRAY_LIKE_EXAMPLES: + msg_regex = r"Expected array-like \(array or non-string sequence\).*" + with pytest.raises(ValueError, match=msg_regex): + type_of_target(example) + + for example in MULTILABEL_SEQUENCES: + msg = ( + "You appear to be using a legacy multi-label data " + "representation. Sequence of sequences are no longer supported;" + " use a binary array or sparse matrix instead." + ) + with pytest.raises(ValueError, match=msg): + type_of_target(example) + + +def test_type_of_target_pandas_sparse(): + pd = pytest.importorskip("pandas") + + y = pd.arrays.SparseArray([1, np.nan, np.nan, 1, np.nan]) + msg = "y cannot be class 'SparseSeries' or 'SparseArray'" + with pytest.raises(ValueError, match=msg): + type_of_target(y) + + +def test_type_of_target_pandas_nullable(): + """Check that type_of_target works with pandas nullable dtypes.""" + pd = pytest.importorskip("pandas") + + for dtype in ["Int32", "Float32"]: + y_true = pd.Series([1, 0, 2, 3, 4], dtype=dtype) + assert type_of_target(y_true) == "multiclass" + + y_true = pd.Series([1, 0, 1, 0], dtype=dtype) + assert type_of_target(y_true) == "binary" + + y_true = pd.DataFrame([[1.4, 3.1], [3.1, 1.4]], dtype="Float32") + assert type_of_target(y_true) == "continuous-multioutput" + + y_true = pd.DataFrame([[0, 1], [1, 1]], dtype="Int32") + assert type_of_target(y_true) == "multilabel-indicator" + + y_true = pd.DataFrame([[1, 2], [3, 1]], dtype="Int32") + assert type_of_target(y_true) == "multiclass-multioutput" + + +@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"]) +def test_unique_labels_pandas_nullable(dtype): + """Checks that unique_labels work with pandas nullable dtypes. + + Non-regression test for gh-25634. + """ + pd = pytest.importorskip("pandas") + + y_true = pd.Series([1, 0, 0, 1, 0, 1, 1, 0, 1], dtype=dtype) + y_predicted = pd.Series([0, 0, 1, 1, 0, 1, 1, 1, 1], dtype="int64") + + labels = unique_labels(y_true, y_predicted) + assert_array_equal(labels, [0, 1]) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_class_distribution(csc_container): + y = np.array( + [ + [1, 0, 0, 1], + [2, 2, 0, 1], + [1, 3, 0, 1], + [4, 2, 0, 1], + [2, 0, 0, 1], + [1, 3, 0, 1], + ] + ) + # Define the sparse matrix with a mix of implicit and explicit zeros + data = np.array([1, 2, 1, 4, 2, 1, 0, 2, 3, 2, 3, 1, 1, 1, 1, 1, 1]) + indices = np.array([0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 5, 0, 1, 2, 3, 4, 5]) + indptr = np.array([0, 6, 11, 11, 17]) + y_sp = csc_container((data, indices, indptr), shape=(6, 4)) + + classes, n_classes, class_prior = class_distribution(y) + classes_sp, n_classes_sp, class_prior_sp = class_distribution(y_sp) + classes_expected = [[1, 2, 4], [0, 2, 3], [0], [1]] + n_classes_expected = [3, 3, 1, 1] + class_prior_expected = [[3 / 6, 2 / 6, 1 / 6], [1 / 3, 1 / 3, 1 / 3], [1.0], [1.0]] + + for k in range(y.shape[1]): + assert_array_almost_equal(classes[k], classes_expected[k]) + assert_array_almost_equal(n_classes[k], n_classes_expected[k]) + assert_array_almost_equal(class_prior[k], class_prior_expected[k]) + + assert_array_almost_equal(classes_sp[k], classes_expected[k]) + assert_array_almost_equal(n_classes_sp[k], n_classes_expected[k]) + assert_array_almost_equal(class_prior_sp[k], class_prior_expected[k]) + + # Test again with explicit sample weights + (classes, n_classes, class_prior) = class_distribution( + y, [1.0, 2.0, 1.0, 2.0, 1.0, 2.0] + ) + (classes_sp, n_classes_sp, class_prior_sp) = class_distribution( + y, [1.0, 2.0, 1.0, 2.0, 1.0, 2.0] + ) + class_prior_expected = [[4 / 9, 3 / 9, 2 / 9], [2 / 9, 4 / 9, 3 / 9], [1.0], [1.0]] + + for k in range(y.shape[1]): + assert_array_almost_equal(classes[k], classes_expected[k]) + assert_array_almost_equal(n_classes[k], n_classes_expected[k]) + assert_array_almost_equal(class_prior[k], class_prior_expected[k]) + + assert_array_almost_equal(classes_sp[k], classes_expected[k]) + assert_array_almost_equal(n_classes_sp[k], n_classes_expected[k]) + assert_array_almost_equal(class_prior_sp[k], class_prior_expected[k]) + + +def test_safe_split_with_precomputed_kernel(): + clf = SVC() + clfp = SVC(kernel="precomputed") + + iris = datasets.load_iris() + X, y = iris.data, iris.target + K = np.dot(X, X.T) + + cv = ShuffleSplit(test_size=0.25, random_state=0) + train, test = list(cv.split(X))[0] + + X_train, y_train = _safe_split(clf, X, y, train) + K_train, y_train2 = _safe_split(clfp, K, y, train) + assert_array_almost_equal(K_train, np.dot(X_train, X_train.T)) + assert_array_almost_equal(y_train, y_train2) + + X_test, y_test = _safe_split(clf, X, y, test, train) + K_test, y_test2 = _safe_split(clfp, K, y, test, train) + assert_array_almost_equal(K_test, np.dot(X_test, X_train.T)) + assert_array_almost_equal(y_test, y_test2) + + +def test_ovr_decision_function(): + # test properties for ovr decision function + + predictions = np.array([[0, 1, 1], [0, 1, 0], [0, 1, 1], [0, 1, 1]]) + + confidences = np.array( + [[-1e16, 0, -1e16], [1.0, 2.0, -3.0], [-5.0, 2.0, 5.0], [-0.5, 0.2, 0.5]] + ) + + n_classes = 3 + + dec_values = _ovr_decision_function(predictions, confidences, n_classes) + + # check that the decision values are within 0.5 range of the votes + votes = np.array([[1, 0, 2], [1, 1, 1], [1, 0, 2], [1, 0, 2]]) + + assert_allclose(votes, dec_values, atol=0.5) + + # check that the prediction are what we expect + # highest vote or highest confidence if there is a tie. + # for the second sample we have a tie (should be won by 1) + expected_prediction = np.array([2, 1, 2, 2]) + assert_array_equal(np.argmax(dec_values, axis=1), expected_prediction) + + # third and fourth sample have the same vote but third sample + # has higher confidence, this should reflect on the decision values + assert dec_values[2, 2] > dec_values[3, 2] + + # assert subset invariance. + dec_values_one = [ + _ovr_decision_function( + np.array([predictions[i]]), np.array([confidences[i]]), n_classes + )[0] + for i in range(4) + ] + + assert_allclose(dec_values, dec_values_one, atol=1e-6) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_optimize.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_optimize.py new file mode 100644 index 0000000000000000000000000000000000000000..a8bcd1aebf793f10aea7f7cf1d6c9ff9f93c5a9a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_optimize.py @@ -0,0 +1,31 @@ +import numpy as np +from scipy.optimize import fmin_ncg + +from sklearn.utils._testing import assert_array_almost_equal +from sklearn.utils.optimize import _newton_cg + + +def test_newton_cg(): + # Test that newton_cg gives same result as scipy's fmin_ncg + + rng = np.random.RandomState(0) + A = rng.normal(size=(10, 10)) + x0 = np.ones(10) + + def func(x): + Ax = A.dot(x) + return 0.5 * (Ax).dot(Ax) + + def grad(x): + return A.T.dot(A.dot(x)) + + def hess(x, p): + return p.dot(A.T.dot(A.dot(x.all()))) + + def grad_hess(x): + return grad(x), lambda x: A.T.dot(A.dot(x)) + + assert_array_almost_equal( + _newton_cg(grad_hess, func, grad, x0, tol=1e-10)[0], + fmin_ncg(f=func, x0=x0, fprime=grad, fhess_p=hess), + ) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_param_validation.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_param_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..795fdecfba2e4795c0771d92e5d15e5b44f86f0b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_param_validation.py @@ -0,0 +1,780 @@ +from numbers import Integral, Real + +import numpy as np +import pytest +from scipy.sparse import csr_matrix + +from sklearn._config import config_context, get_config +from sklearn.base import BaseEstimator, _fit_context +from sklearn.model_selection import LeaveOneOut +from sklearn.utils import deprecated +from sklearn.utils._param_validation import ( + HasMethods, + Hidden, + Interval, + InvalidParameterError, + MissingValues, + Options, + RealNotInt, + StrOptions, + _ArrayLikes, + _Booleans, + _Callables, + _CVObjects, + _InstancesOf, + _IterablesNotString, + _NanConstraint, + _NoneConstraint, + _PandasNAConstraint, + _RandomStates, + _SparseMatrices, + _VerboseHelper, + generate_invalid_param_val, + generate_valid_param, + make_constraint, + validate_params, +) + + +# Some helpers for the tests +@validate_params( + {"a": [Real], "b": [Real], "c": [Real], "d": [Real]}, + prefer_skip_nested_validation=True, +) +def _func(a, b=0, *args, c, d=0, **kwargs): + """A function to test the validation of functions.""" + + +class _Class: + """A class to test the _InstancesOf constraint and the validation of methods.""" + + @validate_params({"a": [Real]}, prefer_skip_nested_validation=True) + def _method(self, a): + """A validated method""" + + @deprecated() + @validate_params({"a": [Real]}, prefer_skip_nested_validation=True) + def _deprecated_method(self, a): + """A deprecated validated method""" + + +class _Estimator(BaseEstimator): + """An estimator to test the validation of estimator parameters.""" + + _parameter_constraints: dict = {"a": [Real]} + + def __init__(self, a): + self.a = a + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X=None, y=None): + pass + + +@pytest.mark.parametrize("interval_type", [Integral, Real]) +def test_interval_range(interval_type): + """Check the range of values depending on closed.""" + interval = Interval(interval_type, -2, 2, closed="left") + assert -2 in interval + assert 2 not in interval + + interval = Interval(interval_type, -2, 2, closed="right") + assert -2 not in interval + assert 2 in interval + + interval = Interval(interval_type, -2, 2, closed="both") + assert -2 in interval + assert 2 in interval + + interval = Interval(interval_type, -2, 2, closed="neither") + assert -2 not in interval + assert 2 not in interval + + +@pytest.mark.parametrize("interval_type", [Integral, Real]) +def test_interval_large_integers(interval_type): + """Check that Interval constraint work with large integers. + + non-regression test for #26648. + """ + interval = Interval(interval_type, 0, 2, closed="neither") + assert 2**65 not in interval + assert 2**128 not in interval + assert float(2**65) not in interval + assert float(2**128) not in interval + + interval = Interval(interval_type, 0, 2**128, closed="neither") + assert 2**65 in interval + assert 2**128 not in interval + assert float(2**65) in interval + assert float(2**128) not in interval + + assert 2**1024 not in interval + + +def test_interval_inf_in_bounds(): + """Check that inf is included iff a bound is closed and set to None. + + Only valid for real intervals. + """ + interval = Interval(Real, 0, None, closed="right") + assert np.inf in interval + + interval = Interval(Real, None, 0, closed="left") + assert -np.inf in interval + + interval = Interval(Real, None, None, closed="neither") + assert np.inf not in interval + assert -np.inf not in interval + + +@pytest.mark.parametrize( + "interval", + [Interval(Real, 0, 1, closed="left"), Interval(Real, None, None, closed="both")], +) +def test_nan_not_in_interval(interval): + """Check that np.nan is not in any interval.""" + assert np.nan not in interval + + +@pytest.mark.parametrize( + "params, error, match", + [ + ( + {"type": Integral, "left": 1.0, "right": 2, "closed": "both"}, + TypeError, + r"Expecting left to be an int for an interval over the integers", + ), + ( + {"type": Integral, "left": 1, "right": 2.0, "closed": "neither"}, + TypeError, + "Expecting right to be an int for an interval over the integers", + ), + ( + {"type": Integral, "left": None, "right": 0, "closed": "left"}, + ValueError, + r"left can't be None when closed == left", + ), + ( + {"type": Integral, "left": 0, "right": None, "closed": "right"}, + ValueError, + r"right can't be None when closed == right", + ), + ( + {"type": Integral, "left": 1, "right": -1, "closed": "both"}, + ValueError, + r"right can't be less than left", + ), + ], +) +def test_interval_errors(params, error, match): + """Check that informative errors are raised for invalid combination of parameters""" + with pytest.raises(error, match=match): + Interval(**params) + + +def test_stroptions(): + """Sanity check for the StrOptions constraint""" + options = StrOptions({"a", "b", "c"}, deprecated={"c"}) + assert options.is_satisfied_by("a") + assert options.is_satisfied_by("c") + assert not options.is_satisfied_by("d") + + assert "'c' (deprecated)" in str(options) + + +def test_options(): + """Sanity check for the Options constraint""" + options = Options(Real, {-0.5, 0.5, np.inf}, deprecated={-0.5}) + assert options.is_satisfied_by(-0.5) + assert options.is_satisfied_by(np.inf) + assert not options.is_satisfied_by(1.23) + + assert "-0.5 (deprecated)" in str(options) + + +@pytest.mark.parametrize( + "type, expected_type_name", + [ + (int, "int"), + (Integral, "int"), + (Real, "float"), + (np.ndarray, "numpy.ndarray"), + ], +) +def test_instances_of_type_human_readable(type, expected_type_name): + """Check the string representation of the _InstancesOf constraint.""" + constraint = _InstancesOf(type) + assert str(constraint) == f"an instance of '{expected_type_name}'" + + +def test_hasmethods(): + """Check the HasMethods constraint.""" + constraint = HasMethods(["a", "b"]) + + class _Good: + def a(self): + pass # pragma: no cover + + def b(self): + pass # pragma: no cover + + class _Bad: + def a(self): + pass # pragma: no cover + + assert constraint.is_satisfied_by(_Good()) + assert not constraint.is_satisfied_by(_Bad()) + assert str(constraint) == "an object implementing 'a' and 'b'" + + +@pytest.mark.parametrize( + "constraint", + [ + Interval(Real, None, 0, closed="left"), + Interval(Real, 0, None, closed="left"), + Interval(Real, None, None, closed="neither"), + StrOptions({"a", "b", "c"}), + MissingValues(), + MissingValues(numeric_only=True), + _VerboseHelper(), + HasMethods("fit"), + _IterablesNotString(), + _CVObjects(), + ], +) +def test_generate_invalid_param_val(constraint): + """Check that the value generated does not satisfy the constraint""" + bad_value = generate_invalid_param_val(constraint) + assert not constraint.is_satisfied_by(bad_value) + + +@pytest.mark.parametrize( + "integer_interval, real_interval", + [ + ( + Interval(Integral, None, 3, closed="right"), + Interval(RealNotInt, -5, 5, closed="both"), + ), + ( + Interval(Integral, None, 3, closed="right"), + Interval(RealNotInt, -5, 5, closed="neither"), + ), + ( + Interval(Integral, None, 3, closed="right"), + Interval(RealNotInt, 4, 5, closed="both"), + ), + ( + Interval(Integral, None, 3, closed="right"), + Interval(RealNotInt, 5, None, closed="left"), + ), + ( + Interval(Integral, None, 3, closed="right"), + Interval(RealNotInt, 4, None, closed="neither"), + ), + ( + Interval(Integral, 3, None, closed="left"), + Interval(RealNotInt, -5, 5, closed="both"), + ), + ( + Interval(Integral, 3, None, closed="left"), + Interval(RealNotInt, -5, 5, closed="neither"), + ), + ( + Interval(Integral, 3, None, closed="left"), + Interval(RealNotInt, 1, 2, closed="both"), + ), + ( + Interval(Integral, 3, None, closed="left"), + Interval(RealNotInt, None, -5, closed="left"), + ), + ( + Interval(Integral, 3, None, closed="left"), + Interval(RealNotInt, None, -4, closed="neither"), + ), + ( + Interval(Integral, -5, 5, closed="both"), + Interval(RealNotInt, None, 1, closed="right"), + ), + ( + Interval(Integral, -5, 5, closed="both"), + Interval(RealNotInt, 1, None, closed="left"), + ), + ( + Interval(Integral, -5, 5, closed="both"), + Interval(RealNotInt, -10, -4, closed="neither"), + ), + ( + Interval(Integral, -5, 5, closed="both"), + Interval(RealNotInt, -10, -4, closed="right"), + ), + ( + Interval(Integral, -5, 5, closed="neither"), + Interval(RealNotInt, 6, 10, closed="neither"), + ), + ( + Interval(Integral, -5, 5, closed="neither"), + Interval(RealNotInt, 6, 10, closed="left"), + ), + ( + Interval(Integral, 2, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="both"), + ), + ( + Interval(Integral, 1, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="both"), + ), + ], +) +def test_generate_invalid_param_val_2_intervals(integer_interval, real_interval): + """Check that the value generated for an interval constraint does not satisfy any of + the interval constraints. + """ + bad_value = generate_invalid_param_val(constraint=real_interval) + assert not real_interval.is_satisfied_by(bad_value) + assert not integer_interval.is_satisfied_by(bad_value) + + bad_value = generate_invalid_param_val(constraint=integer_interval) + assert not real_interval.is_satisfied_by(bad_value) + assert not integer_interval.is_satisfied_by(bad_value) + + +@pytest.mark.parametrize( + "constraint", + [ + _ArrayLikes(), + _InstancesOf(list), + _Callables(), + _NoneConstraint(), + _RandomStates(), + _SparseMatrices(), + _Booleans(), + Interval(Integral, None, None, closed="neither"), + ], +) +def test_generate_invalid_param_val_all_valid(constraint): + """Check that the function raises NotImplementedError when there's no invalid value + for the constraint. + """ + with pytest.raises(NotImplementedError): + generate_invalid_param_val(constraint) + + +@pytest.mark.parametrize( + "constraint", + [ + _ArrayLikes(), + _Callables(), + _InstancesOf(list), + _NoneConstraint(), + _RandomStates(), + _SparseMatrices(), + _Booleans(), + _VerboseHelper(), + MissingValues(), + MissingValues(numeric_only=True), + StrOptions({"a", "b", "c"}), + Options(Integral, {1, 2, 3}), + Interval(Integral, None, None, closed="neither"), + Interval(Integral, 0, 10, closed="neither"), + Interval(Integral, 0, None, closed="neither"), + Interval(Integral, None, 0, closed="neither"), + Interval(Real, 0, 1, closed="neither"), + Interval(Real, 0, None, closed="both"), + Interval(Real, None, 0, closed="right"), + HasMethods("fit"), + _IterablesNotString(), + _CVObjects(), + ], +) +def test_generate_valid_param(constraint): + """Check that the value generated does satisfy the constraint.""" + value = generate_valid_param(constraint) + assert constraint.is_satisfied_by(value) + + +@pytest.mark.parametrize( + "constraint_declaration, value", + [ + (Interval(Real, 0, 1, closed="both"), 0.42), + (Interval(Integral, 0, None, closed="neither"), 42), + (StrOptions({"a", "b", "c"}), "b"), + (Options(type, {np.float32, np.float64}), np.float64), + (callable, lambda x: x + 1), + (None, None), + ("array-like", [[1, 2], [3, 4]]), + ("array-like", np.array([[1, 2], [3, 4]])), + ("sparse matrix", csr_matrix([[1, 2], [3, 4]])), + ("random_state", 0), + ("random_state", np.random.RandomState(0)), + ("random_state", None), + (_Class, _Class()), + (int, 1), + (Real, 0.5), + ("boolean", False), + ("verbose", 1), + ("nan", np.nan), + (MissingValues(), -1), + (MissingValues(), -1.0), + (MissingValues(), 2**1028), + (MissingValues(), None), + (MissingValues(), float("nan")), + (MissingValues(), np.nan), + (MissingValues(), "missing"), + (HasMethods("fit"), _Estimator(a=0)), + ("cv_object", 5), + ], +) +def test_is_satisfied_by(constraint_declaration, value): + """Sanity check for the is_satisfied_by method""" + constraint = make_constraint(constraint_declaration) + assert constraint.is_satisfied_by(value) + + +@pytest.mark.parametrize( + "constraint_declaration, expected_constraint_class", + [ + (Interval(Real, 0, 1, closed="both"), Interval), + (StrOptions({"option1", "option2"}), StrOptions), + (Options(Real, {0.42, 1.23}), Options), + ("array-like", _ArrayLikes), + ("sparse matrix", _SparseMatrices), + ("random_state", _RandomStates), + (None, _NoneConstraint), + (callable, _Callables), + (int, _InstancesOf), + ("boolean", _Booleans), + ("verbose", _VerboseHelper), + (MissingValues(numeric_only=True), MissingValues), + (HasMethods("fit"), HasMethods), + ("cv_object", _CVObjects), + ("nan", _NanConstraint), + ], +) +def test_make_constraint(constraint_declaration, expected_constraint_class): + """Check that make_constraint dispatches to the appropriate constraint class""" + constraint = make_constraint(constraint_declaration) + assert constraint.__class__ is expected_constraint_class + + +def test_make_constraint_unknown(): + """Check that an informative error is raised when an unknown constraint is passed""" + with pytest.raises(ValueError, match="Unknown constraint"): + make_constraint("not a valid constraint") + + +def test_validate_params(): + """Check that validate_params works no matter how the arguments are passed""" + with pytest.raises( + InvalidParameterError, match="The 'a' parameter of _func must be" + ): + _func("wrong", c=1) + + with pytest.raises( + InvalidParameterError, match="The 'b' parameter of _func must be" + ): + _func(*[1, "wrong"], c=1) + + with pytest.raises( + InvalidParameterError, match="The 'c' parameter of _func must be" + ): + _func(1, **{"c": "wrong"}) + + with pytest.raises( + InvalidParameterError, match="The 'd' parameter of _func must be" + ): + _func(1, c=1, d="wrong") + + # check in the presence of extra positional and keyword args + with pytest.raises( + InvalidParameterError, match="The 'b' parameter of _func must be" + ): + _func(0, *["wrong", 2, 3], c=4, **{"e": 5}) + + with pytest.raises( + InvalidParameterError, match="The 'c' parameter of _func must be" + ): + _func(0, *[1, 2, 3], c="four", **{"e": 5}) + + +def test_validate_params_missing_params(): + """Check that no error is raised when there are parameters without + constraints + """ + + @validate_params({"a": [int]}, prefer_skip_nested_validation=True) + def func(a, b): + pass + + func(1, 2) + + +def test_decorate_validated_function(): + """Check that validate_params functions can be decorated""" + decorated_function = deprecated()(_func) + + with pytest.warns(FutureWarning, match="Function _func is deprecated"): + decorated_function(1, 2, c=3) + + # outer decorator does not interfere with validation + with pytest.warns(FutureWarning, match="Function _func is deprecated"): + with pytest.raises( + InvalidParameterError, match=r"The 'c' parameter of _func must be" + ): + decorated_function(1, 2, c="wrong") + + +def test_validate_params_method(): + """Check that validate_params works with methods""" + with pytest.raises( + InvalidParameterError, match="The 'a' parameter of _Class._method must be" + ): + _Class()._method("wrong") + + # validated method can be decorated + with pytest.warns(FutureWarning, match="Function _deprecated_method is deprecated"): + with pytest.raises( + InvalidParameterError, + match="The 'a' parameter of _Class._deprecated_method must be", + ): + _Class()._deprecated_method("wrong") + + +def test_validate_params_estimator(): + """Check that validate_params works with Estimator instances""" + # no validation in init + est = _Estimator("wrong") + + with pytest.raises( + InvalidParameterError, match="The 'a' parameter of _Estimator must be" + ): + est.fit() + + +def test_stroptions_deprecated_subset(): + """Check that the deprecated parameter must be a subset of options.""" + with pytest.raises(ValueError, match="deprecated options must be a subset"): + StrOptions({"a", "b", "c"}, deprecated={"a", "d"}) + + +def test_hidden_constraint(): + """Check that internal constraints are not exposed in the error message.""" + + @validate_params( + {"param": [Hidden(list), dict]}, prefer_skip_nested_validation=True + ) + def f(param): + pass + + # list and dict are valid params + f({"a": 1, "b": 2, "c": 3}) + f([1, 2, 3]) + + with pytest.raises( + InvalidParameterError, match="The 'param' parameter" + ) as exc_info: + f(param="bad") + + # the list option is not exposed in the error message + err_msg = str(exc_info.value) + assert "an instance of 'dict'" in err_msg + assert "an instance of 'list'" not in err_msg + + +def test_hidden_stroptions(): + """Check that we can have 2 StrOptions constraints, one being hidden.""" + + @validate_params( + {"param": [StrOptions({"auto"}), Hidden(StrOptions({"warn"}))]}, + prefer_skip_nested_validation=True, + ) + def f(param): + pass + + # "auto" and "warn" are valid params + f("auto") + f("warn") + + with pytest.raises( + InvalidParameterError, match="The 'param' parameter" + ) as exc_info: + f(param="bad") + + # the "warn" option is not exposed in the error message + err_msg = str(exc_info.value) + assert "auto" in err_msg + assert "warn" not in err_msg + + +def test_validate_params_set_param_constraints_attribute(): + """Check that the validate_params decorator properly sets the parameter constraints + as attribute of the decorated function/method. + """ + assert hasattr(_func, "_skl_parameter_constraints") + assert hasattr(_Class()._method, "_skl_parameter_constraints") + + +def test_boolean_constraint_deprecated_int(): + """Check that validate_params raise a deprecation message but still passes + validation when using an int for a parameter accepting a boolean. + """ + + @validate_params({"param": ["boolean"]}, prefer_skip_nested_validation=True) + def f(param): + pass + + # True/False and np.bool_(True/False) are valid params + f(True) + f(np.bool_(False)) + + +def test_no_validation(): + """Check that validation can be skipped for a parameter.""" + + @validate_params( + {"param1": [int, None], "param2": "no_validation"}, + prefer_skip_nested_validation=True, + ) + def f(param1=None, param2=None): + pass + + # param1 is validated + with pytest.raises(InvalidParameterError, match="The 'param1' parameter"): + f(param1="wrong") + + # param2 is not validated: any type is valid. + class SomeType: + pass + + f(param2=SomeType) + f(param2=SomeType()) + + +def test_pandas_na_constraint_with_pd_na(): + """Add a specific test for checking support for `pandas.NA`.""" + pd = pytest.importorskip("pandas") + + na_constraint = _PandasNAConstraint() + assert na_constraint.is_satisfied_by(pd.NA) + assert not na_constraint.is_satisfied_by(np.array([1, 2, 3])) + + +def test_iterable_not_string(): + """Check that a string does not satisfy the _IterableNotString constraint.""" + constraint = _IterablesNotString() + assert constraint.is_satisfied_by([1, 2, 3]) + assert constraint.is_satisfied_by(range(10)) + assert not constraint.is_satisfied_by("some string") + + +def test_cv_objects(): + """Check that the _CVObjects constraint accepts all current ways + to pass cv objects.""" + constraint = _CVObjects() + assert constraint.is_satisfied_by(5) + assert constraint.is_satisfied_by(LeaveOneOut()) + assert constraint.is_satisfied_by([([1, 2], [3, 4]), ([3, 4], [1, 2])]) + assert constraint.is_satisfied_by(None) + assert not constraint.is_satisfied_by("not a CV object") + + +def test_third_party_estimator(): + """Check that the validation from a scikit-learn estimator inherited by a third + party estimator does not impose a match between the dict of constraints and the + parameters of the estimator. + """ + + class ThirdPartyEstimator(_Estimator): + def __init__(self, b): + self.b = b + super().__init__(a=0) + + def fit(self, X=None, y=None): + super().fit(X, y) + + # does not raise, even though "b" is not in the constraints dict and "a" is not + # a parameter of the estimator. + ThirdPartyEstimator(b=0).fit() + + +def test_interval_real_not_int(): + """Check for the type RealNotInt in the Interval constraint.""" + constraint = Interval(RealNotInt, 0, 1, closed="both") + assert constraint.is_satisfied_by(1.0) + assert not constraint.is_satisfied_by(1) + + +def test_real_not_int(): + """Check for the RealNotInt type.""" + assert isinstance(1.0, RealNotInt) + assert not isinstance(1, RealNotInt) + assert isinstance(np.float64(1), RealNotInt) + assert not isinstance(np.int64(1), RealNotInt) + + +def test_skip_param_validation(): + """Check that param validation can be skipped using config_context.""" + + @validate_params({"a": [int]}, prefer_skip_nested_validation=True) + def f(a): + pass + + with pytest.raises(InvalidParameterError, match="The 'a' parameter"): + f(a="1") + + # does not raise + with config_context(skip_parameter_validation=True): + f(a="1") + + +@pytest.mark.parametrize("prefer_skip_nested_validation", [True, False]) +def test_skip_nested_validation(prefer_skip_nested_validation): + """Check that nested validation can be skipped.""" + + @validate_params({"a": [int]}, prefer_skip_nested_validation=True) + def f(a): + pass + + @validate_params( + {"b": [int]}, + prefer_skip_nested_validation=prefer_skip_nested_validation, + ) + def g(b): + # calls f with a bad parameter type + return f(a="invalid_param_value") + + # Validation for g is never skipped. + with pytest.raises(InvalidParameterError, match="The 'b' parameter"): + g(b="invalid_param_value") + + if prefer_skip_nested_validation: + g(b=1) # does not raise because inner f is not validated + else: + with pytest.raises(InvalidParameterError, match="The 'a' parameter"): + g(b=1) + + +@pytest.mark.parametrize( + "skip_parameter_validation, prefer_skip_nested_validation, expected_skipped", + [ + (True, True, True), + (True, False, True), + (False, True, True), + (False, False, False), + ], +) +def test_skip_nested_validation_and_config_context( + skip_parameter_validation, prefer_skip_nested_validation, expected_skipped +): + """Check interaction between global skip and local skip.""" + + @validate_params( + {"a": [int]}, prefer_skip_nested_validation=prefer_skip_nested_validation + ) + def g(a): + return get_config()["skip_parameter_validation"] + + with config_context(skip_parameter_validation=skip_parameter_validation): + actual_skipped = g(1) + + assert actual_skipped == expected_skipped diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_plotting.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_plotting.py new file mode 100644 index 0000000000000000000000000000000000000000..b2448c2b044e1338cebaec7f247eaafb48f05381 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_plotting.py @@ -0,0 +1,63 @@ +import numpy as np +import pytest + +from sklearn.utils._plotting import _interval_max_min_ratio, _validate_score_name + + +def metric(): + pass # pragma: no cover + + +def neg_metric(): + pass # pragma: no cover + + +@pytest.mark.parametrize( + "score_name, scoring, negate_score, expected_score_name", + [ + ("accuracy", None, False, "accuracy"), # do not transform the name + (None, "accuracy", False, "Accuracy"), # capitalize the name + (None, "accuracy", True, "Negative accuracy"), # add "Negative" + (None, "neg_mean_absolute_error", False, "Negative mean absolute error"), + (None, "neg_mean_absolute_error", True, "Mean absolute error"), # remove "neg_" + ("MAE", "neg_mean_absolute_error", True, "MAE"), # keep score_name + (None, None, False, "Score"), # default name + (None, None, True, "Negative score"), # default name but negated + ("Some metric", metric, False, "Some metric"), # do not transform the name + ("Some metric", metric, True, "Some metric"), # do not transform the name + (None, metric, False, "Metric"), # default name + (None, metric, True, "Negative metric"), # default name but negated + ("Some metric", neg_metric, False, "Some metric"), # do not transform the name + ("Some metric", neg_metric, True, "Some metric"), # do not transform the name + (None, neg_metric, False, "Negative metric"), # default name + (None, neg_metric, True, "Metric"), # default name but negated + ], +) +def test_validate_score_name(score_name, scoring, negate_score, expected_score_name): + """Check that we return the right score name.""" + assert ( + _validate_score_name(score_name, scoring, negate_score) == expected_score_name + ) + + +# In the following test, we check the value of the max to min ratio +# for parameter value intervals to check that using a decision threshold +# of 5. is a good heuristic to decide between linear and log scales on +# common ranges of parameter values. +@pytest.mark.parametrize( + "data, lower_bound, upper_bound", + [ + # Such a range could be clearly displayed with either log scale or linear + # scale. + (np.geomspace(0.1, 1, 5), 5, 6), + # Checking that the ratio is still positive on a negative log scale. + (-np.geomspace(0.1, 1, 10), 7, 8), + # Evenly spaced parameter values lead to a ratio of 1. + (np.linspace(0, 1, 5), 0.9, 1.1), + # This is not exactly spaced on a log scale but we will benefit from treating + # it as such for visualization. + ([1, 2, 5, 10, 20, 50], 20, 40), + ], +) +def test_inverval_max_min_ratio(data, lower_bound, upper_bound): + assert lower_bound < _interval_max_min_ratio(data) < upper_bound diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_response.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_response.py new file mode 100644 index 0000000000000000000000000000000000000000..c84bf6030336a742a12a8097ce71ebe7bee49f55 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_response.py @@ -0,0 +1,347 @@ +import numpy as np +import pytest + +from sklearn.datasets import ( + load_iris, + make_classification, + make_multilabel_classification, + make_regression, +) +from sklearn.ensemble import IsolationForest +from sklearn.linear_model import ( + LinearRegression, + LogisticRegression, +) +from sklearn.multioutput import ClassifierChain +from sklearn.preprocessing import scale +from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor +from sklearn.utils._mocking import _MockEstimatorOnOffPrediction +from sklearn.utils._response import _get_response_values, _get_response_values_binary +from sklearn.utils._testing import assert_allclose, assert_array_equal + +X, y = load_iris(return_X_y=True) +# scale the data to avoid ConvergenceWarning with LogisticRegression +X = scale(X, copy=False) +X_binary, y_binary = X[:100], y[:100] + + +@pytest.mark.parametrize( + "response_method", ["decision_function", "predict_proba", "predict_log_proba"] +) +def test_get_response_values_regressor_error(response_method): + """Check the error message with regressor an not supported response + method.""" + my_estimator = _MockEstimatorOnOffPrediction(response_methods=[response_method]) + X = "mocking_data", "mocking_target" + err_msg = f"{my_estimator.__class__.__name__} should either be a classifier" + with pytest.raises(ValueError, match=err_msg): + _get_response_values(my_estimator, X, response_method=response_method) + + +@pytest.mark.parametrize("return_response_method_used", [True, False]) +def test_get_response_values_regressor(return_response_method_used): + """Check the behaviour of `_get_response_values` with regressor.""" + X, y = make_regression(n_samples=10, random_state=0) + regressor = LinearRegression().fit(X, y) + results = _get_response_values( + regressor, + X, + response_method="predict", + return_response_method_used=return_response_method_used, + ) + assert_array_equal(results[0], regressor.predict(X)) + assert results[1] is None + if return_response_method_used: + assert results[2] == "predict" + + +@pytest.mark.parametrize( + "response_method", + ["predict", "decision_function", ["decision_function", "predict"]], +) +@pytest.mark.parametrize("return_response_method_used", [True, False]) +def test_get_response_values_outlier_detection( + response_method, return_response_method_used +): + """Check the behaviour of `_get_response_values` with outlier detector.""" + X, y = make_classification(n_samples=50, random_state=0) + outlier_detector = IsolationForest(random_state=0).fit(X, y) + results = _get_response_values( + outlier_detector, + X, + response_method=response_method, + return_response_method_used=return_response_method_used, + ) + chosen_response_method = ( + response_method[0] if isinstance(response_method, list) else response_method + ) + prediction_method = getattr(outlier_detector, chosen_response_method) + assert_array_equal(results[0], prediction_method(X)) + assert results[1] is None + if return_response_method_used: + assert results[2] == chosen_response_method + + +@pytest.mark.parametrize( + "response_method", + ["predict_proba", "decision_function", "predict", "predict_log_proba"], +) +def test_get_response_values_classifier_unknown_pos_label(response_method): + """Check that `_get_response_values` raises the proper error message with + classifier.""" + X, y = make_classification(n_samples=10, n_classes=2, random_state=0) + classifier = LogisticRegression().fit(X, y) + + # provide a `pos_label` which is not in `y` + err_msg = r"pos_label=whatever is not a valid label: It should be one of \[0 1\]" + with pytest.raises(ValueError, match=err_msg): + _get_response_values( + classifier, + X, + response_method=response_method, + pos_label="whatever", + ) + + +@pytest.mark.parametrize("response_method", ["predict_proba", "predict_log_proba"]) +def test_get_response_values_classifier_inconsistent_y_pred_for_binary_proba( + response_method, +): + """Check that `_get_response_values` will raise an error when `y_pred` has a + single class with `predict_proba`.""" + X, y_two_class = make_classification(n_samples=10, n_classes=2, random_state=0) + y_single_class = np.zeros_like(y_two_class) + classifier = DecisionTreeClassifier().fit(X, y_single_class) + + err_msg = ( + r"Got predict_proba of shape \(10, 1\), but need classifier with " + r"two classes" + ) + with pytest.raises(ValueError, match=err_msg): + _get_response_values(classifier, X, response_method=response_method) + + +@pytest.mark.parametrize("return_response_method_used", [True, False]) +def test_get_response_values_binary_classifier_decision_function( + return_response_method_used, +): + """Check the behaviour of `_get_response_values` with `decision_function` + and binary classifier.""" + X, y = make_classification( + n_samples=10, + n_classes=2, + weights=[0.3, 0.7], + random_state=0, + ) + classifier = LogisticRegression().fit(X, y) + response_method = "decision_function" + + # default `pos_label` + results = _get_response_values( + classifier, + X, + response_method=response_method, + pos_label=None, + return_response_method_used=return_response_method_used, + ) + assert_allclose(results[0], classifier.decision_function(X)) + assert results[1] == 1 + if return_response_method_used: + assert results[2] == "decision_function" + + # when forcing `pos_label=classifier.classes_[0]` + results = _get_response_values( + classifier, + X, + response_method=response_method, + pos_label=classifier.classes_[0], + return_response_method_used=return_response_method_used, + ) + assert_allclose(results[0], classifier.decision_function(X) * -1) + assert results[1] == 0 + if return_response_method_used: + assert results[2] == "decision_function" + + +@pytest.mark.parametrize("return_response_method_used", [True, False]) +@pytest.mark.parametrize("response_method", ["predict_proba", "predict_log_proba"]) +def test_get_response_values_binary_classifier_predict_proba( + return_response_method_used, response_method +): + """Check that `_get_response_values` with `predict_proba` and binary + classifier.""" + X, y = make_classification( + n_samples=10, + n_classes=2, + weights=[0.3, 0.7], + random_state=0, + ) + classifier = LogisticRegression().fit(X, y) + + # default `pos_label` + results = _get_response_values( + classifier, + X, + response_method=response_method, + pos_label=None, + return_response_method_used=return_response_method_used, + ) + assert_allclose(results[0], getattr(classifier, response_method)(X)[:, 1]) + assert results[1] == 1 + if return_response_method_used: + assert len(results) == 3 + assert results[2] == response_method + else: + assert len(results) == 2 + + # when forcing `pos_label=classifier.classes_[0]` + y_pred, pos_label, *_ = _get_response_values( + classifier, + X, + response_method=response_method, + pos_label=classifier.classes_[0], + return_response_method_used=return_response_method_used, + ) + assert_allclose(y_pred, getattr(classifier, response_method)(X)[:, 0]) + assert pos_label == 0 + + +@pytest.mark.parametrize( + "estimator, X, y, err_msg, params", + [ + ( + DecisionTreeRegressor(), + X_binary, + y_binary, + "Expected 'estimator' to be a binary classifier", + {"response_method": "auto"}, + ), + ( + DecisionTreeClassifier(), + X_binary, + y_binary, + r"pos_label=unknown is not a valid label: It should be one of \[0 1\]", + {"response_method": "auto", "pos_label": "unknown"}, + ), + ( + DecisionTreeClassifier(), + X, + y, + "be a binary classifier. Got 3 classes instead.", + {"response_method": "predict_proba"}, + ), + ], +) +def test_get_response_error(estimator, X, y, err_msg, params): + """Check that we raise the proper error messages in _get_response_values_binary.""" + + estimator.fit(X, y) + with pytest.raises(ValueError, match=err_msg): + _get_response_values_binary(estimator, X, **params) + + +def test_get_response_predict_proba(): + """Check the behaviour of `_get_response_values_binary` using `predict_proba`.""" + classifier = DecisionTreeClassifier().fit(X_binary, y_binary) + y_proba, pos_label = _get_response_values_binary( + classifier, X_binary, response_method="predict_proba" + ) + assert_allclose(y_proba, classifier.predict_proba(X_binary)[:, 1]) + assert pos_label == 1 + + y_proba, pos_label = _get_response_values_binary( + classifier, X_binary, response_method="predict_proba", pos_label=0 + ) + assert_allclose(y_proba, classifier.predict_proba(X_binary)[:, 0]) + assert pos_label == 0 + + +def test_get_response_decision_function(): + """Check the behaviour of `_get_response_values_binary` using decision_function.""" + classifier = LogisticRegression().fit(X_binary, y_binary) + y_score, pos_label = _get_response_values_binary( + classifier, X_binary, response_method="decision_function" + ) + assert_allclose(y_score, classifier.decision_function(X_binary)) + assert pos_label == 1 + + y_score, pos_label = _get_response_values_binary( + classifier, X_binary, response_method="decision_function", pos_label=0 + ) + assert_allclose(y_score, classifier.decision_function(X_binary) * -1) + assert pos_label == 0 + + +@pytest.mark.parametrize( + "estimator, response_method", + [ + (DecisionTreeClassifier(max_depth=2, random_state=0), "predict_proba"), + (DecisionTreeClassifier(max_depth=2, random_state=0), "predict_log_proba"), + (LogisticRegression(), "decision_function"), + ], +) +def test_get_response_values_multiclass(estimator, response_method): + """Check that we can call `_get_response_values` with a multiclass estimator. + It should return the predictions untouched. + """ + estimator.fit(X, y) + predictions, pos_label = _get_response_values( + estimator, X, response_method=response_method + ) + + assert pos_label is None + assert predictions.shape == (X.shape[0], len(estimator.classes_)) + if response_method == "predict_proba": + assert np.logical_and(predictions >= 0, predictions <= 1).all() + elif response_method == "predict_log_proba": + assert (predictions <= 0.0).all() + + +def test_get_response_values_with_response_list(): + """Check the behaviour of passing a list of responses to `_get_response_values`.""" + classifier = LogisticRegression().fit(X_binary, y_binary) + + # it should use `predict_proba` + y_pred, pos_label, response_method = _get_response_values( + classifier, + X_binary, + response_method=["predict_proba", "decision_function"], + return_response_method_used=True, + ) + assert_allclose(y_pred, classifier.predict_proba(X_binary)[:, 1]) + assert pos_label == 1 + assert response_method == "predict_proba" + + # it should use `decision_function` + y_pred, pos_label, response_method = _get_response_values( + classifier, + X_binary, + response_method=["decision_function", "predict_proba"], + return_response_method_used=True, + ) + assert_allclose(y_pred, classifier.decision_function(X_binary)) + assert pos_label == 1 + assert response_method == "decision_function" + + +@pytest.mark.parametrize( + "response_method", ["predict_proba", "decision_function", "predict"] +) +def test_get_response_values_multilabel_indicator(response_method): + X, Y = make_multilabel_classification(random_state=0) + estimator = ClassifierChain(LogisticRegression()).fit(X, Y) + + y_pred, pos_label = _get_response_values( + estimator, X, response_method=response_method + ) + assert pos_label is None + assert y_pred.shape == Y.shape + + if response_method == "predict_proba": + assert np.logical_and(y_pred >= 0, y_pred <= 1).all() + elif response_method == "decision_function": + # values returned by `decision_function` are not bounded in [0, 1] + assert (y_pred < 0).sum() > 0 + assert (y_pred > 1).sum() > 0 + else: # response_method == "predict" + assert np.logical_or(y_pred == 0, y_pred == 1).all() diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_seq_dataset.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_seq_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..82864c6b97a08f2247c0b63c388e0f7929dae400 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_seq_dataset.py @@ -0,0 +1,185 @@ +# Author: Tom Dupre la Tour +# Joan Massich +# +# License: BSD 3 clause + +from itertools import product + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +from sklearn.datasets import load_iris +from sklearn.utils._seq_dataset import ( + ArrayDataset32, + ArrayDataset64, + CSRDataset32, + CSRDataset64, +) +from sklearn.utils._testing import assert_allclose +from sklearn.utils.fixes import CSR_CONTAINERS + +iris = load_iris() +X64 = iris.data.astype(np.float64) +y64 = iris.target.astype(np.float64) +sample_weight64 = np.arange(y64.size, dtype=np.float64) + +X32 = iris.data.astype(np.float32) +y32 = iris.target.astype(np.float32) +sample_weight32 = np.arange(y32.size, dtype=np.float32) + +floating = [np.float32, np.float64] + + +def assert_csr_equal_values(current, expected): + current.eliminate_zeros() + expected.eliminate_zeros() + expected = expected.astype(current.dtype) + assert current.shape[0] == expected.shape[0] + assert current.shape[1] == expected.shape[1] + assert_array_equal(current.data, expected.data) + assert_array_equal(current.indices, expected.indices) + assert_array_equal(current.indptr, expected.indptr) + + +def _make_dense_dataset(float_dtype): + if float_dtype == np.float32: + return ArrayDataset32(X32, y32, sample_weight32, seed=42) + return ArrayDataset64(X64, y64, sample_weight64, seed=42) + + +def _make_sparse_dataset(csr_container, float_dtype): + if float_dtype == np.float32: + X, y, sample_weight, csr_dataset = X32, y32, sample_weight32, CSRDataset32 + else: + X, y, sample_weight, csr_dataset = X64, y64, sample_weight64, CSRDataset64 + X = csr_container(X) + return csr_dataset(X.data, X.indptr, X.indices, y, sample_weight, seed=42) + + +def _make_dense_datasets(): + return [_make_dense_dataset(float_dtype) for float_dtype in floating] + + +def _make_sparse_datasets(): + return [ + _make_sparse_dataset(csr_container, float_dtype) + for csr_container, float_dtype in product(CSR_CONTAINERS, floating) + ] + + +def _make_fused_types_datasets(): + all_datasets = _make_dense_datasets() + _make_sparse_datasets() + # group dataset by array types to get a tuple (float32, float64) + return (all_datasets[idx : idx + 2] for idx in range(0, len(all_datasets), 2)) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +@pytest.mark.parametrize("dataset", _make_dense_datasets() + _make_sparse_datasets()) +def test_seq_dataset_basic_iteration(dataset, csr_container): + NUMBER_OF_RUNS = 5 + X_csr64 = csr_container(X64) + for _ in range(NUMBER_OF_RUNS): + # next sample + xi_, yi, swi, idx = dataset._next_py() + xi = csr_container(xi_, shape=(1, X64.shape[1])) + + assert_csr_equal_values(xi, X_csr64[[idx]]) + assert yi == y64[idx] + assert swi == sample_weight64[idx] + + # random sample + xi_, yi, swi, idx = dataset._random_py() + xi = csr_container(xi_, shape=(1, X64.shape[1])) + + assert_csr_equal_values(xi, X_csr64[[idx]]) + assert yi == y64[idx] + assert swi == sample_weight64[idx] + + +@pytest.mark.parametrize( + "dense_dataset,sparse_dataset", + [ + ( + _make_dense_dataset(float_dtype), + _make_sparse_dataset(csr_container, float_dtype), + ) + for float_dtype, csr_container in product(floating, CSR_CONTAINERS) + ], +) +def test_seq_dataset_shuffle(dense_dataset, sparse_dataset): + # not shuffled + for i in range(5): + _, _, _, idx1 = dense_dataset._next_py() + _, _, _, idx2 = sparse_dataset._next_py() + assert idx1 == i + assert idx2 == i + + for i in [132, 50, 9, 18, 58]: + _, _, _, idx1 = dense_dataset._random_py() + _, _, _, idx2 = sparse_dataset._random_py() + assert idx1 == i + assert idx2 == i + + seed = 77 + dense_dataset._shuffle_py(seed) + sparse_dataset._shuffle_py(seed) + + idx_next = [63, 91, 148, 87, 29] + idx_shuffle = [137, 125, 56, 121, 127] + for i, j in zip(idx_next, idx_shuffle): + _, _, _, idx1 = dense_dataset._next_py() + _, _, _, idx2 = sparse_dataset._next_py() + assert idx1 == i + assert idx2 == i + + _, _, _, idx1 = dense_dataset._random_py() + _, _, _, idx2 = sparse_dataset._random_py() + assert idx1 == j + assert idx2 == j + + +@pytest.mark.parametrize("dataset_32,dataset_64", _make_fused_types_datasets()) +def test_fused_types_consistency(dataset_32, dataset_64): + NUMBER_OF_RUNS = 5 + for _ in range(NUMBER_OF_RUNS): + # next sample + (xi_data32, _, _), yi32, _, _ = dataset_32._next_py() + (xi_data64, _, _), yi64, _, _ = dataset_64._next_py() + + assert xi_data32.dtype == np.float32 + assert xi_data64.dtype == np.float64 + + assert_allclose(xi_data64, xi_data32, rtol=1e-5) + assert_allclose(yi64, yi32, rtol=1e-5) + + +def test_buffer_dtype_mismatch_error(): + with pytest.raises(ValueError, match="Buffer dtype mismatch"): + ArrayDataset64(X32, y32, sample_weight32, seed=42), + + with pytest.raises(ValueError, match="Buffer dtype mismatch"): + ArrayDataset32(X64, y64, sample_weight64, seed=42), + + for csr_container in CSR_CONTAINERS: + X_csr32 = csr_container(X32) + X_csr64 = csr_container(X64) + with pytest.raises(ValueError, match="Buffer dtype mismatch"): + CSRDataset64( + X_csr32.data, + X_csr32.indptr, + X_csr32.indices, + y32, + sample_weight32, + seed=42, + ), + + with pytest.raises(ValueError, match="Buffer dtype mismatch"): + CSRDataset32( + X_csr64.data, + X_csr64.indptr, + X_csr64.indices, + y64, + sample_weight64, + seed=42, + ), diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_show_versions.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_show_versions.py new file mode 100644 index 0000000000000000000000000000000000000000..bd166dfd8e5227ba849e2088a541ecd955fafae2 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_show_versions.py @@ -0,0 +1,39 @@ +from sklearn.utils._show_versions import _get_deps_info, _get_sys_info, show_versions +from sklearn.utils._testing import ignore_warnings +from sklearn.utils.fixes import threadpool_info + + +def test_get_sys_info(): + sys_info = _get_sys_info() + + assert "python" in sys_info + assert "executable" in sys_info + assert "machine" in sys_info + + +def test_get_deps_info(): + with ignore_warnings(): + deps_info = _get_deps_info() + + assert "pip" in deps_info + assert "setuptools" in deps_info + assert "sklearn" in deps_info + assert "numpy" in deps_info + assert "scipy" in deps_info + assert "Cython" in deps_info + assert "pandas" in deps_info + assert "matplotlib" in deps_info + assert "joblib" in deps_info + + +def test_show_versions(capsys): + with ignore_warnings(): + show_versions() + out, err = capsys.readouterr() + + assert "python" in out + assert "numpy" in out + + info = threadpool_info() + if info: + assert "threadpoolctl info:" in out diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_stats.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf679b99b7f296b6037fbc262bfddd49cd03c89 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_stats.py @@ -0,0 +1,98 @@ +import numpy as np +from numpy.testing import assert_allclose +from pytest import approx + +from sklearn.utils.stats import _weighted_percentile + + +def test_weighted_percentile(): + y = np.empty(102, dtype=np.float64) + y[:50] = 0 + y[-51:] = 2 + y[-1] = 100000 + y[50] = 1 + sw = np.ones(102, dtype=np.float64) + sw[-1] = 0.0 + score = _weighted_percentile(y, sw, 50) + assert approx(score) == 1 + + +def test_weighted_percentile_equal(): + y = np.empty(102, dtype=np.float64) + y.fill(0.0) + sw = np.ones(102, dtype=np.float64) + sw[-1] = 0.0 + score = _weighted_percentile(y, sw, 50) + assert score == 0 + + +def test_weighted_percentile_zero_weight(): + y = np.empty(102, dtype=np.float64) + y.fill(1.0) + sw = np.ones(102, dtype=np.float64) + sw.fill(0.0) + score = _weighted_percentile(y, sw, 50) + assert approx(score) == 1.0 + + +def test_weighted_percentile_zero_weight_zero_percentile(): + y = np.array([0, 1, 2, 3, 4, 5]) + sw = np.array([0, 0, 1, 1, 1, 0]) + score = _weighted_percentile(y, sw, 0) + assert approx(score) == 2 + + score = _weighted_percentile(y, sw, 50) + assert approx(score) == 3 + + score = _weighted_percentile(y, sw, 100) + assert approx(score) == 4 + + +def test_weighted_median_equal_weights(): + # Checks weighted percentile=0.5 is same as median when weights equal + rng = np.random.RandomState(0) + # Odd size as _weighted_percentile takes lower weighted percentile + x = rng.randint(10, size=11) + weights = np.ones(x.shape) + + median = np.median(x) + w_median = _weighted_percentile(x, weights) + assert median == approx(w_median) + + +def test_weighted_median_integer_weights(): + # Checks weighted percentile=0.5 is same as median when manually weight + # data + rng = np.random.RandomState(0) + x = rng.randint(20, size=10) + weights = rng.choice(5, size=10) + x_manual = np.repeat(x, weights) + + median = np.median(x_manual) + w_median = _weighted_percentile(x, weights) + + assert median == approx(w_median) + + +def test_weighted_percentile_2d(): + # Check for when array 2D and sample_weight 1D + rng = np.random.RandomState(0) + x1 = rng.randint(10, size=10) + w1 = rng.choice(5, size=10) + + x2 = rng.randint(20, size=10) + x_2d = np.vstack((x1, x2)).T + + w_median = _weighted_percentile(x_2d, w1) + p_axis_0 = [_weighted_percentile(x_2d[:, i], w1) for i in range(x_2d.shape[1])] + assert_allclose(w_median, p_axis_0) + + # Check when array and sample_weight boht 2D + w2 = rng.choice(5, size=10) + w_2d = np.vstack((w1, w2)).T + + w_median = _weighted_percentile(x_2d, w_2d) + p_axis_0 = [ + _weighted_percentile(x_2d[:, i], w_2d[:, i]) for i in range(x_2d.shape[1]) + ] + assert_allclose(w_median, p_axis_0) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_testing.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..c219cb8c0e311dd0dab9a08fed7cb9f371397679 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_testing.py @@ -0,0 +1,923 @@ +import atexit +import os +import unittest +import warnings + +import numpy as np +import pytest +from scipy import sparse + +from sklearn.discriminant_analysis import LinearDiscriminantAnalysis +from sklearn.tree import DecisionTreeClassifier +from sklearn.utils import _IS_WASM +from sklearn.utils._testing import ( + TempMemmap, + _convert_container, + _delete_folder, + _get_warnings_filters_info_list, + assert_allclose, + assert_allclose_dense_sparse, + assert_no_warnings, + assert_raise_message, + assert_raises, + assert_raises_regex, + assert_run_python_script_without_output, + check_docstring_parameters, + create_memmap_backed_data, + ignore_warnings, + raises, + set_random_state, + turn_warnings_into_errors, +) +from sklearn.utils.deprecation import deprecated +from sklearn.utils.fixes import ( + CSC_CONTAINERS, + CSR_CONTAINERS, + parse_version, + sp_version, +) +from sklearn.utils.metaestimators import available_if + + +def test_set_random_state(): + lda = LinearDiscriminantAnalysis() + tree = DecisionTreeClassifier() + # Linear Discriminant Analysis doesn't have random state: smoke test + set_random_state(lda, 3) + set_random_state(tree, 3) + assert tree.random_state == 3 + + +@pytest.mark.parametrize("csr_container", CSC_CONTAINERS) +def test_assert_allclose_dense_sparse(csr_container): + x = np.arange(9).reshape(3, 3) + msg = "Not equal to tolerance " + y = csr_container(x) + for X in [x, y]: + # basic compare + with pytest.raises(AssertionError, match=msg): + assert_allclose_dense_sparse(X, X * 2) + assert_allclose_dense_sparse(X, X) + + with pytest.raises(ValueError, match="Can only compare two sparse"): + assert_allclose_dense_sparse(x, y) + + A = sparse.diags(np.ones(5), offsets=0).tocsr() + B = csr_container(np.ones((1, 5))) + with pytest.raises(AssertionError, match="Arrays are not equal"): + assert_allclose_dense_sparse(B, A) + + +def test_assert_raises_msg(): + with assert_raises_regex(AssertionError, "Hello world"): + with assert_raises(ValueError, msg="Hello world"): + pass + + +def test_assert_raise_message(): + def _raise_ValueError(message): + raise ValueError(message) + + def _no_raise(): + pass + + assert_raise_message(ValueError, "test", _raise_ValueError, "test") + + assert_raises( + AssertionError, + assert_raise_message, + ValueError, + "something else", + _raise_ValueError, + "test", + ) + + assert_raises( + ValueError, + assert_raise_message, + TypeError, + "something else", + _raise_ValueError, + "test", + ) + + assert_raises(AssertionError, assert_raise_message, ValueError, "test", _no_raise) + + # multiple exceptions in a tuple + assert_raises( + AssertionError, + assert_raise_message, + (ValueError, AttributeError), + "test", + _no_raise, + ) + + +def test_ignore_warning(): + # This check that ignore_warning decorator and context manager are working + # as expected + def _warning_function(): + warnings.warn("deprecation warning", DeprecationWarning) + + def _multiple_warning_function(): + warnings.warn("deprecation warning", DeprecationWarning) + warnings.warn("deprecation warning") + + # Check the function directly + assert_no_warnings(ignore_warnings(_warning_function)) + assert_no_warnings(ignore_warnings(_warning_function, category=DeprecationWarning)) + with pytest.warns(DeprecationWarning): + ignore_warnings(_warning_function, category=UserWarning)() + + with pytest.warns() as record: + ignore_warnings(_multiple_warning_function, category=FutureWarning)() + assert len(record) == 2 + assert isinstance(record[0].message, DeprecationWarning) + assert isinstance(record[1].message, UserWarning) + + with pytest.warns() as record: + ignore_warnings(_multiple_warning_function, category=UserWarning)() + assert len(record) == 1 + assert isinstance(record[0].message, DeprecationWarning) + + assert_no_warnings( + ignore_warnings(_warning_function, category=(DeprecationWarning, UserWarning)) + ) + + # Check the decorator + @ignore_warnings + def decorator_no_warning(): + _warning_function() + _multiple_warning_function() + + @ignore_warnings(category=(DeprecationWarning, UserWarning)) + def decorator_no_warning_multiple(): + _multiple_warning_function() + + @ignore_warnings(category=DeprecationWarning) + def decorator_no_deprecation_warning(): + _warning_function() + + @ignore_warnings(category=UserWarning) + def decorator_no_user_warning(): + _warning_function() + + @ignore_warnings(category=DeprecationWarning) + def decorator_no_deprecation_multiple_warning(): + _multiple_warning_function() + + @ignore_warnings(category=UserWarning) + def decorator_no_user_multiple_warning(): + _multiple_warning_function() + + assert_no_warnings(decorator_no_warning) + assert_no_warnings(decorator_no_warning_multiple) + assert_no_warnings(decorator_no_deprecation_warning) + with pytest.warns(DeprecationWarning): + decorator_no_user_warning() + with pytest.warns(UserWarning): + decorator_no_deprecation_multiple_warning() + with pytest.warns(DeprecationWarning): + decorator_no_user_multiple_warning() + + # Check the context manager + def context_manager_no_warning(): + with ignore_warnings(): + _warning_function() + + def context_manager_no_warning_multiple(): + with ignore_warnings(category=(DeprecationWarning, UserWarning)): + _multiple_warning_function() + + def context_manager_no_deprecation_warning(): + with ignore_warnings(category=DeprecationWarning): + _warning_function() + + def context_manager_no_user_warning(): + with ignore_warnings(category=UserWarning): + _warning_function() + + def context_manager_no_deprecation_multiple_warning(): + with ignore_warnings(category=DeprecationWarning): + _multiple_warning_function() + + def context_manager_no_user_multiple_warning(): + with ignore_warnings(category=UserWarning): + _multiple_warning_function() + + assert_no_warnings(context_manager_no_warning) + assert_no_warnings(context_manager_no_warning_multiple) + assert_no_warnings(context_manager_no_deprecation_warning) + with pytest.warns(DeprecationWarning): + context_manager_no_user_warning() + with pytest.warns(UserWarning): + context_manager_no_deprecation_multiple_warning() + with pytest.warns(DeprecationWarning): + context_manager_no_user_multiple_warning() + + # Check that passing warning class as first positional argument + warning_class = UserWarning + match = "'obj' should be a callable.+you should use 'category=UserWarning'" + + with pytest.raises(ValueError, match=match): + silence_warnings_func = ignore_warnings(warning_class)(_warning_function) + silence_warnings_func() + + with pytest.raises(ValueError, match=match): + + @ignore_warnings(warning_class) + def test(): + pass + + +class TestWarns(unittest.TestCase): + def test_warn(self): + def f(): + warnings.warn("yo") + return 3 + + with pytest.raises(AssertionError): + assert_no_warnings(f) + assert assert_no_warnings(lambda x: x, 1) == 1 + + +# Tests for docstrings: + + +def f_ok(a, b): + """Function f + + Parameters + ---------- + a : int + Parameter a + b : float + Parameter b + + Returns + ------- + c : list + Parameter c + """ + c = a + b + return c + + +def f_bad_sections(a, b): + """Function f + + Parameters + ---------- + a : int + Parameter a + b : float + Parameter b + + Results + ------- + c : list + Parameter c + """ + c = a + b + return c + + +def f_bad_order(b, a): + """Function f + + Parameters + ---------- + a : int + Parameter a + b : float + Parameter b + + Returns + ------- + c : list + Parameter c + """ + c = a + b + return c + + +def f_too_many_param_docstring(a, b): + """Function f + + Parameters + ---------- + a : int + Parameter a + b : int + Parameter b + c : int + Parameter c + + Returns + ------- + d : list + Parameter c + """ + d = a + b + return d + + +def f_missing(a, b): + """Function f + + Parameters + ---------- + a : int + Parameter a + + Returns + ------- + c : list + Parameter c + """ + c = a + b + return c + + +def f_check_param_definition(a, b, c, d, e): + """Function f + + Parameters + ---------- + a: int + Parameter a + b: + Parameter b + c : + This is parsed correctly in numpydoc 1.2 + d:int + Parameter d + e + No typespec is allowed without colon + """ + return a + b + c + d + + +class Klass: + def f_missing(self, X, y): + pass + + def f_bad_sections(self, X, y): + """Function f + + Parameter + --------- + a : int + Parameter a + b : float + Parameter b + + Results + ------- + c : list + Parameter c + """ + pass + + +class MockEst: + def __init__(self): + """MockEstimator""" + + def fit(self, X, y): + return X + + def predict(self, X): + return X + + def predict_proba(self, X): + return X + + def score(self, X): + return 1.0 + + +class MockMetaEstimator: + def __init__(self, delegate): + """MetaEstimator to check if doctest on delegated methods work. + + Parameters + --------- + delegate : estimator + Delegated estimator. + """ + self.delegate = delegate + + @available_if(lambda self: hasattr(self.delegate, "predict")) + def predict(self, X): + """This is available only if delegate has predict. + + Parameters + ---------- + y : ndarray + Parameter y + """ + return self.delegate.predict(X) + + @available_if(lambda self: hasattr(self.delegate, "score")) + @deprecated("Testing a deprecated delegated method") + def score(self, X): + """This is available only if delegate has score. + + Parameters + --------- + y : ndarray + Parameter y + """ + + @available_if(lambda self: hasattr(self.delegate, "predict_proba")) + def predict_proba(self, X): + """This is available only if delegate has predict_proba. + + Parameters + --------- + X : ndarray + Parameter X + """ + return X + + @deprecated("Testing deprecated function with wrong params") + def fit(self, X, y): + """Incorrect docstring but should not be tested""" + + +def test_check_docstring_parameters(): + pytest.importorskip( + "numpydoc", + reason="numpydoc is required to test the docstrings", + minversion="1.2.0", + ) + + incorrect = check_docstring_parameters(f_ok) + assert incorrect == [] + incorrect = check_docstring_parameters(f_ok, ignore=["b"]) + assert incorrect == [] + incorrect = check_docstring_parameters(f_missing, ignore=["b"]) + assert incorrect == [] + with pytest.raises(RuntimeError, match="Unknown section Results"): + check_docstring_parameters(f_bad_sections) + with pytest.raises(RuntimeError, match="Unknown section Parameter"): + check_docstring_parameters(Klass.f_bad_sections) + + incorrect = check_docstring_parameters(f_check_param_definition) + mock_meta = MockMetaEstimator(delegate=MockEst()) + mock_meta_name = mock_meta.__class__.__name__ + assert incorrect == [ + ( + "sklearn.utils.tests.test_testing.f_check_param_definition There " + "was no space between the param name and colon ('a: int')" + ), + ( + "sklearn.utils.tests.test_testing.f_check_param_definition There " + "was no space between the param name and colon ('b:')" + ), + ( + "sklearn.utils.tests.test_testing.f_check_param_definition There " + "was no space between the param name and colon ('d:int')" + ), + ] + + messages = [ + [ + "In function: sklearn.utils.tests.test_testing.f_bad_order", + ( + "There's a parameter name mismatch in function docstring w.r.t." + " function signature, at index 0 diff: 'b' != 'a'" + ), + "Full diff:", + "- ['b', 'a']", + "+ ['a', 'b']", + ], + [ + "In function: " + + "sklearn.utils.tests.test_testing.f_too_many_param_docstring", + ( + "Parameters in function docstring have more items w.r.t. function" + " signature, first extra item: c" + ), + "Full diff:", + "- ['a', 'b']", + "+ ['a', 'b', 'c']", + "? +++++", + ], + [ + "In function: sklearn.utils.tests.test_testing.f_missing", + ( + "Parameters in function docstring have less items w.r.t. function" + " signature, first missing item: b" + ), + "Full diff:", + "- ['a', 'b']", + "+ ['a']", + ], + [ + "In function: sklearn.utils.tests.test_testing.Klass.f_missing", + ( + "Parameters in function docstring have less items w.r.t. function" + " signature, first missing item: X" + ), + "Full diff:", + "- ['X', 'y']", + "+ []", + ], + [ + "In function: " + + f"sklearn.utils.tests.test_testing.{mock_meta_name}.predict", + ( + "There's a parameter name mismatch in function docstring w.r.t." + " function signature, at index 0 diff: 'X' != 'y'" + ), + "Full diff:", + "- ['X']", + "? ^", + "+ ['y']", + "? ^", + ], + [ + "In function: " + + f"sklearn.utils.tests.test_testing.{mock_meta_name}." + + "predict_proba", + "potentially wrong underline length... ", + "Parameters ", + "--------- in ", + ], + [ + "In function: " + + f"sklearn.utils.tests.test_testing.{mock_meta_name}.score", + "potentially wrong underline length... ", + "Parameters ", + "--------- in ", + ], + [ + "In function: " + f"sklearn.utils.tests.test_testing.{mock_meta_name}.fit", + ( + "Parameters in function docstring have less items w.r.t. function" + " signature, first missing item: X" + ), + "Full diff:", + "- ['X', 'y']", + "+ []", + ], + ] + + for msg, f in zip( + messages, + [ + f_bad_order, + f_too_many_param_docstring, + f_missing, + Klass.f_missing, + mock_meta.predict, + mock_meta.predict_proba, + mock_meta.score, + mock_meta.fit, + ], + ): + incorrect = check_docstring_parameters(f) + assert msg == incorrect, '\n"%s"\n not in \n"%s"' % (msg, incorrect) + + +class RegistrationCounter: + def __init__(self): + self.nb_calls = 0 + + def __call__(self, to_register_func): + self.nb_calls += 1 + assert to_register_func.func is _delete_folder + + +def check_memmap(input_array, mmap_data, mmap_mode="r"): + assert isinstance(mmap_data, np.memmap) + writeable = mmap_mode != "r" + assert mmap_data.flags.writeable is writeable + np.testing.assert_array_equal(input_array, mmap_data) + + +def test_tempmemmap(monkeypatch): + registration_counter = RegistrationCounter() + monkeypatch.setattr(atexit, "register", registration_counter) + + input_array = np.ones(3) + with TempMemmap(input_array) as data: + check_memmap(input_array, data) + temp_folder = os.path.dirname(data.filename) + if os.name != "nt": + assert not os.path.exists(temp_folder) + assert registration_counter.nb_calls == 1 + + mmap_mode = "r+" + with TempMemmap(input_array, mmap_mode=mmap_mode) as data: + check_memmap(input_array, data, mmap_mode=mmap_mode) + temp_folder = os.path.dirname(data.filename) + if os.name != "nt": + assert not os.path.exists(temp_folder) + assert registration_counter.nb_calls == 2 + + +@pytest.mark.xfail(_IS_WASM, reason="memmap not fully supported") +def test_create_memmap_backed_data(monkeypatch): + registration_counter = RegistrationCounter() + monkeypatch.setattr(atexit, "register", registration_counter) + + input_array = np.ones(3) + data = create_memmap_backed_data(input_array) + check_memmap(input_array, data) + assert registration_counter.nb_calls == 1 + + data, folder = create_memmap_backed_data(input_array, return_folder=True) + check_memmap(input_array, data) + assert folder == os.path.dirname(data.filename) + assert registration_counter.nb_calls == 2 + + mmap_mode = "r+" + data = create_memmap_backed_data(input_array, mmap_mode=mmap_mode) + check_memmap(input_array, data, mmap_mode) + assert registration_counter.nb_calls == 3 + + input_list = [input_array, input_array + 1, input_array + 2] + mmap_data_list = create_memmap_backed_data(input_list) + for input_array, data in zip(input_list, mmap_data_list): + check_memmap(input_array, data) + assert registration_counter.nb_calls == 4 + + output_data, other = create_memmap_backed_data([input_array, "not-an-array"]) + check_memmap(input_array, output_data) + assert other == "not-an-array" + + +@pytest.mark.parametrize( + "constructor_name, container_type", + [ + ("list", list), + ("tuple", tuple), + ("array", np.ndarray), + ("sparse", sparse.csr_matrix), + # using `zip` will only keep the available sparse containers + # depending of the installed SciPy version + *zip(["sparse_csr", "sparse_csr_array"], CSR_CONTAINERS), + *zip(["sparse_csc", "sparse_csc_array"], CSC_CONTAINERS), + ("dataframe", lambda: pytest.importorskip("pandas").DataFrame), + ("series", lambda: pytest.importorskip("pandas").Series), + ("index", lambda: pytest.importorskip("pandas").Index), + ("slice", slice), + ], +) +@pytest.mark.parametrize( + "dtype, superdtype", + [ + (np.int32, np.integer), + (np.int64, np.integer), + (np.float32, np.floating), + (np.float64, np.floating), + ], +) +def test_convert_container( + constructor_name, + container_type, + dtype, + superdtype, +): + """Check that we convert the container to the right type of array with the + right data type.""" + if constructor_name in ("dataframe", "series", "index"): + # delay the import of pandas within the function to only skip this test + # instead of the whole file + container_type = container_type() + container = [0, 1] + + container_converted = _convert_container( + container, + constructor_name, + dtype=dtype, + ) + assert isinstance(container_converted, container_type) + + if constructor_name in ("list", "tuple", "index"): + # list and tuple will use Python class dtype: int, float + # pandas index will always use high precision: np.int64 and np.float64 + assert np.issubdtype(type(container_converted[0]), superdtype) + elif hasattr(container_converted, "dtype"): + assert container_converted.dtype == dtype + elif hasattr(container_converted, "dtypes"): + assert container_converted.dtypes[0] == dtype + + +def test_convert_container_categories_pandas(): + pytest.importorskip("pandas") + df = _convert_container( + [["x"]], "dataframe", ["A"], categorical_feature_names=["A"] + ) + assert df.dtypes.iloc[0] == "category" + + +def test_convert_container_categories_polars(): + pl = pytest.importorskip("polars") + df = _convert_container([["x"]], "polars", ["A"], categorical_feature_names=["A"]) + assert df.schema["A"] == pl.Categorical() + + +def test_convert_container_categories_pyarrow(): + pa = pytest.importorskip("pyarrow") + df = _convert_container([["x"]], "pyarrow", ["A"], categorical_feature_names=["A"]) + assert type(df.schema[0].type) is pa.DictionaryType + + +@pytest.mark.skipif( + sp_version >= parse_version("1.8"), + reason="sparse arrays are available as of scipy 1.8.0", +) +@pytest.mark.parametrize("constructor_name", ["sparse_csr_array", "sparse_csc_array"]) +@pytest.mark.parametrize("dtype", [np.int32, np.int64, np.float32, np.float64]) +def test_convert_container_raise_when_sparray_not_available(constructor_name, dtype): + """Check that if we convert to sparse array but sparse array are not supported + (scipy<1.8.0), we should raise an explicit error.""" + container = [0, 1] + + with pytest.raises( + ValueError, + match=f"only available with scipy>=1.8.0, got {sp_version}", + ): + _convert_container(container, constructor_name, dtype=dtype) + + +def test_raises(): + # Tests for the raises context manager + + # Proper type, no match + with raises(TypeError): + raise TypeError() + + # Proper type, proper match + with raises(TypeError, match="how are you") as cm: + raise TypeError("hello how are you") + assert cm.raised_and_matched + + # Proper type, proper match with multiple patterns + with raises(TypeError, match=["not this one", "how are you"]) as cm: + raise TypeError("hello how are you") + assert cm.raised_and_matched + + # bad type, no match + with pytest.raises(ValueError, match="this will be raised"): + with raises(TypeError) as cm: + raise ValueError("this will be raised") + assert not cm.raised_and_matched + + # Bad type, no match, with a err_msg + with pytest.raises(AssertionError, match="the failure message"): + with raises(TypeError, err_msg="the failure message") as cm: + raise ValueError() + assert not cm.raised_and_matched + + # bad type, with match (is ignored anyway) + with pytest.raises(ValueError, match="this will be raised"): + with raises(TypeError, match="this is ignored") as cm: + raise ValueError("this will be raised") + assert not cm.raised_and_matched + + # proper type but bad match + with pytest.raises( + AssertionError, match="should contain one of the following patterns" + ): + with raises(TypeError, match="hello") as cm: + raise TypeError("Bad message") + assert not cm.raised_and_matched + + # proper type but bad match, with err_msg + with pytest.raises(AssertionError, match="the failure message"): + with raises(TypeError, match="hello", err_msg="the failure message") as cm: + raise TypeError("Bad message") + assert not cm.raised_and_matched + + # no raise with default may_pass=False + with pytest.raises(AssertionError, match="Did not raise"): + with raises(TypeError) as cm: + pass + assert not cm.raised_and_matched + + # no raise with may_pass=True + with raises(TypeError, match="hello", may_pass=True) as cm: + pass # still OK + assert not cm.raised_and_matched + + # Multiple exception types: + with raises((TypeError, ValueError)): + raise TypeError() + with raises((TypeError, ValueError)): + raise ValueError() + with pytest.raises(AssertionError): + with raises((TypeError, ValueError)): + pass + + +def test_float32_aware_assert_allclose(): + # The relative tolerance for float32 inputs is 1e-4 + assert_allclose(np.array([1.0 + 2e-5], dtype=np.float32), 1.0) + with pytest.raises(AssertionError): + assert_allclose(np.array([1.0 + 2e-4], dtype=np.float32), 1.0) + + # The relative tolerance for other inputs is left to 1e-7 as in + # the original numpy version. + assert_allclose(np.array([1.0 + 2e-8], dtype=np.float64), 1.0) + with pytest.raises(AssertionError): + assert_allclose(np.array([1.0 + 2e-7], dtype=np.float64), 1.0) + + # atol is left to 0.0 by default, even for float32 + with pytest.raises(AssertionError): + assert_allclose(np.array([1e-5], dtype=np.float32), 0.0) + assert_allclose(np.array([1e-5], dtype=np.float32), 0.0, atol=2e-5) + + +@pytest.mark.xfail(_IS_WASM, reason="cannot start subprocess") +def test_assert_run_python_script_without_output(): + code = "x = 1" + assert_run_python_script_without_output(code) + + code = "print('something to stdout')" + with pytest.raises(AssertionError, match="Expected no output"): + assert_run_python_script_without_output(code) + + code = "print('something to stdout')" + with pytest.raises( + AssertionError, + match="output was not supposed to match.+got.+something to stdout", + ): + assert_run_python_script_without_output(code, pattern="to.+stdout") + + code = "\n".join(["import sys", "print('something to stderr', file=sys.stderr)"]) + with pytest.raises( + AssertionError, + match="output was not supposed to match.+got.+something to stderr", + ): + assert_run_python_script_without_output(code, pattern="to.+stderr") + + +@pytest.mark.parametrize( + "constructor_name", + [ + "sparse_csr", + "sparse_csc", + pytest.param( + "sparse_csr_array", + marks=pytest.mark.skipif( + sp_version < parse_version("1.8"), + reason="sparse arrays are available as of scipy 1.8.0", + ), + ), + pytest.param( + "sparse_csc_array", + marks=pytest.mark.skipif( + sp_version < parse_version("1.8"), + reason="sparse arrays are available as of scipy 1.8.0", + ), + ), + ], +) +def test_convert_container_sparse_to_sparse(constructor_name): + """Non-regression test to check that we can still convert a sparse container + from a given format to another format. + """ + X_sparse = sparse.random(10, 10, density=0.1, format="csr") + _convert_container(X_sparse, constructor_name) + + +def check_warnings_as_errors(warning_info, warnings_as_errors): + if warning_info.action == "error" and warnings_as_errors: + with pytest.raises(warning_info.category, match=warning_info.message): + warnings.warn( + message=warning_info.message, + category=warning_info.category, + ) + if warning_info.action == "ignore": + with warnings.catch_warnings(record=True) as record: + message = warning_info.message + # Special treatment when regex is used + if "Pyarrow" in message: + message = "\nPyarrow will become a required dependency" + + warnings.warn( + message=message, + category=warning_info.category, + ) + assert len(record) == 0 if warnings_as_errors else 1 + if record: + assert str(record[0].message) == message + assert record[0].category == warning_info.category + + +@pytest.mark.parametrize("warning_info", _get_warnings_filters_info_list()) +def test_sklearn_warnings_as_errors(warning_info): + warnings_as_errors = os.environ.get("SKLEARN_WARNINGS_AS_ERRORS", "0") != "0" + check_warnings_as_errors(warning_info, warnings_as_errors=warnings_as_errors) + + +@pytest.mark.parametrize("warning_info", _get_warnings_filters_info_list()) +def test_turn_warnings_into_errors(warning_info): + with warnings.catch_warnings(): + turn_warnings_into_errors() + check_warnings_as_errors(warning_info, warnings_as_errors=True) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_utils.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..20b3fdc600a8ca57fb91ed99211e41ae993dff37 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_utils.py @@ -0,0 +1,866 @@ +import string +import timeit +import warnings +from copy import copy +from itertools import chain +from unittest import SkipTest + +import numpy as np +import pytest + +from sklearn import config_context +from sklearn.externals._packaging.version import parse as parse_version +from sklearn.utils import ( + _approximate_mode, + _determine_key_type, + _get_column_indices, + _is_polars_df, + _message_with_time, + _print_elapsed_time, + _safe_assign, + _safe_indexing, + _to_object_array, + check_random_state, + column_or_1d, + deprecated, + gen_even_slices, + get_chunk_n_rows, + is_scalar_nan, + resample, + safe_mask, + shuffle, +) +from sklearn.utils._mocking import MockDataFrame +from sklearn.utils._testing import ( + _convert_container, + assert_allclose_dense_sparse, + assert_array_equal, + assert_no_warnings, +) +from sklearn.utils.fixes import CSC_CONTAINERS, CSR_CONTAINERS + +# toy array +X_toy = np.arange(9).reshape((3, 3)) + + +def test_make_rng(): + # Check the check_random_state utility function behavior + assert check_random_state(None) is np.random.mtrand._rand + assert check_random_state(np.random) is np.random.mtrand._rand + + rng_42 = np.random.RandomState(42) + assert check_random_state(42).randint(100) == rng_42.randint(100) + + rng_42 = np.random.RandomState(42) + assert check_random_state(rng_42) is rng_42 + + rng_42 = np.random.RandomState(42) + assert check_random_state(43).randint(100) != rng_42.randint(100) + + with pytest.raises(ValueError): + check_random_state("some invalid seed") + + +def test_deprecated(): + # Test whether the deprecated decorator issues appropriate warnings + # Copied almost verbatim from https://docs.python.org/library/warnings.html + + # First a function... + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + @deprecated() + def ham(): + return "spam" + + spam = ham() + + assert spam == "spam" # function must remain usable + + assert len(w) == 1 + assert issubclass(w[0].category, FutureWarning) + assert "deprecated" in str(w[0].message).lower() + + # ... then a class. + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + @deprecated("don't use this") + class Ham: + SPAM = 1 + + ham = Ham() + + assert hasattr(ham, "SPAM") + + assert len(w) == 1 + assert issubclass(w[0].category, FutureWarning) + assert "deprecated" in str(w[0].message).lower() + + +def test_resample(): + # Border case not worth mentioning in doctests + assert resample() is None + + # Check that invalid arguments yield ValueError + with pytest.raises(ValueError): + resample([0], [0, 1]) + with pytest.raises(ValueError): + resample([0, 1], [0, 1], replace=False, n_samples=3) + + # Issue:6581, n_samples can be more when replace is True (default). + assert len(resample([1, 2], n_samples=5)) == 5 + + +def test_resample_stratified(): + # Make sure resample can stratify + rng = np.random.RandomState(0) + n_samples = 100 + p = 0.9 + X = rng.normal(size=(n_samples, 1)) + y = rng.binomial(1, p, size=n_samples) + + _, y_not_stratified = resample(X, y, n_samples=10, random_state=0, stratify=None) + assert np.all(y_not_stratified == 1) + + _, y_stratified = resample(X, y, n_samples=10, random_state=0, stratify=y) + assert not np.all(y_stratified == 1) + assert np.sum(y_stratified) == 9 # all 1s, one 0 + + +def test_resample_stratified_replace(): + # Make sure stratified resampling supports the replace parameter + rng = np.random.RandomState(0) + n_samples = 100 + X = rng.normal(size=(n_samples, 1)) + y = rng.randint(0, 2, size=n_samples) + + X_replace, _ = resample( + X, y, replace=True, n_samples=50, random_state=rng, stratify=y + ) + X_no_replace, _ = resample( + X, y, replace=False, n_samples=50, random_state=rng, stratify=y + ) + assert np.unique(X_replace).shape[0] < 50 + assert np.unique(X_no_replace).shape[0] == 50 + + # make sure n_samples can be greater than X.shape[0] if we sample with + # replacement + X_replace, _ = resample( + X, y, replace=True, n_samples=1000, random_state=rng, stratify=y + ) + assert X_replace.shape[0] == 1000 + assert np.unique(X_replace).shape[0] == 100 + + +def test_resample_stratify_2dy(): + # Make sure y can be 2d when stratifying + rng = np.random.RandomState(0) + n_samples = 100 + X = rng.normal(size=(n_samples, 1)) + y = rng.randint(0, 2, size=(n_samples, 2)) + X, y = resample(X, y, n_samples=50, random_state=rng, stratify=y) + assert y.ndim == 2 + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_resample_stratify_sparse_error(csr_container): + # resample must be ndarray + rng = np.random.RandomState(0) + n_samples = 100 + X = rng.normal(size=(n_samples, 2)) + y = rng.randint(0, 2, size=n_samples) + stratify = csr_container(y.reshape(-1, 1)) + with pytest.raises(TypeError, match="Sparse data was passed"): + X, y = resample(X, y, n_samples=50, random_state=rng, stratify=stratify) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_safe_mask(csr_container): + random_state = check_random_state(0) + X = random_state.rand(5, 4) + X_csr = csr_container(X) + mask = [False, False, True, True, True] + + mask = safe_mask(X, mask) + assert X[mask].shape[0] == 3 + + mask = safe_mask(X_csr, mask) + assert X_csr[mask].shape[0] == 3 + + +def test_column_or_1d(): + EXAMPLES = [ + ("binary", ["spam", "egg", "spam"]), + ("binary", [0, 1, 0, 1]), + ("continuous", np.arange(10) / 20.0), + ("multiclass", [1, 2, 3]), + ("multiclass", [0, 1, 2, 2, 0]), + ("multiclass", [[1], [2], [3]]), + ("multilabel-indicator", [[0, 1, 0], [0, 0, 1]]), + ("multiclass-multioutput", [[1, 2, 3]]), + ("multiclass-multioutput", [[1, 1], [2, 2], [3, 1]]), + ("multiclass-multioutput", [[5, 1], [4, 2], [3, 1]]), + ("multiclass-multioutput", [[1, 2, 3]]), + ("continuous-multioutput", np.arange(30).reshape((-1, 3))), + ] + + for y_type, y in EXAMPLES: + if y_type in ["binary", "multiclass", "continuous"]: + assert_array_equal(column_or_1d(y), np.ravel(y)) + else: + with pytest.raises(ValueError): + column_or_1d(y) + + +@pytest.mark.parametrize( + "key, dtype", + [ + (0, "int"), + ("0", "str"), + (True, "bool"), + (np.bool_(True), "bool"), + ([0, 1, 2], "int"), + (["0", "1", "2"], "str"), + ((0, 1, 2), "int"), + (("0", "1", "2"), "str"), + (slice(None, None), None), + (slice(0, 2), "int"), + (np.array([0, 1, 2], dtype=np.int32), "int"), + (np.array([0, 1, 2], dtype=np.int64), "int"), + (np.array([0, 1, 2], dtype=np.uint8), "int"), + ([True, False], "bool"), + ((True, False), "bool"), + (np.array([True, False]), "bool"), + ("col_0", "str"), + (["col_0", "col_1", "col_2"], "str"), + (("col_0", "col_1", "col_2"), "str"), + (slice("begin", "end"), "str"), + (np.array(["col_0", "col_1", "col_2"]), "str"), + (np.array(["col_0", "col_1", "col_2"], dtype=object), "str"), + ], +) +def test_determine_key_type(key, dtype): + assert _determine_key_type(key) == dtype + + +def test_determine_key_type_error(): + with pytest.raises(ValueError, match="No valid specification of the"): + _determine_key_type(1.0) + + +def test_determine_key_type_slice_error(): + with pytest.raises(TypeError, match="Only array-like or scalar are"): + _determine_key_type(slice(0, 2, 1), accept_slice=False) + + +@pytest.mark.parametrize("array_type", ["list", "array", "sparse", "dataframe"]) +@pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series", "slice"]) +def test_safe_indexing_2d_container_axis_0(array_type, indices_type): + indices = [1, 2] + if indices_type == "slice" and isinstance(indices[1], int): + indices[1] += 1 + array = _convert_container([[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type) + indices = _convert_container(indices, indices_type) + subset = _safe_indexing(array, indices, axis=0) + assert_allclose_dense_sparse( + subset, _convert_container([[4, 5, 6], [7, 8, 9]], array_type) + ) + + +@pytest.mark.parametrize("array_type", ["list", "array", "series"]) +@pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series", "slice"]) +def test_safe_indexing_1d_container(array_type, indices_type): + indices = [1, 2] + if indices_type == "slice" and isinstance(indices[1], int): + indices[1] += 1 + array = _convert_container([1, 2, 3, 4, 5, 6, 7, 8, 9], array_type) + indices = _convert_container(indices, indices_type) + subset = _safe_indexing(array, indices, axis=0) + assert_allclose_dense_sparse(subset, _convert_container([2, 3], array_type)) + + +@pytest.mark.parametrize("array_type", ["array", "sparse", "dataframe"]) +@pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series", "slice"]) +@pytest.mark.parametrize("indices", [[1, 2], ["col_1", "col_2"]]) +def test_safe_indexing_2d_container_axis_1(array_type, indices_type, indices): + # validation of the indices + # we make a copy because indices is mutable and shared between tests + indices_converted = copy(indices) + if indices_type == "slice" and isinstance(indices[1], int): + indices_converted[1] += 1 + + columns_name = ["col_0", "col_1", "col_2"] + array = _convert_container( + [[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type, columns_name + ) + indices_converted = _convert_container(indices_converted, indices_type) + + if isinstance(indices[0], str) and array_type != "dataframe": + err_msg = ( + "Specifying the columns using strings is only supported for dataframes" + ) + with pytest.raises(ValueError, match=err_msg): + _safe_indexing(array, indices_converted, axis=1) + else: + subset = _safe_indexing(array, indices_converted, axis=1) + assert_allclose_dense_sparse( + subset, _convert_container([[2, 3], [5, 6], [8, 9]], array_type) + ) + + +@pytest.mark.parametrize("array_read_only", [True, False]) +@pytest.mark.parametrize("indices_read_only", [True, False]) +@pytest.mark.parametrize("array_type", ["array", "sparse", "dataframe"]) +@pytest.mark.parametrize("indices_type", ["array", "series"]) +@pytest.mark.parametrize( + "axis, expected_array", [(0, [[4, 5, 6], [7, 8, 9]]), (1, [[2, 3], [5, 6], [8, 9]])] +) +def test_safe_indexing_2d_read_only_axis_1( + array_read_only, indices_read_only, array_type, indices_type, axis, expected_array +): + array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + if array_read_only: + array.setflags(write=False) + array = _convert_container(array, array_type) + indices = np.array([1, 2]) + if indices_read_only: + indices.setflags(write=False) + indices = _convert_container(indices, indices_type) + subset = _safe_indexing(array, indices, axis=axis) + assert_allclose_dense_sparse(subset, _convert_container(expected_array, array_type)) + + +@pytest.mark.parametrize("array_type", ["list", "array", "series"]) +@pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series"]) +def test_safe_indexing_1d_container_mask(array_type, indices_type): + indices = [False] + [True] * 2 + [False] * 6 + array = _convert_container([1, 2, 3, 4, 5, 6, 7, 8, 9], array_type) + indices = _convert_container(indices, indices_type) + subset = _safe_indexing(array, indices, axis=0) + assert_allclose_dense_sparse(subset, _convert_container([2, 3], array_type)) + + +@pytest.mark.parametrize("array_type", ["array", "sparse", "dataframe"]) +@pytest.mark.parametrize("indices_type", ["list", "tuple", "array", "series"]) +@pytest.mark.parametrize( + "axis, expected_subset", + [(0, [[4, 5, 6], [7, 8, 9]]), (1, [[2, 3], [5, 6], [8, 9]])], +) +def test_safe_indexing_2d_mask(array_type, indices_type, axis, expected_subset): + columns_name = ["col_0", "col_1", "col_2"] + array = _convert_container( + [[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type, columns_name + ) + indices = [False, True, True] + indices = _convert_container(indices, indices_type) + + subset = _safe_indexing(array, indices, axis=axis) + assert_allclose_dense_sparse( + subset, _convert_container(expected_subset, array_type) + ) + + +@pytest.mark.parametrize( + "array_type, expected_output_type", + [ + ("list", "list"), + ("array", "array"), + ("sparse", "sparse"), + ("dataframe", "series"), + ], +) +def test_safe_indexing_2d_scalar_axis_0(array_type, expected_output_type): + array = _convert_container([[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type) + indices = 2 + subset = _safe_indexing(array, indices, axis=0) + expected_array = _convert_container([7, 8, 9], expected_output_type) + assert_allclose_dense_sparse(subset, expected_array) + + +@pytest.mark.parametrize("array_type", ["list", "array", "series"]) +def test_safe_indexing_1d_scalar(array_type): + array = _convert_container([1, 2, 3, 4, 5, 6, 7, 8, 9], array_type) + indices = 2 + subset = _safe_indexing(array, indices, axis=0) + assert subset == 3 + + +@pytest.mark.parametrize( + "array_type, expected_output_type", + [("array", "array"), ("sparse", "sparse"), ("dataframe", "series")], +) +@pytest.mark.parametrize("indices", [2, "col_2"]) +def test_safe_indexing_2d_scalar_axis_1(array_type, expected_output_type, indices): + columns_name = ["col_0", "col_1", "col_2"] + array = _convert_container( + [[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type, columns_name + ) + + if isinstance(indices, str) and array_type != "dataframe": + err_msg = ( + "Specifying the columns using strings is only supported for dataframes" + ) + with pytest.raises(ValueError, match=err_msg): + _safe_indexing(array, indices, axis=1) + else: + subset = _safe_indexing(array, indices, axis=1) + expected_output = [3, 6, 9] + if expected_output_type == "sparse": + # sparse matrix are keeping the 2D shape + expected_output = [[3], [6], [9]] + expected_array = _convert_container(expected_output, expected_output_type) + assert_allclose_dense_sparse(subset, expected_array) + + +@pytest.mark.parametrize("array_type", ["list", "array", "sparse"]) +def test_safe_indexing_None_axis_0(array_type): + X = _convert_container([[1, 2, 3], [4, 5, 6], [7, 8, 9]], array_type) + X_subset = _safe_indexing(X, None, axis=0) + assert_allclose_dense_sparse(X_subset, X) + + +def test_safe_indexing_pandas_no_matching_cols_error(): + pd = pytest.importorskip("pandas") + err_msg = "No valid specification of the columns." + X = pd.DataFrame(X_toy) + with pytest.raises(ValueError, match=err_msg): + _safe_indexing(X, [1.0], axis=1) + + +@pytest.mark.parametrize("axis", [None, 3]) +def test_safe_indexing_error_axis(axis): + with pytest.raises(ValueError, match="'axis' should be either 0"): + _safe_indexing(X_toy, [0, 1], axis=axis) + + +@pytest.mark.parametrize("X_constructor", ["array", "series"]) +def test_safe_indexing_1d_array_error(X_constructor): + # check that we are raising an error if the array-like passed is 1D and + # we try to index on the 2nd dimension + X = list(range(5)) + if X_constructor == "array": + X_constructor = np.asarray(X) + elif X_constructor == "series": + pd = pytest.importorskip("pandas") + X_constructor = pd.Series(X) + + err_msg = "'X' should be a 2D NumPy array, 2D sparse matrix or pandas" + with pytest.raises(ValueError, match=err_msg): + _safe_indexing(X_constructor, [0, 1], axis=1) + + +def test_safe_indexing_container_axis_0_unsupported_type(): + indices = ["col_1", "col_2"] + array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + err_msg = "String indexing is not supported with 'axis=0'" + with pytest.raises(ValueError, match=err_msg): + _safe_indexing(array, indices, axis=0) + + +def test_safe_indexing_pandas_no_settingwithcopy_warning(): + # Using safe_indexing with an array-like indexer gives a copy of the + # DataFrame -> ensure it doesn't raise a warning if modified + pd = pytest.importorskip("pandas") + + pd_version = parse_version(pd.__version__) + pd_base_version = parse_version(pd_version.base_version) + + if pd_base_version >= parse_version("3"): + raise SkipTest("SettingWithCopyWarning has been removed in pandas 3.0.0.dev") + + X = pd.DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]}) + subset = _safe_indexing(X, [0, 1], axis=0) + if hasattr(pd.errors, "SettingWithCopyWarning"): + SettingWithCopyWarning = pd.errors.SettingWithCopyWarning + else: + # backward compatibility for pandas < 1.5 + SettingWithCopyWarning = pd.core.common.SettingWithCopyWarning + with warnings.catch_warnings(): + warnings.simplefilter("error", SettingWithCopyWarning) + subset.iloc[0, 0] = 10 + # The original dataframe is unaffected by the assignment on the subset: + assert X.iloc[0, 0] == 1 + + +@pytest.mark.parametrize("indices", [0, [0, 1], slice(0, 2), np.array([0, 1])]) +def test_safe_indexing_list_axis_1_unsupported(indices): + """Check that we raise a ValueError when axis=1 with input as list.""" + X = [[1, 2], [4, 5], [7, 8]] + err_msg = "axis=1 is not supported for lists" + with pytest.raises(ValueError, match=err_msg): + _safe_indexing(X, indices, axis=1) + + +@pytest.mark.parametrize( + "key, err_msg", + [ + (10, r"all features must be in \[0, 2\]"), + ("whatever", "A given column is not a column of the dataframe"), + (object(), "No valid specification of the columns"), + ], +) +def test_get_column_indices_error(key, err_msg): + pd = pytest.importorskip("pandas") + X_df = pd.DataFrame(X_toy, columns=["col_0", "col_1", "col_2"]) + + with pytest.raises(ValueError, match=err_msg): + _get_column_indices(X_df, key) + + +@pytest.mark.parametrize( + "key", [["col1"], ["col2"], ["col1", "col2"], ["col1", "col3"], ["col2", "col3"]] +) +def test_get_column_indices_pandas_nonunique_columns_error(key): + pd = pytest.importorskip("pandas") + toy = np.zeros((1, 5), dtype=int) + columns = ["col1", "col1", "col2", "col3", "col2"] + X = pd.DataFrame(toy, columns=columns) + + err_msg = "Selected columns, {}, are not unique in dataframe".format(key) + with pytest.raises(ValueError) as exc_info: + _get_column_indices(X, key) + assert str(exc_info.value) == err_msg + + +def test_shuffle_on_ndim_equals_three(): + def to_tuple(A): # to make the inner arrays hashable + return tuple(tuple(tuple(C) for C in B) for B in A) + + A = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # A.shape = (2,2,2) + S = set(to_tuple(A)) + shuffle(A) # shouldn't raise a ValueError for dim = 3 + assert set(to_tuple(A)) == S + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_shuffle_dont_convert_to_array(csc_container): + # Check that shuffle does not try to convert to numpy arrays with float + # dtypes can let any indexable datastructure pass-through. + a = ["a", "b", "c"] + b = np.array(["a", "b", "c"], dtype=object) + c = [1, 2, 3] + d = MockDataFrame(np.array([["a", 0], ["b", 1], ["c", 2]], dtype=object)) + e = csc_container(np.arange(6).reshape(3, 2)) + a_s, b_s, c_s, d_s, e_s = shuffle(a, b, c, d, e, random_state=0) + + assert a_s == ["c", "b", "a"] + assert type(a_s) == list # noqa: E721 + + assert_array_equal(b_s, ["c", "b", "a"]) + assert b_s.dtype == object + + assert c_s == [3, 2, 1] + assert type(c_s) == list # noqa: E721 + + assert_array_equal(d_s, np.array([["c", 2], ["b", 1], ["a", 0]], dtype=object)) + assert type(d_s) == MockDataFrame # noqa: E721 + + assert_array_equal(e_s.toarray(), np.array([[4, 5], [2, 3], [0, 1]])) + + +def test_gen_even_slices(): + # check that gen_even_slices contains all samples + some_range = range(10) + joined_range = list(chain(*[some_range[slice] for slice in gen_even_slices(10, 3)])) + assert_array_equal(some_range, joined_range) + + +@pytest.mark.parametrize( + ("row_bytes", "max_n_rows", "working_memory", "expected"), + [ + (1024, None, 1, 1024), + (1024, None, 0.99999999, 1023), + (1023, None, 1, 1025), + (1025, None, 1, 1023), + (1024, None, 2, 2048), + (1024, 7, 1, 7), + (1024 * 1024, None, 1, 1), + ], +) +def test_get_chunk_n_rows(row_bytes, max_n_rows, working_memory, expected): + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + 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 warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + actual = get_chunk_n_rows(row_bytes=row_bytes, max_n_rows=max_n_rows) + assert actual == expected + assert type(actual) is type(expected) + + +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) + + +@pytest.mark.parametrize( + ["source", "message", "is_long"], + [ + ("ABC", string.ascii_lowercase, False), + ("ABCDEF", string.ascii_lowercase, False), + ("ABC", string.ascii_lowercase * 3, True), + ("ABC" * 10, string.ascii_lowercase, True), + ("ABC", string.ascii_lowercase + "\u1048", False), + ], +) +@pytest.mark.parametrize( + ["time", "time_str"], + [ + (0.2, " 0.2s"), + (20, " 20.0s"), + (2000, "33.3min"), + (20000, "333.3min"), + ], +) +def test_message_with_time(source, message, is_long, time, time_str): + out = _message_with_time(source, message, time) + if is_long: + assert len(out) > 70 + else: + assert len(out) == 70 + + assert out.startswith("[" + source + "] ") + out = out[len(source) + 3 :] + + assert out.endswith(time_str) + out = out[: -len(time_str)] + assert out.endswith(", total=") + out = out[: -len(", total=")] + assert out.endswith(message) + out = out[: -len(message)] + assert out.endswith(" ") + out = out[:-1] + + if is_long: + assert not out + else: + assert list(set(out)) == ["."] + + +@pytest.mark.parametrize( + ["message", "expected"], + [ + ("hello", _message_with_time("ABC", "hello", 0.1) + "\n"), + ("", _message_with_time("ABC", "", 0.1) + "\n"), + (None, ""), + ], +) +def test_print_elapsed_time(message, expected, capsys, monkeypatch): + monkeypatch.setattr(timeit, "default_timer", lambda: 0) + with _print_elapsed_time("ABC", message): + monkeypatch.setattr(timeit, "default_timer", lambda: 0.1) + assert capsys.readouterr().out == expected + + +@pytest.mark.parametrize( + "value, result", + [ + (float("nan"), True), + (np.nan, True), + (float(np.nan), True), + (np.float32(np.nan), True), + (np.float64(np.nan), True), + (0, False), + (0.0, False), + (None, False), + ("", False), + ("nan", False), + ([np.nan], False), + (9867966753463435747313673, False), # Python int that overflows with C type + ], +) +def test_is_scalar_nan(value, result): + assert is_scalar_nan(value) is result + # make sure that we are returning a Python bool + assert isinstance(is_scalar_nan(value), bool) + + +def test_approximate_mode(): + """Make sure sklearn.utils._approximate_mode returns valid + results for cases where "class_counts * n_draws" is enough + to overflow 32-bit signed integer. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/20774 + """ + X = np.array([99000, 1000], dtype=np.int32) + ret = _approximate_mode(class_counts=X, n_draws=25000, rng=0) + + # Draws 25% of the total population, so in this case a fair draw means: + # 25% * 99.000 = 24.750 + # 25% * 1.000 = 250 + assert_array_equal(ret, [24750, 250]) + + +def dummy_func(): + pass + + +def test_deprecation_joblib_api(tmpdir): + # Only parallel_backend and register_parallel_backend are not deprecated in + # sklearn.utils + from sklearn.utils import parallel_backend, register_parallel_backend + + assert_no_warnings(parallel_backend, "loky", None) + assert_no_warnings(register_parallel_backend, "failing", None) + + from sklearn.utils._joblib import joblib + + del joblib.parallel.BACKENDS["failing"] + + +@pytest.mark.parametrize("sequence", [[np.array(1), np.array(2)], [[1, 2], [3, 4]]]) +def test_to_object_array(sequence): + out = _to_object_array(sequence) + assert isinstance(out, np.ndarray) + assert out.dtype.kind == "O" + assert out.ndim == 1 + + +@pytest.mark.parametrize("array_type", ["array", "sparse", "dataframe"]) +def test_safe_assign(array_type): + """Check that `_safe_assign` works as expected.""" + rng = np.random.RandomState(0) + X_array = rng.randn(10, 5) + + row_indexer = [1, 2] + values = rng.randn(len(row_indexer), X_array.shape[1]) + X = _convert_container(X_array, array_type) + _safe_assign(X, values, row_indexer=row_indexer) + + assigned_portion = _safe_indexing(X, row_indexer, axis=0) + assert_allclose_dense_sparse( + assigned_portion, _convert_container(values, array_type) + ) + + column_indexer = [1, 2] + values = rng.randn(X_array.shape[0], len(column_indexer)) + X = _convert_container(X_array, array_type) + _safe_assign(X, values, column_indexer=column_indexer) + + assigned_portion = _safe_indexing(X, column_indexer, axis=1) + assert_allclose_dense_sparse( + assigned_portion, _convert_container(values, array_type) + ) + + row_indexer, column_indexer = None, None + values = rng.randn(*X.shape) + X = _convert_container(X_array, array_type) + _safe_assign(X, values, column_indexer=column_indexer) + + assert_allclose_dense_sparse(X, _convert_container(values, array_type)) + + +def test_get_column_indices_interchange(): + """Check _get_column_indices for edge cases with the interchange""" + pd = pytest.importorskip("pandas", minversion="1.5") + + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "b", "c"]) + + # Hide the fact that this is a pandas dataframe to trigger the dataframe protocol + # code path. + class MockDataFrame: + def __init__(self, df): + self._df = df + + def __getattr__(self, name): + return getattr(self._df, name) + + df_mocked = MockDataFrame(df) + + key_results = [ + (slice(1, None), [1, 2]), + (slice(None, 2), [0, 1]), + (slice(1, 2), [1]), + (["b", "c"], [1, 2]), + (slice("a", "b"), [0, 1]), + (slice("a", None), [0, 1, 2]), + (slice(None, "a"), [0]), + (["c", "a"], [2, 0]), + ([], []), + ] + for key, result in key_results: + assert _get_column_indices(df_mocked, key) == result + + msg = "A given column is not a column of the dataframe" + with pytest.raises(ValueError, match=msg): + _get_column_indices(df_mocked, ["not_a_column"]) + + msg = "key.step must be 1 or None" + with pytest.raises(NotImplementedError, match=msg): + _get_column_indices(df_mocked, slice("a", None, 2)) + + +def test_polars_indexing(): + """Check _safe_indexing for polars as expected.""" + pl = pytest.importorskip("polars", minversion="0.18.2") + df = pl.DataFrame( + {"a": [1, 2, 3, 4], "b": [4, 5, 6, 8], "c": [1, 4, 1, 10]}, orient="row" + ) + + from polars.testing import assert_frame_equal + + str_keys = [["b"], ["a", "b"], ["b", "a", "c"], ["c"], ["a"]] + + for key in str_keys: + out = _safe_indexing(df, key, axis=1) + assert_frame_equal(df[key], out) + + bool_keys = [([True, False, True], ["a", "c"]), ([False, False, True], ["c"])] + + for bool_key, str_key in bool_keys: + out = _safe_indexing(df, bool_key, axis=1) + assert_frame_equal(df[:, str_key], out) + + int_keys = [([0, 1], ["a", "b"]), ([2], ["c"])] + + for int_key, str_key in int_keys: + out = _safe_indexing(df, int_key, axis=1) + assert_frame_equal(df[:, str_key], out) + + axis_0_keys = [[0, 1], [1, 3], [3, 2]] + for key in axis_0_keys: + out = _safe_indexing(df, key, axis=0) + assert_frame_equal(df[key], out) + + +def test__is_polars_df(): + """Check that _is_polars_df return False for non-dataframe objects.""" + + class LooksLikePolars: + def __init__(self): + self.columns = ["a", "b"] + self.schema = ["a", "b"] + + assert not _is_polars_df(LooksLikePolars()) diff --git a/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_weight_vector.py b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_weight_vector.py new file mode 100644 index 0000000000000000000000000000000000000000..0b19792475e06369fb26e526e2644a3285f4223f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sklearn/utils/tests/test_weight_vector.py @@ -0,0 +1,25 @@ +import numpy as np +import pytest + +from sklearn.utils._weight_vector import ( + WeightVector32, + WeightVector64, +) + + +@pytest.mark.parametrize( + "dtype, WeightVector", + [ + (np.float32, WeightVector32), + (np.float64, WeightVector64), + ], +) +def test_type_invariance(dtype, WeightVector): + """Check the `dtype` consistency of `WeightVector`.""" + weights = np.random.rand(100).astype(dtype) + average_weights = np.random.rand(100).astype(dtype) + + weight_vector = WeightVector(weights, average_weights) + + assert np.asarray(weight_vector.w).dtype is np.dtype(dtype) + assert np.asarray(weight_vector.aw).dtype is np.dtype(dtype)