MCPcopy Create free account
hub / github.com/scikit-learn/scikit-learn / transform

Method transform

sklearn/preprocessing/_encoders.py:1009–1094  ·  view source on GitHub ↗

Transform X using one-hot encoding. If `sparse_output=True` (default), it returns a SciPy sparse in CSR format. If there are infrequent categories for a feature, set by specifying `max_categories` or `min_frequency`, the infrequent categories are grouped in

(self, X)

Source from the content-addressed store, hash-verified

1007 return self
1008
1009 def transform(self, X):
1010 """
1011 Transform X using one-hot encoding.
1012
1013 If `sparse_output=True` (default), it returns a SciPy sparse in CSR format.
1014
1015 If there are infrequent categories for a feature, set by specifying
1016 `max_categories` or `min_frequency`, the infrequent categories are
1017 grouped into a single category.
1018
1019 Parameters
1020 ----------
1021 X : array-like of shape (n_samples, n_features)
1022 The data to encode.
1023
1024 Returns
1025 -------
1026 X_out : {ndarray, sparse matrix} of shape \
1027 (n_samples, n_encoded_features)
1028 Transformed input. If `sparse_output=True`, a sparse matrix will be
1029 returned.
1030 """
1031 check_is_fitted(self)
1032 transform_output = _get_output_config("transform", estimator=self)["dense"]
1033 if transform_output != "default" and self.sparse_output:
1034 capitalize_transform_output = transform_output.capitalize()
1035 raise ValueError(
1036 f"{capitalize_transform_output} output does not support sparse data."
1037 f" Set sparse_output=False to output {transform_output} dataframes or"
1038 f" disable {capitalize_transform_output} output via"
1039 '` ohe.set_output(transform="default").'
1040 )
1041
1042 # validation of X happens in _check_X called by _transform
1043 if self.handle_unknown == "warn":
1044 warn_on_unknown, handle_unknown = True, "infrequent_if_exist"
1045 else:
1046 warn_on_unknown = self.drop is not None and self.handle_unknown in {
1047 "ignore",
1048 "infrequent_if_exist",
1049 }
1050 handle_unknown = self.handle_unknown
1051 X_int, X_mask = self._transform(
1052 X,
1053 handle_unknown=handle_unknown,
1054 ensure_all_finite="allow-nan",
1055 warn_on_unknown=warn_on_unknown,
1056 )
1057
1058 n_samples, n_features = X_int.shape
1059
1060 if self._drop_idx_after_grouping is not None:
1061 to_drop = self._drop_idx_after_grouping.copy()
1062 # We remove all the dropped categories from mask, and decrement all
1063 # categories that occur after them to avoid an empty column.
1064 keep_cells = X_int != to_drop
1065 for i, cats in enumerate(self.categories_):
1066 # drop='if_binary' but feature isn't binary

Calls 5

check_is_fittedFunction · 0.90
_get_output_configFunction · 0.90
_align_api_if_sparseFunction · 0.90
_transformMethod · 0.45