|
| 1 | +"""Gray encoding""" |
| 2 | +from functools import partialmethod |
| 3 | + |
| 4 | +import pandas as pd |
| 5 | + |
| 6 | +from category_encoders import utils |
| 7 | +from category_encoders.basen import BaseNEncoder |
| 8 | +from typing import List |
| 9 | + |
| 10 | +__author__ = 'paulwestenthanner' |
| 11 | + |
| 12 | + |
| 13 | +class GrayEncoder(BaseNEncoder): |
| 14 | + """Gray encoding for categorical variables. |
| 15 | + Gray encoding is a form of binary encoding where consecutive values only differ by a single bit. |
| 16 | + Hence, gray encoding only makes sense for ordinal features. |
| 17 | + This has benefits in privacy preserving data publishing. |
| 18 | +
|
| 19 | + Parameters |
| 20 | + ---------- |
| 21 | +
|
| 22 | + verbose: int |
| 23 | + integer indicating verbosity of the output. 0 for none. |
| 24 | + cols: list |
| 25 | + a list of columns to encode, if None, all string columns will be encoded. |
| 26 | + drop_invariant: bool |
| 27 | + boolean for whether or not to drop columns with 0 variance. |
| 28 | + return_df: bool |
| 29 | + boolean for whether to return a pandas DataFrame from transform (otherwise it will be a numpy array). |
| 30 | + handle_unknown: str |
| 31 | + options are 'error', 'return_nan', 'value', and 'indicator'. The default is 'value'. Warning: if indicator is used, |
| 32 | + an extra column will be added in if the transform matrix has unknown categories. This can cause |
| 33 | + unexpected changes in dimension in some cases. |
| 34 | + handle_missing: str |
| 35 | + options are 'error', 'return_nan', 'value', and 'indicator'. The default is 'value'. Warning: if indicator is used, |
| 36 | + an extra column will be added in if the transform matrix has nan values. This can cause |
| 37 | + unexpected changes in dimension in some cases. |
| 38 | +
|
| 39 | + Example |
| 40 | + ------- |
| 41 | + >>> from category_encoders import GrayEncoder |
| 42 | + >>> import pandas as pd |
| 43 | + >>> from sklearn.datasets import load_boston |
| 44 | + >>> bunch = load_boston() |
| 45 | + >>> y = bunch.target |
| 46 | + >>> X = pd.DataFrame(bunch.data, columns=bunch.feature_names) |
| 47 | + >>> enc = GrayEncoder(cols=['CHAS', 'RAD']).fit(X, y) |
| 48 | + >>> numeric_dataset = enc.transform(X) |
| 49 | + >>> print(numeric_dataset.info()) |
| 50 | + <class 'pandas.core.frame.DataFrame'> |
| 51 | + RangeIndex: 506 entries, 0 to 505 |
| 52 | + Data columns (total 18 columns): |
| 53 | + CRIM 506 non-null float64 |
| 54 | + ZN 506 non-null float64 |
| 55 | + INDUS 506 non-null float64 |
| 56 | + CHAS_0 506 non-null int64 |
| 57 | + CHAS_1 506 non-null int64 |
| 58 | + NOX 506 non-null float64 |
| 59 | + RM 506 non-null float64 |
| 60 | + AGE 506 non-null float64 |
| 61 | + DIS 506 non-null float64 |
| 62 | + RAD_0 506 non-null int64 |
| 63 | + RAD_1 506 non-null int64 |
| 64 | + RAD_2 506 non-null int64 |
| 65 | + RAD_3 506 non-null int64 |
| 66 | + RAD_4 506 non-null int64 |
| 67 | + TAX 506 non-null float64 |
| 68 | + PTRATIO 506 non-null float64 |
| 69 | + B 506 non-null float64 |
| 70 | + LSTAT 506 non-null float64 |
| 71 | + dtypes: float64(11), int64(7) |
| 72 | + memory usage: 71.3 KB |
| 73 | + None |
| 74 | +
|
| 75 | + References |
| 76 | + ---------- |
| 77 | +
|
| 78 | + .. [1] https://en.wikipedia.org/wiki/Gray_code |
| 79 | + .. [2] Jun Zhang, Graham Cormode, Cecilia M. Procopiuc, Divesh Srivastava, and Xiaokui Xiao. 2017. PrivBayes: |
| 80 | + Private Data Release via Bayesian Networks. ACM Trans. Database Syst. 42, 4, Article 25 (October 2017) |
| 81 | + """ |
| 82 | + encoding_relation = utils.EncodingRelation.ONE_TO_M |
| 83 | + __init__ = partialmethod(BaseNEncoder.__init__, base=2) |
| 84 | + |
| 85 | + @staticmethod |
| 86 | + def gray_code(n, n_bit) -> List[int]: |
| 87 | + gray = n ^ (n >> 1) |
| 88 | + gray_formatted = "{0:0{1}b}".format(gray, n_bit) |
| 89 | + return [int(bit) for bit in gray_formatted] |
| 90 | + |
| 91 | + def _fit(self, X, y=None, **kwargs): |
| 92 | + super(GrayEncoder, self)._fit(X, y, **kwargs) |
| 93 | + gray_mapping = [] |
| 94 | + # convert binary mapping to Gray mapping and reorder |
| 95 | + for col_to_encode in self.mapping: |
| 96 | + col = col_to_encode["col"] |
| 97 | + bin_mapping = col_to_encode["mapping"] |
| 98 | + n_cols_out = bin_mapping.shape[1] |
| 99 | + null_cond = (bin_mapping.index < 0) | (bin_mapping.isnull().all(1)) |
| 100 | + map_null = bin_mapping[null_cond] |
| 101 | + map_non_null = bin_mapping[~null_cond].copy() |
| 102 | + ordinal_mapping = [m for m in self.ordinal_encoder.mapping if m.get("col") == col] |
| 103 | + if len(ordinal_mapping) != 1: |
| 104 | + raise ValueError("Cannot find ordinal encoder mapping of Gray encoder") |
| 105 | + ordinal_mapping = ordinal_mapping[0]["mapping"] |
| 106 | + reverse_ordinal_mapping = {v: k for k, v in ordinal_mapping.to_dict().items()} |
| 107 | + map_non_null["orig_value"] = map_non_null.index.to_series().map(reverse_ordinal_mapping) |
| 108 | + map_non_null = map_non_null.sort_values(by="orig_value") |
| 109 | + gray_encoding = [self.gray_code(i + 1, n_cols_out) for i in range(map_non_null.shape[0])] |
| 110 | + gray_encoding = pd.DataFrame(data=gray_encoding, index=map_non_null.index, columns=bin_mapping.columns) |
| 111 | + gray_encoding = pd.concat([gray_encoding, map_null]) |
| 112 | + gray_mapping.append({"col": col, "mapping": gray_encoding}) |
| 113 | + self.mapping = gray_mapping |
0 commit comments