|
| 1 | +"""Base encoder for various contrast coding schemes""" |
| 2 | +from abc import abstractmethod |
| 3 | + |
| 4 | +import pandas as pd |
| 5 | +from patsy.contrasts import ContrastMatrix |
| 6 | +import numpy as np |
| 7 | +from category_encoders.ordinal import OrdinalEncoder |
| 8 | +import category_encoders.utils as util |
| 9 | + |
| 10 | +__author__ = 'paulwestenthanner' |
| 11 | + |
| 12 | + |
| 13 | +class BaseContrastEncoder(util.BaseEncoder, util.UnsupervisedTransformerMixin): |
| 14 | + """Base class for various contrast encoders |
| 15 | +
|
| 16 | + Parameters |
| 17 | + ---------- |
| 18 | +
|
| 19 | + verbose: int |
| 20 | + integer indicating verbosity of the output. 0 for none. |
| 21 | + cols: list |
| 22 | + a list of columns to encode, if None, all string columns will be encoded. |
| 23 | + drop_invariant: bool |
| 24 | + boolean for whether or not to drop columns with 0 variance. |
| 25 | + return_df: bool |
| 26 | + boolean for whether to return a pandas DataFrame from transform (otherwise it will be a numpy array). |
| 27 | + handle_unknown: str |
| 28 | + options are 'error', 'return_nan', 'value', and 'indicator'. The default is 'value'. Warning: if indicator is used, |
| 29 | + an extra column will be added in if the transform matrix has unknown categories. This can cause |
| 30 | + unexpected changes in dimension in some cases. |
| 31 | + handle_missing: str |
| 32 | + options are 'error', 'return_nan', 'value', and 'indicator'. The default is 'value'. Warning: if indicator is used, |
| 33 | + an extra column will be added in if the transform matrix has nan values. This can cause |
| 34 | + unexpected changes in dimension in some cases. |
| 35 | +
|
| 36 | + References |
| 37 | + ---------- |
| 38 | +
|
| 39 | + .. [1] Contrast Coding Systems for Categorical Variables, from |
| 40 | + https://stats.idre.ucla.edu/r/library/r-library-contrast-coding-systems-for-categorical-variables/ |
| 41 | +
|
| 42 | + .. [2] Gregory Carey (2003). Coding Categorical Variables, from |
| 43 | + http://psych.colorado.edu/~carey/Courses/PSYC5741/handouts/Coding%20Categorical%20Variables%202006-03-03.pdf |
| 44 | +
|
| 45 | + """ |
| 46 | + prefit_ordinal = True |
| 47 | + encoding_relation = util.EncodingRelation.ONE_TO_N_UNIQUE |
| 48 | + |
| 49 | + def __init__(self, verbose=0, cols=None, mapping=None, drop_invariant=False, return_df=True, |
| 50 | + handle_unknown='value', handle_missing='value'): |
| 51 | + super().__init__(verbose=verbose, cols=cols, drop_invariant=drop_invariant, return_df=return_df, |
| 52 | + handle_unknown=handle_unknown, handle_missing=handle_missing) |
| 53 | + self.mapping = mapping |
| 54 | + self.ordinal_encoder = None |
| 55 | + |
| 56 | + def _fit(self, X, y=None, **kwargs): |
| 57 | + # train an ordinal pre-encoder |
| 58 | + self.ordinal_encoder = OrdinalEncoder( |
| 59 | + verbose=self.verbose, |
| 60 | + cols=self.cols, |
| 61 | + handle_unknown='value', |
| 62 | + handle_missing='value' |
| 63 | + ) |
| 64 | + self.ordinal_encoder = self.ordinal_encoder.fit(X) |
| 65 | + |
| 66 | + ordinal_mapping = self.ordinal_encoder.category_mapping |
| 67 | + |
| 68 | + mappings_out = [] |
| 69 | + for switch in ordinal_mapping: |
| 70 | + values = switch.get('mapping') |
| 71 | + col = switch.get('col') |
| 72 | + |
| 73 | + column_mapping = self.fit_contrast_coding(col, values, self.handle_missing, self.handle_unknown) |
| 74 | + mappings_out.append({'col': col, 'mapping': column_mapping, }) |
| 75 | + |
| 76 | + self.mapping = mappings_out |
| 77 | + |
| 78 | + def _transform(self, X) -> pd.DataFrame: |
| 79 | + X = self.ordinal_encoder.transform(X) |
| 80 | + if self.handle_unknown == 'error': |
| 81 | + if X[self.cols].isin([-1]).any().any(): |
| 82 | + raise ValueError('Columns to be encoded can not contain new values') |
| 83 | + |
| 84 | + X = self.transform_contrast_coding(X, mapping=self.mapping) |
| 85 | + return X |
| 86 | + |
| 87 | + @abstractmethod |
| 88 | + def get_contrast_matrix(self, values_to_encode: np.array) -> ContrastMatrix: |
| 89 | + raise NotImplementedError |
| 90 | + |
| 91 | + def fit_contrast_coding(self, col, values, handle_missing, handle_unknown): |
| 92 | + if handle_missing == 'value': |
| 93 | + values = values[values > 0] |
| 94 | + |
| 95 | + values_to_encode = values.values |
| 96 | + |
| 97 | + if len(values) < 2: |
| 98 | + return pd.DataFrame(index=values_to_encode) |
| 99 | + |
| 100 | + if handle_unknown == 'indicator': |
| 101 | + values_to_encode = np.append(values_to_encode, -1) |
| 102 | + |
| 103 | + contrast_matrix = self.get_contrast_matrix(values_to_encode) |
| 104 | + df = pd.DataFrame(data=contrast_matrix.matrix, index=values_to_encode, |
| 105 | + columns=[f"{col}_{i}" for i in range(len(contrast_matrix.column_suffixes))]) |
| 106 | + |
| 107 | + if handle_unknown == 'return_nan': |
| 108 | + df.loc[-1] = np.nan |
| 109 | + elif handle_unknown == 'value': |
| 110 | + df.loc[-1] = np.zeros(len(values_to_encode) - 1) |
| 111 | + |
| 112 | + if handle_missing == 'return_nan': |
| 113 | + df.loc[values.loc[np.nan]] = np.nan |
| 114 | + elif handle_missing == 'value': |
| 115 | + df.loc[-2] = np.zeros(len(values_to_encode) - 1) |
| 116 | + |
| 117 | + return df |
| 118 | + |
| 119 | + @staticmethod |
| 120 | + def transform_contrast_coding(X, mapping): |
| 121 | + cols = X.columns.values.tolist() |
| 122 | + |
| 123 | + # See issue 370 if it is necessary to add an intercept or not. |
| 124 | + X['intercept'] = pd.Series([1] * X.shape[0], index=X.index) |
| 125 | + |
| 126 | + for switch in mapping: |
| 127 | + col = switch.get('col') |
| 128 | + mod = switch.get('mapping') |
| 129 | + |
| 130 | + # reindex actually applies the mapping |
| 131 | + base_df = mod.reindex(X[col]) |
| 132 | + base_df.set_index(X.index, inplace=True) |
| 133 | + X = pd.concat([base_df, X], axis=1) |
| 134 | + |
| 135 | + old_column_index = cols.index(col) |
| 136 | + cols[old_column_index: old_column_index + 1] = mod.columns |
| 137 | + |
| 138 | + # this could lead to problems if an intercept column is already present |
| 139 | + # (e.g. if another column has been encoded with another contrast coding scheme) |
| 140 | + cols = ['intercept'] + cols |
| 141 | + |
| 142 | + return X.reindex(columns=cols) |
0 commit comments