code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def 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)
Dat... | 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 f... | add_dummy_feature | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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(
... | Compute percentiles for dense matrices.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
The data used to scale along the features axis.
| _dense_fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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 mat... | 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 i... | _sparse_fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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 i... | 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... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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
... | Private function to transform a single feature. | _transform_col | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
def _check_inputs(self, X, in_fit, accept_sparse_negative=False, copy=False):
"""Check inputs before fit and transform."""
X = validate_data(
self,
X,
reset=in_fit,
accept_sparse="csc",
copy=copy,
dtype=FLOAT_DTYPES,
# o... | Check inputs before fit and transform. | _check_inputs | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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. ... | 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.
... | _transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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 ... | 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``. ... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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 i... | 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``. Ad... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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... | 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 robu... | quantile_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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 : nd... | 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_featur... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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_original = exp(X_trans)
else:
X_original = (X * lambda_ + 1) ** (1 / la... | Apply the inverse power transformation using the fitted lambdas.
The inverse of the Box-Cox transformation is given by::
if lambda_ == 0:
X_original = exp(X_trans)
else:
X_original = (X * lambda_ + 1) ** (1 / lambda_)
The inverse of the Yeo-John... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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... | Return inverse-transformed input x following Yeo-Johnson inverse
transform with parameter lambda.
| _yeo_johnson_inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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... | Return transformed input x following Yeo-Johnson transform with
parameter lambda.
| _yeo_johnson_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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 ... | 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.
| _box_cox_optimize | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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):
... | 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.
| _yeo_johnson_optimize | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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 t... | Return the negative log likelihood of the observed data x as a
function of lambda. | _neg_log_likelihood | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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 othe... | 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... | _check_input | python | scikit-learn/scikit-learn | sklearn/preprocessing/_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_data.py | BSD-3-Clause |
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
:cl... |
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 ... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_discretization.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_discretization.py | BSD-3-Clause |
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)
... | Returns n_bins_, the number of bins per feature. | _validate_n_bins | python | scikit-learn/scikit-learn | sklearn/preprocessing/_discretization.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_discretization.py | BSD-3-Clause |
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 t... |
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 m... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_discretization.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_discretization.py | BSD-3-Clause |
def inverse_transform(self, X):
"""
Transform discretized data back to original feature space.
Note that this function does not regenerate the original data
due to discretization rounding.
Parameters
----------
X : array-like of shape (n_samples, n_features)
... |
Transform discretized data back to original feature space.
Note that this function does not regenerate the original data
due to discretization rounding.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Transformed data in the binned spa... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_discretization.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_discretization.py | BSD-3-Clause |
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 f... | 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,
... | get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/preprocessing/_discretization.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_discretization.py | BSD-3-Clause |
def _check_X(self, X, ensure_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
... |
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 type... | _check_X | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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... |
This functions checks whether _infrequent_enabled is True or False.
This has to be called after parameter validation in the fit function.
| _check_infrequent_enabled | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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
... | 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.
... | _identify_infrequent | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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 integ... | 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_mappi... | _fit_infrequent_category_mapping | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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
... | 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: n... | _map_infrequent_categories | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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.
... | 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.
| _map_drop_idx_to_infrequent | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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`
oth... | 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 in... | _set_drop_idx | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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.
"""
c... | 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.
| _compute_transformed_categories | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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 no... | Compute the n_features_out for each input feature. | _compute_n_features_outs | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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
... |
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... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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_... |
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 categori... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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, th... |
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 inve... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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
... | 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... | get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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 ... |
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.pip... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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... |
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.
| transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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_original : ndarray of shape (n_sam... |
Convert the data back to the original representation.
Parameters
----------
X : array-like of shape (n_samples, n_encoded_features)
The transformed data.
Returns
-------
X_original : ndarray of shape (n_samples, n_features)
Inverse trans... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_encoders.py | BSD-3-Clause |
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]
... | Check that func and inverse_func are the inverse. | _check_inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_function_transformer.py | BSD-3-Clause |
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
... | 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 : Igno... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_function_transformer.py | BSD-3-Clause |
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
-------... | 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... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_function_transformer.py | BSD-3-Clause |
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... | 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_original : array-l... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_function_transformer.py | BSD-3-Clause |
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.
... | 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_i... | get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/preprocessing/_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_function_transformer.py | BSD-3-Clause |
def set_output(self, *, transform=None):
"""Set output container.
See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py`
for an example on how to use the API.
Parameters
----------
transform : {"default", "pandas", "polars"}, default=None
Configu... | Set output container.
See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py`
for an example on how to use the API.
Parameters
----------
transform : {"default", "pandas", "polars"}, default=None
Configure output of `transform` and `fit_transform`.
... | set_output | python | scikit-learn/scikit-learn | sklearn/preprocessing/_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_function_transformer.py | BSD-3-Clause |
def _get_function_name(self):
"""Get the name display of the `func` used in HTML representation."""
if hasattr(self.func, "__name__"):
return self.func.__name__
if isinstance(self.func, partial):
return self.func.func.__name__
return f"{self.func.__class__.__name_... | Get the name display of the `func` used in HTML representation. | _get_function_name | python | scikit-learn/scikit-learn | sklearn/preprocessing/_function_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_function_transformer.py | BSD-3-Clause |
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)... | Fit label encoder.
Parameters
----------
y : array-like of shape (n_samples,)
Target values.
Returns
-------
self : returns an instance of self.
Fitted label encoder.
| fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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.
"""
... | 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.
| fit_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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.
"""... | 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.
| transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
def inverse_transform(self, y):
"""Transform labels back to original encoding.
Parameters
----------
y : array-like of shape (n_samples,)
Target values.
Returns
-------
y_original : ndarray of shape (n_samples,)
Original encoding.
... | Transform labels back to original encoding.
Parameters
----------
y : array-like of shape (n_samples,)
Target values.
Returns
-------
y_original : ndarray of shape (n_samples,)
Original encoding.
| inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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
-------
s... | 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
Retu... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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... | 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 value... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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 transf... | 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
... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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 t... | 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 ... | label_binarize | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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 =... | Inverse label binarization transformation for multiclass.
Multiclass uses the maximal score instead of a threshold.
| _inverse_binarize_multiclass | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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 != "... | Inverse label binarization transformation using thresholding. | _inverse_binarize_thresholding | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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
iterat... | 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
... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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... | 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... | fit_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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.
Retur... | 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_indica... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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
... | 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
... | _transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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_original : list of tu... | 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_original : list of tuples
The set of labels for each ... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_label.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_label.py | BSD-3-Clause |
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 =... | Helper function for creating and appending sparse expansion matrices | _create_expansion | python | scikit-learn/scikit-learn | sklearn/preprocessing/_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_polynomial.py | BSD-3-Clause |
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 interac... | Calculate number of terms in polynomial expansion
This should be equivalent to counting the number of terms returned by
_combinations(...) but much faster.
| _num_combinations | python | scikit-learn/scikit-learn | sklearn/preprocessing/_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_polynomial.py | BSD-3-Clause |
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.intera... | Exponent for each of the inputs in the output. | powers_ | python | scikit-learn/scikit-learn | sklearn/preprocessing/_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_polynomial.py | BSD-3-Clause |
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
... | 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 d... | get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/preprocessing/_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_polynomial.py | BSD-3-Clause |
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.
Retur... |
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 : obj... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_polynomial.py | BSD-3-Clause |
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
r... | 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 highe... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_polynomial.py | BSD-3-Clause |
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.
... | 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... | _get_base_knot_positions | python | scikit-learn/scikit-learn | sklearn/preprocessing/_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_polynomial.py | BSD-3-Clause |
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
... | 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... | get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/preprocessing/_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_polynomial.py | BSD-3-Clause |
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 = Non... | 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... | fit | python | scikit-learn/scikit-learn | sklearn/preprocessing/_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_polynomial.py | BSD-3-Clause |
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_splin... | 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 featu... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_polynomial.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_polynomial.py | BSD-3-Clause |
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... | 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 <target_encoder>`. for detail... | fit_transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_target_encoder.py | BSD-3-Clause |
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 <target_encoder>`. for de... | 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 <target_encoder>`. for details.
Parameters
... | transform | python | scikit-learn/scikit-learn | sklearn/preprocessing/_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_target_encoder.py | BSD-3-Clause |
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", ensure_all... | Fit a target encoding with all the data. | _fit_encodings_all | python | scikit-learn/scikit-learn | sklearn/preprocessing/_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_target_encoder.py | BSD-3-Clause |
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_c... | 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
... | _fit_encoding_multiclass | python | scikit-learn/scikit-learn | sklearn/preprocessing/_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_target_encoder.py | BSD-3-Clause |
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_fea... | 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 feature... | _transform_X_ordinal | python | scikit-learn/scikit-learn | sklearn/preprocessing/_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_target_encoder.py | BSD-3-Clause |
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
-------
... | 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
Trans... | get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/preprocessing/_target_encoder.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/_target_encoder.py | BSD-3-Clause |
def test_quantile_transform_subsampling_disabled():
"""Check the behaviour of `QuantileTransformer` when `subsample=None`."""
X = np.random.RandomState(0).normal(size=(200, 1))
n_quantiles = 5
transformer = QuantileTransformer(n_quantiles=n_quantiles, subsample=None).fit(X)
expected_references = n... | Check the behaviour of `QuantileTransformer` when `subsample=None`. | test_quantile_transform_subsampling_disabled | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_data.py | BSD-3-Clause |
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-... | Check that box-cox raises informative when a column contains all nans.
Non-regression test for gh-26303
| test_power_transformer_box_cox_raise_all_nans_col | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_data.py | BSD-3-Clause |
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,... | 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
| test_standard_scaler_raise_error_for_1d_input | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_data.py | BSD-3-Clause |
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
... | 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
| test_power_transformer_significantly_non_gaussian | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_data.py | BSD-3-Clause |
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) | Check one-to-one transformers give correct feature names. | test_one_to_one_features | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_data.py | BSD-3-Clause |
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_arra... | Check one-to-one transformers give correct feature names. | test_one_to_one_features_pandas | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_data.py | BSD-3-Clause |
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_... | Check that PowerTransfomer leaves constant features unchanged. | test_power_transformer_constant_feature | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_data.py | BSD-3-Clause |
def test_power_transformer_no_warnings():
"""Verify that PowerTransformer operates without raising any warnings on valid data.
This test addresses numerical issues with floating point numbers (mostly
overflows) with the Yeo-Johnson transform, see
https://github.com/scikit-learn/scikit-learn/issues/2331... | Verify that PowerTransformer operates without raising any warnings on valid data.
This test addresses numerical issues with floating point numbers (mostly
overflows) with the Yeo-Johnson transform, see
https://github.com/scikit-learn/scikit-learn/issues/23319#issuecomment-1464933635
| test_power_transformer_no_warnings | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_data.py | BSD-3-Clause |
def _test_no_warnings(data):
"""Internal helper to test for unexpected warnings."""
with warnings.catch_warnings(record=True) as caught_warnings:
warnings.simplefilter("always") # Ensure all warnings are captured
PowerTransformer(method="yeo-johnson", standardize=True).fit_trans... | Internal helper to test for unexpected warnings. | _test_no_warnings | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_data.py | BSD-3-Clause |
def test_yeojohnson_for_different_scipy_version():
"""Check that the results are consistent across different SciPy versions."""
pt = PowerTransformer(method="yeo-johnson").fit(X_1col)
pt.lambdas_[0] == pytest.approx(0.99546157, rel=1e-7) | Check that the results are consistent across different SciPy versions. | test_yeojohnson_for_different_scipy_version | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_data.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_data.py | BSD-3-Clause |
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(
... | Check the impact of `sample_weight` one computed quantiles. | test_kbinsdiscretizer_effect_sample_weight | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_discretization.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_discretization.py | BSD-3-Clause |
def test_kbinsdiscretizer_no_mutating_sample_weight(strategy):
"""Make sure that `sample_weight` is not changed in place."""
if strategy == "quantile":
est = KBinsDiscretizer(
n_bins=3,
encode="ordinal",
strategy=strategy,
quantile_method="averaged_invert... | Make sure that `sample_weight` is not changed in place. | test_kbinsdiscretizer_no_mutating_sample_weight | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_discretization.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_discretization.py | BSD-3-Clause |
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, quantile_method="averaged... | Check get_feature_names_out for different settings.
Non-regression test for #22731
| test_kbinsdiscrtizer_get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_discretization.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_discretization.py | BSD-3-Clause |
def test_one_hot_encoder_custom_feature_name_combiner():
"""Check the behaviour of `feature_name_combiner` as a callable."""
def name_combiner(feature, category):
return feature + "_" + repr(category)
enc = OneHotEncoder(feature_name_combiner=name_combiner)
X = np.array([["None", None]], dtype... | Check the behaviour of `feature_name_combiner` as a callable. | test_one_hot_encoder_custom_feature_name_combiner | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_one_hot_encoder_inverse_transform_raise_error_with_unknown(
X, X_trans, sparse_
):
"""Check that `inverse_transform` raise an error with unknown samples, no
dropped feature, and `handle_unknow="error`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/14934
""... | Check that `inverse_transform` raise an error with unknown samples, no
dropped feature, and `handle_unknow="error`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/14934
| test_one_hot_encoder_inverse_transform_raise_error_with_unknown | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_encoder_nan_ending_specified_categories(Encoder):
"""Test encoder for specified categories that nan is at the end.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27088
"""
cats = [np.array([0, np.nan, 1])]
enc = Encoder(categories=cats)
X = np.array([[... | Test encoder for specified categories that nan is at the end.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27088
| test_encoder_nan_ending_specified_categories | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_two_levels(kwargs, categories):
"""Test that different parameters for combine 'a', 'c', and 'd' into
the infrequent category works as expected."""
X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T
ohe = OneHotEncoder(
categories=categories,
... | Test that different parameters for combine 'a', 'c', and 'd' into
the infrequent category works as expected. | test_ohe_infrequent_two_levels | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_two_levels_drop_frequent(drop):
"""Test two levels and dropping the frequent category."""
X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T
ohe = OneHotEncoder(
handle_unknown="infrequent_if_exist",
sparse_output=False,
max_categories=2,... | Test two levels and dropping the frequent category. | test_ohe_infrequent_two_levels_drop_frequent | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_two_levels_drop_infrequent_errors(drop):
"""Test two levels and dropping any infrequent category removes the
whole infrequent category."""
X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T
ohe = OneHotEncoder(
handle_unknown="infrequent_if_exist",
... | Test two levels and dropping any infrequent category removes the
whole infrequent category. | test_ohe_infrequent_two_levels_drop_infrequent_errors | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_three_levels(kwargs):
"""Test that different parameters for combing 'a', and 'd' into
the infrequent category works as expected."""
X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T
ohe = OneHotEncoder(
handle_unknown="infrequent_if_exist", sparse_o... | Test that different parameters for combing 'a', and 'd' into
the infrequent category works as expected. | test_ohe_infrequent_three_levels | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_three_levels_drop_frequent(drop):
"""Test three levels and dropping the frequent category."""
X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T
ohe = OneHotEncoder(
handle_unknown="infrequent_if_exist",
sparse_output=False,
max_categorie... | Test three levels and dropping the frequent category. | test_ohe_infrequent_three_levels_drop_frequent | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_three_levels_drop_infrequent_errors(drop):
"""Test three levels and dropping the infrequent category."""
X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T
ohe = OneHotEncoder(
handle_unknown="infrequent_if_exist",
sparse_output=False,
max... | Test three levels and dropping the infrequent category. | test_ohe_infrequent_three_levels_drop_infrequent_errors | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
def test_ohe_infrequent_handle_unknown_error():
"""Test that different parameters for combining 'a', and 'd' into
the infrequent category works as expected."""
X_train = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3]).T
ohe = OneHotEncoder(
handle_unknown="error", sparse_output=Fals... | Test that different parameters for combining 'a', and 'd' into
the infrequent category works as expected. | test_ohe_infrequent_handle_unknown_error | python | scikit-learn/scikit-learn | sklearn/preprocessing/tests/test_encoders.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/tests/test_encoders.py | BSD-3-Clause |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.