[docs]classSumEncoder(BaseEstimator,TransformerMixin):"""Sum contrast coding for the encoding of categorical features. Parameters ---------- verbose: int integer indicating verbosity of the output. 0 for none. cols: list a list of columns to encode, if None, all string columns will be encoded. drop_invariant: bool boolean for whether or not to drop columns with 0 variance. return_df: bool boolean for whether to return a pandas DataFrame from transform (otherwise it will be a numpy array). handle_unknown: str options are 'error', 'return_nan', 'value', and 'indicator'. The default is 'value'. Warning: if indicator is used, an extra column will be added in if the transform matrix has unknown categories. This can cause unexpected changes in dimension in some cases. handle_missing: str options are 'error', 'return_nan', 'value', and 'indicator'. The default is 'value'. Warning: if indicator is used, an extra column will be added in if the transform matrix has nan values. This can cause unexpected changes in dimension in some cases. Example ------- >>> from category_encoders import * >>> import pandas as pd >>> from sklearn.datasets import load_boston >>> bunch = load_boston() >>> y = bunch.target >>> X = pd.DataFrame(bunch.data, columns=bunch.feature_names) >>> enc = SumEncoder(cols=['CHAS', 'RAD']).fit(X, y) >>> numeric_dataset = enc.transform(X) >>> print(numeric_dataset.info()) <class 'pandas.core.frame.DataFrame'> RangeIndex: 506 entries, 0 to 505 Data columns (total 21 columns): intercept 506 non-null int64 CRIM 506 non-null float64 ZN 506 non-null float64 INDUS 506 non-null float64 CHAS_0 506 non-null float64 NOX 506 non-null float64 RM 506 non-null float64 AGE 506 non-null float64 DIS 506 non-null float64 RAD_0 506 non-null float64 RAD_1 506 non-null float64 RAD_2 506 non-null float64 RAD_3 506 non-null float64 RAD_4 506 non-null float64 RAD_5 506 non-null float64 RAD_6 506 non-null float64 RAD_7 506 non-null float64 TAX 506 non-null float64 PTRATIO 506 non-null float64 B 506 non-null float64 LSTAT 506 non-null float64 dtypes: float64(20), int64(1) memory usage: 83.1 KB None References ---------- .. [1] Contrast Coding Systems for Categorical Variables, from https://stats.idre.ucla.edu/r/library/r-library-contrast-coding-systems-for-categorical-variables/ .. [2] Gregory Carey (2003). Coding Categorical Variables, from http://psych.colorado.edu/~carey/Courses/PSYC5741/handouts/Coding%20Categorical%20Variables%202006-03-03.pdf """def__init__(self,verbose=0,cols=None,mapping=None,drop_invariant=False,return_df=True,handle_unknown='value',handle_missing='value'):self.return_df=return_dfself.drop_invariant=drop_invariantself.drop_cols=[]self.verbose=verboseself.mapping=mappingself.handle_unknown=handle_unknownself.handle_missing=handle_missingself.cols=colsself.ordinal_encoder=Noneself._dim=Noneself.feature_names=None
[docs]deffit(self,X,y=None,**kwargs):"""Fit encoder according to X and y. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape = [n_samples] Target values. Returns ------- self : encoder Returns self. """# if the input dataset isn't already a dataframe, convert it to one (using default column names)# first check the typeX=util.convert_input(X)self._dim=X.shape[1]# if columns aren't passed, just use every string columnifself.colsisNone:self.cols=util.get_obj_cols(X)else:self.cols=util.convert_cols_to_list(self.cols)ifself.handle_missing=='error':ifX[self.cols].isnull().any().any():raiseValueError('Columns to be encoded can not contain null')# train an ordinal pre-encoderself.ordinal_encoder=OrdinalEncoder(verbose=self.verbose,cols=self.cols,handle_unknown='value',handle_missing='value')self.ordinal_encoder=self.ordinal_encoder.fit(X)ordinal_mapping=self.ordinal_encoder.category_mappingmappings_out=[]forswitchinordinal_mapping:values=switch.get('mapping')col=switch.get('col')column_mapping=self.fit_sum_coding(col,values,self.handle_missing,self.handle_unknown)mappings_out.append({'col':switch.get('col'),'mapping':column_mapping,})self.mapping=mappings_outX_temp=self.transform(X,override_return_df=True)self.feature_names=X_temp.columns.tolist()# drop all output columns with 0 variance.ifself.drop_invariant:self.drop_cols=[]generated_cols=util.get_generated_cols(X,X_temp,self.cols)self.drop_cols=[xforxingenerated_colsifX_temp[x].var()<=10e-5]try:[self.feature_names.remove(x)forxinself.drop_cols]exceptKeyErrorase:ifself.verbose>0:print("Could not remove column from feature names.""Not found in generated cols.\n{}".format(e))returnself
[docs]deftransform(self,X,override_return_df=False):"""Perform the transformation to new categorical data. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- p : array, shape = [n_samples, n_numeric + N] Transformed values with encoding applied. """ifself.handle_missing=='error':ifX[self.cols].isnull().any().any():raiseValueError('Columns to be encoded can not contain null')ifself._dimisNone:raiseValueError('Must train encoder before it can be used to transform data.')# first check the typeX=util.convert_input(X)# then make sure that it is the right sizeifX.shape[1]!=self._dim:raiseValueError('Unexpected input dimension %d, expected %d'%(X.shape[1],self._dim,))ifnotlist(self.cols):returnXX=self.ordinal_encoder.transform(X)ifself.handle_unknown=='error':ifX[self.cols].isin([-1]).any().any():raiseValueError('Columns to be encoded can not contain new values')X=self.sum_coding(X,mapping=self.mapping)ifself.drop_invariant:forcolinself.drop_cols:X.drop(col,1,inplace=True)ifself.return_dforoverride_return_df:returnXelse:returnX.values
[docs]defget_feature_names(self):""" Returns the names of all transformed / added columns. Returns ------- feature_names: list A list with all feature names transformed or added. Note: potentially dropped features are not included! """ifnotisinstance(self.feature_names,list):raiseValueError("Estimator has to be fitted to return feature names.")else:returnself.feature_names