OneHotEncoder#

class cuml.preprocessing.OneHotEncoder(
*,
categories='auto',
drop=None,
sparse_output=True,
dtype=<class 'numpy.float32'>,
handle_unknown='error',
output_type=None,
verbose=False,
)[source]#

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.

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.

drop‘first’, None, or 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.

  • array : drop[i] is the category in feature X[:, i] that should be dropped.

sparse_outputbool, default=True

When True, transform returns a sparse matrix/array in CSR format.

dtypedtype, default=np.float32

Desired dtype of transformed output.

handle_unknown{‘error’, ‘ignore’}, default=’error’

Specifies the way unknown categories are handled during 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.

verboseint or boolean, default=False

Sets logging level. It must be one of cuml.common.logger.level_*. See Verbosity Levels for more info.

output_type{None, ‘input’, ‘cupy’, ‘numpy’, ‘cudf’, ‘pandas’}, default=None

Return results and set estimator attributes to the indicated output type. If None, the output type set at the module level (cuml.global_settings.output_type) will be used. See Output Data Type Configuration for more info.

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 feature i, or None if no category is to be dropped.

  • drop_idx_ = None if all the transformed features will be retained.

n_features_in_int

Number of features seen during fit.

feature_names_in_ndarray of shape (n_features_in_,)

Names of features seen during fit. Defined only when X has feature names that are all strings.

Methods

fit(X[, y])

Fit OneHotEncoder to X.

fit_transform(X[, y])

Fit OneHotEncoder to X, then transform X.

get_feature_names_out([input_features])

Get output feature names for transformation.

inverse_transform(X)

Convert the data back to the original representation.

transform(X)

Transform X using one-hot encoding.

Examples

>>> import cudf
>>> from cuml.preprocessing import OneHotEncoder
>>> X = cudf.DataFrame({"fruit": ["apple", "banana", "apple"], "group": [1, 3, 2]})
>>> enc = OneHotEncoder().fit(X)
>>> enc.categories_
[array(['apple', 'banana'], dtype=object), array([1, 2, 3])]
>>> enc.transform(X).toarray()
array([[1., 0., 1., 0., 0.],
       [0., 1., 0., 0., 1.],
       [1., 0., 0., 1., 0.]], dtype=float32)
>>> enc.inverse_transform([[0, 1, 1, 0, 0], [1, 0, 0, 1, 0]])
array([['banana', 1],
       ['apple', 2]], dtype=object)
as_sklearn()[source]#

Convert this estimator into an equivalent scikit-learn (or scikit-learn extension) estimator.

Returns:
sklearn.base.BaseEstimator

A scikit-learn compatible estimator instance that mirrors the trained state of the current estimator.

fit(
X,
y=None,
) OneHotEncoder[source]#

Fit OneHotEncoder to X.

Parameters:
Xarray-like (device or host) shape = (n_samples, n_features)

Dense matrix with dtype float32 or float64. Acceptable formats: CUDA array interface compliant objects like CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas DataFrame/Series.

yNone

Ignored. This parameter exists for compatibility only.

fit_transform(X, y=None)[source]#

Fit OneHotEncoder to X, then transform X.

Parameters:
Xarray-like (device or host) shape = (n_samples, n_features)

Dense matrix with dtype float32 or float64. Acceptable formats: CUDA array interface compliant objects like CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas DataFrame/Series.

yNone

Ignored. This parameter exists for compatibility only.

Returns:
X_outcuDF, CuPy or NumPy object depending on cuML’s output type configuration, cupyx.scipy.sparse for sparse output, shape = (n_samples, n_encoded_features)

Transformed input. A sparse matrix if sparse_output=True, dense otherwise.

For more information on how to configure cuML’s dense output type, refer to: Output Data Type Configuration.

classmethod from_sklearn(model)[source]#

Create a cuml estimator from a scikit-learn estimator.

Parameters:
modelsklearn.base.BaseEstimator

A compatible scikit-learn (or scikit-learn extension) estimator.

Returns:
cls

A new instance of this cuml estimator class that mirrors the state of the input estimator.

Notes

output_type of the estimator is set to “numpy” by default, as these cannot be inferred from training arguments. If something different is required, then please use cuml’s output_type configuration utilities.

get_feature_names(input_features=None)[source]#

Return feature names for output features.

Deprecated since version 26.10: This method was deprecated in version 26.10 and will be removed in version 26.12. Please use get_feature_names_out instead.

get_feature_names_out(input_features=None)[source]#

Get output feature names for transformation.

Parameters:
input_featuresarray-like of str or None, default=None

Input feature names.

Returns:
feature_names_outnumpy.ndarray of str objects.

Transformed feature names.

get_params(deep=True)[source]#

Returns a dict of all params owned by this class. If the child class has appropriately overridden the _get_param_names method and does not need anything other than what is there in this method, then it doesn’t have to override this method

inverse_transform(X)[source]#

Convert the data back to the original representation.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_encoded_features)

The transformed data.

Returns:
X_originalarray of shape (n_samples, n_features)

Inverse transformed array.

set_params(**params)[source]#

Accepts a dict of params and updates the corresponding ones owned by this class. If the child class has appropriately overridden the _get_param_names method and does not need anything other than what is, there in this method, then it doesn’t have to override this method

transform(X)[source]#

Transform X using one-hot encoding.

Parameters:
Xarray-like (device or host) shape = (n_samples, n_features)

Dense matrix with dtype float32 or float64. Acceptable formats: CUDA array interface compliant objects like CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas DataFrame/Series.

Returns:
X_outcuDF, CuPy or NumPy object depending on cuML’s output type configuration, cupyx.scipy.sparse for sparse output, shape = (n_samples, n_encoded_features)

Transformed input. A sparse matrix if sparse_output=True, dense otherwise.

For more information on how to configure cuML’s dense output type, refer to: Output Data Type Configuration.