# 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]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/preprocessing/encoders.py#L201)

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**
  : 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**
  : 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.
    <br/>
    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_output**
  : When `True`, transform returns a sparse matrix/array in CSR format.

  **dtype**
  : Desired dtype of transformed output.

  **handle_unknown**
  : Specifies the way unknown categories are handled during [`transform()`](#cuml.preprocessing.OneHotEncoder.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.

  **verbose**
  : Sets logging level. It must be one of `cuml.common.logger.level_*`.
    See [Verbosity Levels](../../cuml/index.html.md#verbosity-levels) for more info.

  **output_type**
  : 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](../../cuml/index.html.md#output-data-type-configuration) for more info.
* **Attributes:**
  **categories_**
  : 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_**
  : - `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_**
  : Number of features seen during `fit`.

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

### Methods

| [`fit`](#cuml.preprocessing.OneHotEncoder.fit)(X[, y])                             | Fit OneHotEncoder to X.                               |
|------------------------------------------------------------------------------------------|-------------------------------------------------------|
| [`fit_transform`](#cuml.preprocessing.OneHotEncoder.fit_transform)(X[, y])                   | Fit OneHotEncoder to X, then transform X.             |
| [`get_feature_names_out`](#cuml.preprocessing.OneHotEncoder.get_feature_names_out)([input_features]) | Get output feature names for transformation.          |
| [`inverse_transform`](#cuml.preprocessing.OneHotEncoder.inverse_transform)(X)                    | Convert the data back to the original representation. |
| [`transform`](#cuml.preprocessing.OneHotEncoder.transform)(X)                            | Transform X using one-hot encoding.                   |

### Examples

```pycon
>>> 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)
```

<!-- !! processed by numpydoc !! -->

#### as_sklearn()[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/interop.py#L206)

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.

<!-- !! processed by numpydoc !! -->

#### fit(X, y=None) → [OneHotEncoder](#cuml.preprocessing.OneHotEncoder)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/preprocessing/encoders.py#L408)

Fit OneHotEncoder to X.

* **Parameters:**
  **X**
  : 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.

  **y**
  : Ignored. This parameter exists for compatibility only.

<!-- !! processed by numpydoc !! -->

#### fit_transform(X, y=None)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/preprocessing/encoders.py#L416)

Fit OneHotEncoder to X, then transform X.

* **Parameters:**
  **X**
  : 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.

  **y**
  : Ignored. This parameter exists for compatibility only.
* **Returns:**
  **X_out**
  : Transformed input. A sparse matrix if `sparse_output=True`, dense otherwise.
    <br/>
    For more information on how to configure cuML’s dense output type,
    refer to: [Output Data Type Configuration](../../cuml/index.html.md#output-data-type-configuration).

<!-- !! processed by numpydoc !! -->

#### *classmethod* from_sklearn(model)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/interop.py#L222)

Create a cuml estimator from a scikit-learn estimator.

* **Parameters:**
  **model**
  : 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.

<!-- !! processed by numpydoc !! -->

#### get_feature_names_out(input_features=None)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/preprocessing/encoders.py#L678)

Get output feature names for transformation.

* **Parameters:**
  **input_features**
  : Input feature names.
* **Returns:**
  **feature_names_out**
  : Transformed feature names.

<!-- !! processed by numpydoc !! -->

#### get_params(deep=True)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/base.py#L191)

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

<!-- !! processed by numpydoc !! -->

#### inverse_transform(X)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/preprocessing/encoders.py#L605)

Convert the data back to the original representation.

* **Parameters:**
  **X**
  : The transformed data.
* **Returns:**
  **X_original**
  : Inverse transformed array.

<!-- !! processed by numpydoc !! -->

#### set_params(\*\*params)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/base.py#L200)

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

<!-- !! processed by numpydoc !! -->

#### transform(X)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/preprocessing/encoders.py#L510)

Transform X using one-hot encoding.

* **Parameters:**
  **X**
  : 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_out**
  : Transformed input. A sparse matrix if `sparse_output=True`, dense otherwise.
    <br/>
    For more information on how to configure cuML’s dense output type,
    refer to: [Output Data Type Configuration](../../cuml/index.html.md#output-data-type-configuration).

<!-- !! processed by numpydoc !! -->
