-
-
Notifications
You must be signed in to change notification settings - Fork 25.8k
/
Copy path_encoders.py
1698 lines (1421 loc) · 66.8 KB
/
_encoders.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Authors: The scikit-learn developers
# SPDX-License-Identifier: 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
from ..utils._encode import _check_unknown, _encode, _get_counts, _unique
from ..utils._mask import _get_mask
from ..utils._missing import is_scalar_nan
from ..utils._param_validation import Interval, RealNotInt, StrOptions
from ..utils._set_output import _get_output_config
from ..utils.validation import (
_check_feature_names,
_check_feature_names_in,
_check_n_features,
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, 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
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, ensure_all_finite=ensure_all_finite)
if not hasattr(X, "dtype") and np.issubdtype(X_temp.dtype, np.str_):
X = check_array(X, dtype=object, ensure_all_finite=ensure_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 = ensure_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, ensure_all_finite=needs_validation
)
X_columns.append(Xi)
return X_columns, n_samples, n_features
def _fit(
self,
X,
handle_unknown="error",
ensure_all_finite=True,
return_counts=False,
return_and_ignore_missing_for_infrequent=False,
):
self._check_infrequent_enabled()
_check_n_features(self, X, reset=True)
_check_feature_names(self, X, reset=True)
X_list, n_samples, n_features = self._check_X(
X, ensure_all_finite=ensure_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",
ensure_all_finite=True,
warn_on_unknown=False,
ignore_category_indices=None,
):
X_list, n_samples, n_features = self._check_X(
X, ensure_all_finite=ensure_all_finite
)
_check_feature_names(self, X, reset=False)
_check_n_features(self, 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 __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.input_tags.categorical = True
tags.input_tags.allow_nan = True
return tags
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 <preprocessing_categorical_features>`.
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', 'warn'}, \
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 <encoder_infrequent_categories>`.
- 'warn' : When an unknown category is encountered during transform
a warning is issued, and the encoding then proceeds as described for
`handle_unknown="infrequent_if_exist"`.
.. versionchanged:: 1.1
`'infrequent_if_exist'` was added to automatically handle unknown
categories and infrequent categories.
.. versionadded:: 1.6
The option `"warn"` was added in 1.6.
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 <encoder_infrequent_categories>`.
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 <encoder_infrequent_categories>`.
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", "warn"})
],
"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,
ensure_all_finite="allow-nan",
)
self._set_drop_idx()
self._n_features_outs = self._compute_n_features_outs()
return self
def transform(self, X):