"""BaseX encoding"""importpandasaspdimportnumpyasnpimportmathimportrefromsklearn.baseimportBaseEstimator,TransformerMixinfromcategory_encoders.ordinalimportOrdinalEncoderimportcategory_encoders.utilsasutilimportwarnings__author__='willmcginnis'def_ceillogint(n,base):""" Returns ceil(log(n, base)) for integers n and base. Uses integer math, so the result is not subject to floating point rounding errors. base must be >= 2 and n must be >= 1. """ifbase<2:raiseValueError('base must be >= 2')ifn<1:raiseValueError('n must be >= 1')n-=1ret=0whilen>0:ret+=1n//=basereturnret
[docs]classBaseNEncoder(BaseEstimator,TransformerMixin):"""Base-N encoder encodes the categories into arrays of their base-N representation. A base of 1 is equivalent to one-hot encoding (not really base-1, but useful), a base of 2 is equivalent to binary encoding. N=number of actual categories is equivalent to vanilla ordinal encoding. 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). base: int when the downstream model copes well with nonlinearities (like decision tree), use higher base. 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 = BaseNEncoder(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 18 columns): CRIM 506 non-null float64 ZN 506 non-null float64 INDUS 506 non-null float64 CHAS_0 506 non-null int64 CHAS_1 506 non-null int64 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 int64 RAD_1 506 non-null int64 RAD_2 506 non-null int64 RAD_3 506 non-null int64 RAD_4 506 non-null int64 TAX 506 non-null float64 PTRATIO 506 non-null float64 B 506 non-null float64 LSTAT 506 non-null float64 dtypes: float64(11), int64(7) memory usage: 71.3 KB None """def__init__(self,verbose=0,cols=None,mapping=None,drop_invariant=False,return_df=True,base=2,handle_unknown='value',handle_missing='value'):self.return_df=return_dfself.drop_invariant=drop_invariantself.drop_cols=[]self.verbose=verboseself.handle_unknown=handle_unknownself.handle_missing=handle_missingself.cols=colsself.mapping=mappingself.ordinal_encoder=Noneself._dim=Noneself.base=baseself._encoded_columns=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)X=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)self.mapping=self.fit_base_n_encoding(X)# do a transform on the training data to get a column listX_temp=self.transform(X,override_return_df=True)self._encoded_columns=X_temp.columns.valuesself.feature_names=list(X_temp.columns)# 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_out=self.ordinal_encoder.transform(X)ifself.handle_unknown=='error':ifX_out[self.cols].isin([-1]).any().any():raiseValueError('Columns to be encoded can not contain new values')X_out=self.basen_encode(X_out,cols=self.cols)ifself.drop_invariant:forcolinself.drop_cols:X_out.drop(col,1,inplace=True)# impute missing values only in the generated columns# generated_cols = util.get_generated_cols(X, X_out, self.cols)# X_out[generated_cols] = X_out[generated_cols].fillna(value=0.0)ifself.return_dforoverride_return_df:returnX_outelse:returnX_out.values
[docs]definverse_transform(self,X_in):""" Perform the inverse transformation to encoded data. Parameters ---------- X_in : array-like, shape = [n_samples, n_features] Returns ------- p: array, the same size of X_in """# fail fastifself._dimisNone:raiseValueError('Must train encoder before it can be used to inverse_transform data')# unite the type into pandas dataframe (it makes the input size detection code easier...) and make deep copyX=util.convert_input(X_in,columns=self.feature_names,deep=True)X=self.basen_to_integer(X,self.cols,self.base)# make sure that it is the right sizeifX.shape[1]!=self._dim:ifself.drop_invariant:raiseValueError("Unexpected input dimension %d, the attribute drop_invariant should ""be False when transforming the data"%(X.shape[1],))else:raiseValueError('Unexpected input dimension %d, expected %d'%(X.shape[1],self._dim,))ifnotlist(self.cols):returnXifself.return_dfelseX.valuesforswitchinself.ordinal_encoder.mapping:column_mapping=switch.get('mapping')inverse=pd.Series(data=column_mapping.index,index=column_mapping.values)X[switch.get('col')]=X[switch.get('col')].map(inverse).astype(switch.get('data_type'))ifself.handle_unknown=='return_nan'andself.handle_missing=='return_nan':forcolinself.cols:ifX[switch.get('col')].isnull().any():warnings.warn("inverse_transform is not supported because transform impute ""the unknown category nan when encode %s"%(col,))returnXifself.return_dfelseX.values
[docs]defcalc_required_digits(self,values):# figure out how many digits we need to represent the classes presentifself.base==1:digits=len(values)+1else:digits=_ceillogint(len(values)+1,self.base)returndigits
[docs]defbasen_encode(self,X_in,cols=None):""" Basen encoding encodes the integers as basen code with one column per digit. Parameters ---------- X_in: DataFrame cols: list-like, default None Column names in the DataFrame to be encoded Returns ------- dummies : DataFrame """X=X_in.copy(deep=True)cols=X.columns.values.tolist()forswitchinself.mapping:col=switch.get('col')mod=switch.get('mapping')base_df=mod.reindex(X[col])base_df.set_index(X.index,inplace=True)X=pd.concat([base_df,X],axis=1)old_column_index=cols.index(col)cols[old_column_index:old_column_index+1]=mod.columnsreturnX.reindex(columns=cols)
[docs]defbasen_to_integer(self,X,cols,base):""" Convert basen code as integers. Parameters ---------- X : DataFrame encoded data cols : list-like Column names in the DataFrame that be encoded base : int The base of transform Returns ------- numerical: DataFrame """out_cols=X.columns.values.tolist()forcolincols:col_list=[col0forcol0inout_colsifre.match(str(col)+'_\\d+',str(col0))]insert_at=out_cols.index(col_list[0])ifbase==1:value_array=np.array([int(col0.split('_')[-1])forcol0incol_list])else:len0=len(col_list)value_array=np.array([base**(len0-1-i)foriinrange(len0)])X.insert(insert_at,col,np.dot(X[col_list].values,value_array.T))X.drop(col_list,axis=1,inplace=True)out_cols=X.columns.values.tolist()returnX
[docs]defcol_transform(self,col,digits):""" The lambda body to transform the column values """ifcolisNoneorfloat(col)<0.0:returnNoneelse:col=self.number_to_base(int(col),self.base,digits)iflen(col)==digits:returncolelse:return[0for_inrange(digits-len(col))]+col
[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('Must fit data first. Affected feature names are not known before.')else:returnself.feature_names