preprocess.py 109.8 KB
Newer Older
P
pycaret 已提交
1 2 3 4
# Module: Preprocess
# Author: Fahad Akbar <m.akbar@queensu.ca>
# License: MIT

P
PyCaret 已提交
5

P
pycaret 已提交
6 7 8 9 10 11 12 13
import pandas as pd
import numpy as np
import ipywidgets as wg 
from IPython.display import display
from ipywidgets import Layout
from sklearn.base import BaseEstimator , TransformerMixin
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
P
PyCaret 已提交
14 15
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import MaxAbsScaler
P
pycaret 已提交
16 17 18
from sklearn.preprocessing import PowerTransformer
from sklearn.preprocessing import QuantileTransformer
from sklearn.preprocessing import OneHotEncoder
P
PyCaret 已提交
19
from sklearn.preprocessing import OrdinalEncoder
P
pycaret 已提交
20
from sklearn.decomposition import PCA
P
PyCaret 已提交
21 22 23 24 25
from sklearn.decomposition import KernelPCA
from sklearn.cross_decomposition import PLSRegression
from sklearn.manifold import TSNE
from sklearn.decomposition import IncrementalPCA
from sklearn.preprocessing import KBinsDiscretizer
P
PyCaret 已提交
26 27 28 29
from pyod.models.knn import KNN
from pyod.models.iforest import IForest
from pyod.models.pca import PCA as PCA_od
from sklearn import cluster
P
PyCaret 已提交
30 31 32 33 34
from scipy import stats
from sklearn.ensemble import RandomForestClassifier as rfc
from sklearn.ensemble import RandomForestRegressor as rfr
from lightgbm import LGBMClassifier as lgbmc
from lightgbm import LGBMRegressor as lgbmr
P
pycaret 已提交
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
import sys 
from sklearn.pipeline import Pipeline
from sklearn import metrics
import datefinder
from datetime import datetime
import calendar
from sklearn.preprocessing import LabelEncoder
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_rows', 500)

#ignore warnings
import warnings
warnings.filterwarnings('ignore') 

#_____________________________________________________________________________________________________________________________

class DataTypes_Auto_infer(BaseEstimator,TransformerMixin):
  '''
    - This will try to infer data types automatically, option to override learent data types is also available.
    - This alos automatically delets duplicate columns (values or same colume name), removes rows where target variable is null and 
      remove columns and rows where all the records are null
  '''

  def __init__(self,target,ml_usecase,categorical_features=[],numerical_features=[],time_features=[],features_todrop=[],display_types=True): # nothing to define
    '''
    User to define the target (y) variable
      args:
        target: string, name of the target variable
        ml_usecase: string , 'regresson' or 'classification . For now, only supports two  class classification
        - this is useful in case target variable is an object / string . it will replace the strings with integers
        categorical_features: list of categorical features, default None, when None best guess will be used to identify categorical features
        numerical_features: list of numerical features, default None, when None best guess will be used to identify numerical features
        time_features: list of date/time features, default None, when None best guess will be used to identify date/time features    
  '''
    self.target = target
    self.ml_usecase= ml_usecase
    self.categorical_features =categorical_features
    self.numerical_features = numerical_features
    self.time_features =time_features
    self.features_todrop = features_todrop
    self.display_types = display_types
  
  def fit(self,dataset,y=None): # learning data types of all the columns
    '''
    Args: 
      data: accepts a pandas data frame
    Returns:
      Panda Data Frame
    '''
    data = dataset.copy()
    # remove sepcial char from column names
    #data.columns= data.columns.str.replace('[,]','')

    # we will take float as numberic, object as categorical from the begning
    # fir int64, we will check to see what is the proportion of unique counts to the total lenght of the data
    # if proportion is lower, then it is probabaly categorical 
    # however, proportion can be lower / disturebed due to samller denominator (total lenghth / number of samples)
    # so we will take the following chart
    # 0-50 samples, threshold is 24%
    # 50-100 samples, th is 12%
    # 50-250 samples , th is 4.8%
    # 250-500 samples, th is 2.4%
    # 500 and above 2% or belwo
   
P
PyCaret 已提交
99 100
    # # if there are inf or -inf then replace them with NaN
    # data.replace([np.inf,-np.inf],np.NaN,inplace=True)
P
pycaret 已提交
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
   
    # we canc check if somehow everything is object, we can try converting them in float
    for i in data.select_dtypes(include=['object']).columns:
      try:
        data[i] = data[i].astype('int64')
      except:
        None
    
    # if data type is bool , convert to categorical
    for i in data.columns:
      if data[i].dtype=='bool':
        data[i] = data[i].astype('object')
    

    # some times we have id column in the data set, we will try to find it and then  will drop it if found
    len_samples = len(data)
    self.id_columns = []
    for i in data.drop(self.target,axis=1).columns:
      if data[i].dtype in ['int64','float64']:
        if sum(data[i].isna()) == 0: 
          if len(data[i].unique()) == len_samples:
            min_number = min(data[i])
            max_number = max(data[i])
            arr = np.arange(min_number,max_number+1,1)
            try:
P
PyCaret 已提交
126
              all_match = sum(data[i].sort_values() == arr)
P
pycaret 已提交
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
              if all_match == len_samples:
                self.id_columns.append(i) 
            except:
              None 
    
    data_len = len(data)                        
        
    # wiith csv , if we have any null in  a colum that was int , panda will read it as float.
    # so first we need to convert any such floats that have NaN and unique values are lower than 20
    for i in data.drop(self.target,axis=1).columns:
      if data[i].dtypes == 'float64':
        # count how many Nas are there
        na_count = sum(data[i].isna())
        # count how many digits are there that have decimiles
        count_float = np.nansum([ False if r.is_integer() else True for r in data[i]])
        # total decimiels digits
        count_float = count_float - na_count # reducing it because we know NaN is counted as a float digit
        # now if there isnt any float digit , & unique levales are less than 20 and there are Na's then convert it to object
        if ( (count_float == 0) & (len(data[i].unique()) <=20) & (na_count>0) ):
          data[i] = data[i].astype('object')
        

    # should really be an absolute number say 20
    # length = len(data.iloc[:,0])
    # if length in range(0,51):
    #   th=.25
    # elif length in range(51,101):
    #   th=.12
    # elif length in range(101,251):
    #   th=.048
    # elif length in range(251,501):
    #   th=.024
    # elif length > 500:
    #   th=.02

    # if column is int and unique counts are more than two, then: (exclude target)
    for i in data.drop(self.target,axis=1).columns:
      if data[i].dtypes == 'int64': #((data[i].dtypes == 'int64') & (len(data[i].unique())>2))
        if len(data[i].unique()) <=20: #hard coded
          data[i]= data[i].apply(str)
        else:
          data[i]= data[i].astype('float64')


    # # if colum is objfloat  and only have two unique counts , this is probabaly one hot encoded
    # # make it object
    for i in data.columns:
      if ((data[i].dtypes == 'float64') & (len(data[i].unique())==2)):
        data[i]= data[i].apply(str)
    
    
    #for time & dates
    #self.drop_time = [] # for now we are deleting time columns
    for i in data.drop(self.target,axis=1).columns:
      # we are going to check every first row of every column and see if it is a date
      match = datefinder.find_dates(data[i].values[0]) # to get the first value
      try:
        for m in match:
          if isinstance(m, datetime) == True:
            data[i] = pd.to_datetime(data[i])
            #self.drop_time.append(i)  # for now we are deleting time columns
      except:
        continue

    # now in case we were given any specific columns dtypes in advance , we will over ride theos 
    if len(self.categorical_features) > 0:
      for i in self.categorical_features:
P
PyCaret 已提交
194 195 196 197 198
        try:
          data[i]=data[i].apply(str)
        except:
          data[i]=dataset[i].apply(str)

P
pycaret 已提交
199 200
    if len(self.numerical_features) > 0:
      for i in self.numerical_features:
P
PyCaret 已提交
201 202 203 204
        try:
          data[i]=data[i].astype('float64')
        except:
          data[i]=dataset[i].astype('float64')
P
pycaret 已提交
205 206 207
    
    if len(self.time_features) > 0:
      for i in self.time_features:
P
PyCaret 已提交
208 209 210 211
        try:
          data[i]=pd.to_datetime(data[i])
        except:
          data[i]=pd.to_datetime(dataset[i])
P
pycaret 已提交
212 213 214 215

    # table of learent types
    self.learent_dtypes = data.dtypes
    #self.training_columns = data.drop(self.target,axis=1).columns
P
PyCaret 已提交
216 217 218 219
    
    # if there are inf or -inf then replace them with NaN
    data.replace([np.inf,-np.inf],np.NaN,inplace=True)
    
P
pycaret 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    # lets remove duplicates
    # remove duplicate columns (columns with same values)
    #(too expensive on bigger data sets)
    # data_c = data.T.drop_duplicates()
    # data = data_c.T
    #remove columns with duplicate name 
    data = data.loc[:,~data.columns.duplicated()]
    # Remove NAs
    data.dropna(axis=0, how='all', inplace=True)
    data.dropna(axis=1, how='all', inplace=True)
    # remove the row if target column has NA
    data = data[~data[self.target].isnull()]
            

    #self.training_columns = data.drop(self.target,axis=1).columns

    # since due to transpose , all data types have changed, lets change the dtypes to original---- not required any more since not transposing any more
    # for i in data.columns: # we are taking all the columns in test , so we dot have to worry about droping target column
    #   data[i] = data[i].astype(self.learent_dtypes[self.learent_dtypes.index==i])
    
    if self.display_types == True:
P
PyCaret 已提交
241
      display(wg.Text(value="Following data types have been inferred automatically, if they are correct press enter to continue or type 'quit' otherwise.",layout =Layout(width='100%')),display_id='m1')
P
pycaret 已提交
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
      
      dt_print_out = pd.DataFrame(self.learent_dtypes, columns=['Feature_Type'])
      dt_print_out['Data Type'] = ""
      
      for i in dt_print_out.index:
        if i != self.target:
          if dt_print_out.loc[i,'Feature_Type'] == 'object':
            dt_print_out.loc[i,'Data Type'] = 'Categorical'
          elif dt_print_out.loc[i,'Feature_Type'] == 'float64':
            dt_print_out.loc[i,'Data Type'] = 'Numeric'
          elif dt_print_out.loc[i,'Feature_Type'] == 'datetime64[ns]':
            dt_print_out.loc[i,'Data Type'] = 'Date'
          #elif dt_print_out.loc[i,'Feature_Type'] == 'int64':
          #  dt_print_out.loc[i,'Data Type'] = 'Categorical'
        else:
          dt_print_out.loc[i,'Data Type'] = 'Label'

      # for ID column:
      for i in dt_print_out.index:
        if i in self.id_columns:
          dt_print_out.loc[i,'Data Type'] = 'ID Column'
      
      # if we added the dummy  target column , then drop it 
      dt_print_out.drop(index='dummy_target',errors='ignore',inplace=True)
      # drop any columns that were asked to drop
      dt_print_out.drop(index=self.features_todrop,errors='ignore',inplace=True)


      display(dt_print_out[['Data Type']])
      self.response = input()
P
PyCaret 已提交
272
      
P
pycaret 已提交
273 274 275

      if self.response in ['quit','Quit','exit','EXIT','q','Q','e','E','QUIT','Exit']:
        sys.exit('Read the documentation of setup to learn how to overwrite data types over the inferred types. setup function must run again before you continue modeling.')
P
PyCaret 已提交
276 277
      
      
P
pycaret 已提交
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
    # drop time columns
    #data.drop(self.drop_time,axis=1,errors='ignore',inplace=True)

    # drop id columns
    data.drop(self.id_columns,axis=1,errors='ignore',inplace=True)
    
    return(data)
  
  def transform(self,dataset,y=None):
    '''
      Args: 
        data: accepts a pandas data frame
      Returns:
        Panda Data Frame
    '''
    data = dataset.copy()
    # remove sepcial char from column names
    #data.columns= data.columns.str.replace('[,]','')

    #very first thing we need to so is to check if the training and test data hace same columns
    #exception checking   
    import sys

    for i in self.final_training_columns:  
      if i not in data.columns:
        sys.exit('(Type Error): test data does not have column ' + str(i) + " which was used for training")

    ## we only need to take test columns that we used in ttaining (test in production may have a lot more columns)
    data = data[self.final_training_columns]

    
    # just keep picking the data and keep applying to the test data set (be mindful of target variable)
    for i in data.columns: # we are taking all the columns in test , so we dot have to worry about droping target column
      data[i] = data[i].astype(self.learent_dtypes[self.learent_dtypes.index==i])
    
    # drop time columns
    #data.drop(self.drop_time,axis=1,errors='ignore',inplace=True)

    # drop id columns
    data.drop(self.id_columns,axis=1,errors='ignore',inplace=True)

     # drop custome columns
    data.drop(self.features_todrop,axis=1,errors='ignore',inplace=True)
    
    return(data)

  # fit_transform
  def fit_transform(self,dataset,y=None):

    data= dataset.copy()
    # since this is for training , we dont nees any transformation since it has already been transformed in fit
    data = self.fit(data)

    # additionally we just need to treat the target variable
    # for ml use ase
    if ((self.ml_usecase == 'classification') &  (data[self.target].dtype=='object')):
      le = LabelEncoder()
      data[self.target] = le.fit_transform(np.array(data[self.target]))

      # now get the replacement dict
      rev= le.inverse_transform(range(0,len(le.classes_)))
      rep = np.array(range(0,len(le.classes_)))
      self.replacement={}
      for i,k in zip(rev,rep):
        self.replacement[i] = k

      # self.u = list(pd.unique(data[self.target]))
      # self.replacement = np.arange(0,len(self.u))
      # data[self.target]= data[self.target].replace(self.u,self.replacement)
      # data[self.target] = data[self.target].astype('int64')
      # self.replacement = pd.DataFrame(dict(target_variable=self.u,replaced_with=self.replacement))

    
    # drop time columns
    #data.drop(self.drop_time,axis=1,errors='ignore',inplace=True)

    # drop id columns
    data.drop(self.id_columns,axis=1,errors='ignore',inplace=True)

    # drop custome columns
    data.drop(self.features_todrop,axis=1,errors='ignore',inplace=True)
    
    # finally save a list of columns that we would need from test data set
    self.final_training_columns = data.drop(self.target,axis=1).columns

    
    return(data)
# _______________________________________________________________________________________________________________________
# Imputation
class Simple_Imputer(BaseEstimator,TransformerMixin):
  '''
    Imputes all type of data (numerical,categorical & Time).
      Highly recommended to run Define_dataTypes class first
      Numerical values can be imputed with mean or median 
      categorical missing values will be replaced with "Other"
      Time values are imputed with the most frequesnt value
      Ignores target (y) variable    
      Args: 
        Numeric_strategy: string , all possible values {'mean','median'}
        categorical_strategy: string , all possible values {'not_available','most frequent'}
        target: string , name of the target variable

  '''

  def __init__(self,numeric_strategy,categorical_strategy,target_variable):
    self.numeric_strategy = numeric_strategy
    self.target = target_variable
    self.categorical_strategy = categorical_strategy
  
  def fit(self,dataset,y=None): #
    data = dataset.copy()
    # make a table for numerical variable with strategy stats
    if self.numeric_strategy == 'mean':
      self.numeric_stats = data.drop(self.target,axis=1).select_dtypes(include=['float64','int64']).apply(np.nanmean)
    else:
      self.numeric_stats = data.drop(self.target,axis=1).select_dtypes(include=['float64','int64']).apply(np.nanmedian)

    self.numeric_columns = data.drop(self.target,axis=1).select_dtypes(include=['float64','int64']).columns

    #for Catgorical , 
    if self.categorical_strategy == 'most frequent':
      self.categorical_columns = data.drop(self.target,axis=1).select_dtypes(include=['object']).columns
      self.categorical_stats = pd.DataFrame(columns=self.categorical_columns) # place holder
      for i in (self.categorical_stats.columns):
        self.categorical_stats.loc[0,i] = data[i].value_counts().index[0]
    else:
      self.categorical_columns = data.drop(self.target,axis=1).select_dtypes(include=['object']).columns
    
    # for time, there is only one way, pick up the most frequent one
    self.time_columns = data.drop(self.target,axis=1).select_dtypes(include=['datetime64[ns]']).columns
    self.time_stats = pd.DataFrame(columns=self.time_columns) # place holder
    for i in (self.time_columns):
      self.time_stats.loc[0,i] = data[i].value_counts().index[0]
    return(data)

      
  
  def transform(self,dataset,y=None):
    data = dataset.copy() 
    # for numeric columns
    for i,s in zip(data[self.numeric_columns].columns,self.numeric_stats):
      data[i].fillna(s,inplace=True)
    
    # for categorical columns
    if self.categorical_strategy == 'most frequent':
      for i in (self.categorical_stats.columns):
        #data[i].fillna(self.categorical_stats.loc[0,i],inplace=True)
        data[i] = data[i].fillna(self.categorical_stats.loc[0,i])
        data[i] = data[i].apply(str)    
    else: # this means replace na with "not_available"
      for i in (self.categorical_columns):
        data[i].fillna("not_available",inplace=True)
        data[i] = data[i].apply(str)
    # for time
    for i in (self.time_stats.columns):
        data[i].fillna(self.time_stats.loc[0,i],inplace=True)
    
    return(data)
  
  def fit_transform(self,dataset,y=None):
    data = dataset.copy() 
    data= self.fit(data)
    return(self.transform(data))

# _______________________________________________________________________________________________________________________
# Imputation with surrogate columns
class Surrogate_Imputer(BaseEstimator,TransformerMixin):
  '''
    Imputes feature with surrogate column (numerical,categorical & Time).
      - Highly recommended to run Define_dataTypes class first
      - it is also recommended to only apply this to features where it makes business sense to creat surrogate column
      - feature name has to be provided
      - only able to handle one feature at a time
      - Numerical values can be imputed with mean or median 
      - categorical missing values will be replaced with "Other"
      - Time values are imputed with the most frequesnt value
      - Ignores target (y) variable    
      Args: 
        feature_name: string, provide features name
        feature_type: string , all possible values {'numeric','categorical','date'}
        strategy: string ,all possible values {'mean','median','not_available','most frequent'}
        target: string , name of the target variable

  '''
  def __init__(self,numeric_strategy,categorical_strategy,target_variable):
    self.numeric_strategy = numeric_strategy
    self.target = target_variable
    self.categorical_strategy = categorical_strategy
  
  def fit(self,dataset,y=None): #
    data = dataset.copy()
    # make a table for numerical variable with strategy stats
    if self.numeric_strategy == 'mean':
      self.numeric_stats = data.drop(self.target,axis=1).select_dtypes(include=['float64','int64']).apply(np.nanmean)
    else:
      self.numeric_stats = data.drop(self.target,axis=1).select_dtypes(include=['float64','int64']).apply(np.nanmedian)

    self.numeric_columns = data.drop(self.target,axis=1).select_dtypes(include=['float64','int64']).columns
    # also need to learn if any columns had NA in training
    self.numeric_na = pd.DataFrame(columns=self.numeric_columns)
    for i in self.numeric_columns:
      if data[i].isna().any() == True:
        self.numeric_na.loc[0,i] = True
      else:
        self.numeric_na.loc[0,i] = False 

    #for Catgorical , 
    if self.categorical_strategy == 'most frequent':
      self.categorical_columns = data.drop(self.target,axis=1).select_dtypes(include=['object']).columns
      self.categorical_stats = pd.DataFrame(columns=self.categorical_columns) # place holder
      for i in (self.categorical_stats.columns):
        self.categorical_stats.loc[0,i] = data[i].value_counts().index[0]
      # also need to learn if any columns had NA in training, but this is only valid if strategy is "most frequent"
      self.categorical_na = pd.DataFrame(columns=self.categorical_columns)
      for i in self.categorical_columns:
        if sum(data[i].isna()) > 0:
          self.categorical_na.loc[0,i] = True
        else:
          self.categorical_na.loc[0,i] = False        
    else:
      self.categorical_columns = data.drop(self.target,axis=1).select_dtypes(include=['object']).columns
      self.categorical_na = pd.DataFrame(columns=self.categorical_columns)
      self.categorical_na.loc[0,:] = False #(in this situation we are not making any surrogate column)
    
    # for time, there is only one way, pick up the most frequent one
    self.time_columns = data.drop(self.target,axis=1).select_dtypes(include=['datetime64[ns]']).columns
    self.time_stats = pd.DataFrame(columns=self.time_columns) # place holder
    self.time_na = pd.DataFrame(columns=self.time_columns)
    for i in (self.time_columns):
      self.time_stats.loc[0,i] = data[i].value_counts().index[0]
    
    # learn if time columns were NA
    for i in self.time_columns:
      if data[i].isna().any() == True:
        self.time_na.loc[0,i] = True
      else:
        self.time_na.loc[0,i] = False
    
    return(data) # nothing to return

      
  
  def transform(self,dataset,y=None):
    data = dataset.copy() 
    # for numeric columns
    for i,s in zip(data[self.numeric_columns].columns,self.numeric_stats):
      array = data[i].isna()
      data[i].fillna(s,inplace=True)
      # make a surrogate column if there was any
      if self.numeric_na.loc[0,i] == True:
        data[i+"_surrogate"]= array
        # make it string
        data[i+"_surrogate"]= data[i+"_surrogate"].apply(str)

    
    # for categorical columns
    if self.categorical_strategy == 'most frequent':
      for i in (self.categorical_stats.columns):
        #data[i].fillna(self.categorical_stats.loc[0,i],inplace=True)
        array = data[i].isna()
        data[i] = data[i].fillna(self.categorical_stats.loc[0,i])
        data[i] = data[i].apply(str)  
        # make surrogate column
        if self.categorical_na.loc[0,i] == True:
          data[i+"_surrogate"]= array
          # make it string
          data[i+"_surrogate"]= data[i+"_surrogate"].apply(str)
    else: # this means replace na with "not_available"
      for i in (self.categorical_columns):
        data[i].fillna("not_available",inplace=True)
        data[i] = data[i].apply(str)
        # no need to make surrogate since not_available is itself a new colum
    
    # for time
    for i in (self.time_stats.columns):
      array = data[i].isna()
      data[i].fillna(self.time_stats.loc[0,i],inplace=True)
      # make surrogate column
      if self.time_na.loc[0,i] == True:
        data[i+"_surrogate"]= array
        # make it string
        data[i+"_surrogate"]= data[i+"_surrogate"].apply(str)
    
    return(data)
  
  def fit_transform(self,dataset,y=None):
    data = dataset.copy()
    data= self.fit(data)
    return(self.transform(data))
# _______________________________________________________________________________________________________________________
P
PyCaret 已提交
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
# Zero and Near Zero Variance
class Zroe_NearZero_Variance(BaseEstimator,TransformerMixin):
  '''
    - it eliminates the features having zero variance
    - it eliminates the features haveing near zero variance
    - Near zero variance is determined by 
      -1) Count of unique points divided by the total length of the feature has to be lower than a pre sepcified threshold 
      -2) Most common point(count) divided by the second most common point(count) in the feature is greater than a pre specified threshold
      Once both conditions are met , the feature is dropped  
    -Ignores target variable
      
      Args: 
        threshold_1: float (between 0.0 to 1.0) , default is .10 
        threshold_2: int (between 1 to 100), default is 20 
        tatget variable : string, name of the target variable

  '''

  def __init__(self,target,threshold_1=0.1,threshold_2=20):
    self.threshold_1 = threshold_1
    self.threshold_2 = threshold_2
    self.target = target
  
  def fit(self,dataset,y=None): # from training data set we are going to learn what columns to drop
    data = dataset.copy()
    self.to_drop= []
    self.sampl_len = len(data[self.target])
    for i in data.drop(self.target,axis=1).columns:
      # get the number of unique counts
      u = pd.DataFrame( data[i].value_counts()).sort_values(by=i,ascending=False, inplace=False)
      # take len of u and divided it by the total sample numbers, so this will check the 1st rule , has to be low say 10%
      #import pdb; pdb.set_trace()
      first=len(u)/self.sampl_len
      # then check if most common divided by 2nd most common ratio is 20 or more
      if len(u[i]) == 1: # this means that if column is non variance , automatically make the number big to drop it
        second=100
      else:
        second = u.iloc[0,0]/u.iloc[1,0]
    # if both conditions are true then drop the column, however, we dont want to alter column that indicate NA's
      if ((first <= 0.10) and (second >=20) and (i[-10:]!='_surrogate')):
        self.to_drop.append(i) 
    # now drop if the column has zero variance
      if (((second ==100) and (i[-10:]!='_surrogate'))):
        self.to_drop.append(i) 

  
  def transform(self,dataset,y=None): # since it is only for training data set , nothing here
    data= dataset.copy()
    data.drop(self.to_drop,axis=1,inplace=True)
    return(data)
  
  def fit_transform(self,dataset,y=None):
    data= dataset.copy()
    self.fit(data)
    return(self.transform(data))
#____________________________________________________________________________________________________________________________
# rare catagorical variables
class Catagorical_variables_With_Rare_levels(BaseEstimator,TransformerMixin):
  '''
    -Merges levels in catagorical features with more frequent level  if they appear less than a threshold count 
      e.g. Col=[a,a,a,a,b,b,c,c]
      if threshold is set to 2 , then c will be mrged with b because both are below threshold
      There has to be atleast two levels belwo threshold for this to work 
      the process will keep going until all the levels have atleast 2(threshold) counts
    -Only handles catagorical features
    -It is recommended to run the Zroe_NearZero_Variance and Define_dataTypes first
    -Ignores target variable 
      Args: 
        threshold: int , default 10
        target: string , name of the target variable
        new_level_name: string , name given to the new level generated, default 'others'

  '''

  def __init__(self,target,new_level_name='others_infrequent',threshold=.05):
    self.threshold = threshold
    self.target = target
    self.new_level_name = new_level_name
  def fit(self,dataset,y=None): # we will learn for what columnns what are the level to merge as others
    # every level of the catagorical feature has to be more than threshols, if not they will be clubed togather as "others"
    # in order to apply, there should be atleast two levels belwo the threshold ! 
    # creat a place holder
    data = dataset.copy()
    self.ph = pd.DataFrame(columns=data.drop(self.target,axis=1).select_dtypes(include="object").columns)
    #ph.columns = df.columns# catagorical only 
    for i in data[self.ph.columns].columns:
        # determine the infrequebt count
        v_c = data[i].value_counts()
        count_th = round(v_c.quantile(self.threshold))
        a = np.sum(pd.DataFrame(data[i].value_counts().sort_values()) [i]  <= count_th)
        if a >= 2: # rare levels has to be atleast two
          count = pd.DataFrame( data[i].value_counts().sort_values())
          count.columns = ['fre']
          count = count[count['fre']<=count_th]
          to_club = list(count.index)
          self.ph.loc[0,i] = to_club
        else:
          self.ph.loc[0,i] = []
    # # also need to make a place holder that keep records of all the levels , and in case a new level appears in test we will change it to others
    # self.ph_level = pd.DataFrame(columns=data.drop(self.target,axis=1).select_dtypes(include="object").columns)
    # for i in self.ph_level.columns:
    #   self.ph_level.loc[0,i] = list(data[i].value_counts().sort_values().index)

  
  def transform(self,dataset,y=None): # 
    # transorm 
    data = dataset.copy()
    for i in data[self.ph.columns].columns:
      t_replace = self.ph.loc[0,i]
      data[i].replace(to_replace=t_replace,value=self.new_level_name,inplace=True)
    return(data)
  
  def fit_transform(self,dataset,y=None):
    data = dataset.copy()
    self.fit(data)
    return(self.transform(data))

P
PyCaret 已提交
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
# _______________________________________________________________________________________________________________________
# new catagorical level in test
class New_Catagorical_Levels_in_TestData(BaseEstimator,TransformerMixin):
  '''
    -This treats if a new level appears in the test dataset catagorical's feature (i.e a level on whihc model was not trained previously) 
    -It simply replaces the new level in test data set with the most frequent or least frequent level in the same feature in the training data set
    -It is recommended to run the Zroe_NearZero_Variance and Define_dataTypes first
    -Ignores target variable 
      Args: 
        target: string , name of the target variable
        replacement_strategy:string , 'least frequent' or 'most frequent' (default 'most frequent' )

  '''

  def __init__(self,target,replacement_strategy='most frequent'):
    self.target = target
    self.replacement_strategy = replacement_strategy

  def fit(self,data,y=None): 
    # need to make a place holder that keep records of all the levels , and in case a new level appears in test we will change it to others
    self.ph_train_level = pd.DataFrame(columns=data.drop(self.target,axis=1).select_dtypes(include="object").columns)
    for i in self.ph_train_level.columns:
      if self.replacement_strategy == "least frequent": 
        self.ph_train_level.loc[0,i] = list(data[i].value_counts().sort_values().index)
      else:
        self.ph_train_level.loc[0,i] = list(data[i].value_counts().index)

  
  def transform(self,data,y=None): # 
    # transorm 
    # we need to learn the same for test data , and then we will compare to check what levels are new in there
    self.ph_test_level = pd.DataFrame(columns=data.drop(self.target,axis=1,errors='ignore').select_dtypes(include="object").columns)
    for i in self.ph_test_level.columns:
        self.ph_test_level.loc[0,i] = list(data[i].value_counts().sort_values().index)
    
    # new we have levels for both test and train, we will start comparing and replacing levels in test set (Only if test set has new levels)
    for i in self.ph_test_level.columns:
      new = list((set(self.ph_test_level.loc[0,i]) - set(self.ph_train_level.loc[0,i])))
      # now if there is a difference , only then replace it 
      if len(new) > 0 :
        data[i].replace(new,self.ph_train_level.loc[0,i][0],inplace=True)

    return(data)
  
  def fit_transform(self,data,y=None): #There is no transformation happening in training data set, its all about test 
    self.fit(data)
    return(data)


# _______________________________________________________________________________________________________________________
# Group akin features
class Group_Similar_Features(BaseEstimator,TransformerMixin):
  '''
    - Given a list of features , it creates aggregate features 
    - features created are Min, Max, Mean, Median, Mode & Std
    - Only works on numerical features
      Args: 
        list_of_similar_features: list of list, string , e.g. [['col',col2],['col3','col4']]
        group_name: list, group name/names to be added as prefix to aggregate features, e.g ['gorup1','group2']
  '''

  def __init__(self,group_name=[],list_of_grouped_features=[[]]):
    self.list_of_similar_features = list_of_grouped_features
    self.group_name = group_name
    # if list of list not given
    try:
      np.array(self.list_of_similar_features).shape[0]
    except:
      raise("Group_Similar_Features: list_of_grouped_features is not provided as list of list")
      
  
  def fit(self,data,y=None):
    # nothing to learn
      return(None)

  def transform(self,dataset,y=None):
    data = dataset.copy()
    # # only going to process if there is an actual missing value in training data set
    if len(self.list_of_similar_features) > 0:
      for f,g in zip(self.list_of_similar_features,self.group_name): 
        data[g+'_Min'] = data[f].apply(np.min,1)
        data[g+'_Max'] = data[f].apply(np.max,1)
        data[g+'_Mean'] = data[f].apply(np.mean,1)
        data[g+'_Median'] = data[f].apply(np.median,1)
        data[g+'_Mode'] = stats.mode(data[f],1)[0]
        data[g+'_Std'] = data[f].apply(np.std,1)
        
      return(data)
    else:
      return(data)

  def fit_transform(self,data,y=None):
    self.fit(data)
    return(self.transform(data))
    
P
PyCaret 已提交
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

#____________________________________________________________________________________________________________________________________________________________________
# Binning for Continious
class Binning(BaseEstimator,TransformerMixin):
  '''
    - Converts numerical variables to catagorical variable through binning
    - Number of binns are automitically determined through Sturges method
    - Once discretize, original feature will be dropped
        Args:
            features_to_discretize: list of featur names to be binned

  '''

  def __init__(self, features_to_discretize):
    self.features_to_discretize =features_to_discretize
    return(None)

  def fit(self,data,y=None):
    return(None)

  def transform(self,dataset,y=None):
    data = dataset.copy()
    #only do if features are provided
    if len(self.features_to_discretize) > 0:
      data_t = self.disc.transform(np.array(data[self.features_to_discretize]).reshape(-1,self.len_columns))
      # make pandas data frame
      data_t = pd.DataFrame(data_t,columns=self.features_to_discretize,index=data.index)
      # all these columns are catagorical
      data_t = data_t.astype(str)
      # drop original columns
      data.drop(self.features_to_discretize,axis=1,inplace=True)
      # add newly created columns
      data = pd.concat((data,data_t),axis=1)
    return(data)

  def fit_transform(self,dataset,y=None):
    data = dataset.copy()
    # only do if features are given

    if len(self.features_to_discretize) > 0:

      # place holder for all the features for their binns  
      self.binns = []
      for i in self.features_to_discretize:
        # get numbr of binns
        hist, bin_edg = np.histogram(data[i],bins='sturges')
        self.binns.append(len(hist))

      # how many colums to deal with
      self.len_columns = len(self.features_to_discretize)
      # now do fit transform 
      self.disc = KBinsDiscretizer(n_bins=self.binns, encode='ordinal', strategy='kmeans')
      data_t = self.disc.fit_transform(np.array(data[self.features_to_discretize]).reshape(-1,self.len_columns))
      # make pandas data frame
      data_t = pd.DataFrame(data_t,columns=self.features_to_discretize,index=data.index)
      # all these columns are catagorical
      data_t = data_t.astype(str)
      # drop original columns
      data.drop(self.features_to_discretize,axis=1,inplace=True)
      # add newly created columns
      data = pd.concat((data,data_t),axis=1)

    return(data)
# ______________________________________________________________________________________________________________________
P
pycaret 已提交
844 845 846 847 848 849 850 851
# Scaling & Power Transform
class Scaling_and_Power_transformation(BaseEstimator,TransformerMixin):
  '''
    -Given a data set, applies Min Max, Standar Scaler or Power Transformation (yeo-johnson)
    -it is recommended to run Define_dataTypes first
    - ignores target variable 
      Args: 
        target: string , name of the target variable
P
PyCaret 已提交
852
        function_to_apply: string , default 'zscore' (standard scaler), all other {'minmaxm','yj','quantile','robust','maxabs'} ( min max,yeo-johnson & quantile power transformation, robust and MaxAbs scaler )
P
pycaret 已提交
853 854 855

  '''

P
PyCaret 已提交
856
  def __init__(self,target,function_to_apply='zscore',random_state_quantile=42):
P
pycaret 已提交
857 858 859
    self.target = target
    self.function_to_apply = function_to_apply
    self.random_state_quantile = random_state_quantile
P
PyCaret 已提交
860 861
    # self.transform_target = transform_target
    # self.ml_usecase = ml_usecase
P
pycaret 已提交
862 863
  
  def fit(self,dataset,y=None):
P
PyCaret 已提交
864 865
    
    data=dataset.copy()
P
pycaret 已提交
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
    # we only want to apply if there are numeric columns
    self.numeric_features = data.drop(self.target,axis=1,errors='ignore').select_dtypes(include=["float64",'int64']).columns
    if len(self.numeric_features) > 0:
      if self.function_to_apply == 'zscore':
        self.scale_and_power = StandardScaler()
        self.scale_and_power.fit(data[self.numeric_features])
      elif  self.function_to_apply == 'minmax':
        self.scale_and_power = MinMaxScaler()
        self.scale_and_power.fit(data[self.numeric_features])
      elif  self.function_to_apply == 'yj':
        self.scale_and_power = PowerTransformer(method='yeo-johnson',standardize=False)
        self.scale_and_power.fit(data[self.numeric_features])
      elif  self.function_to_apply == 'quantile':
        self.scale_and_power = QuantileTransformer(random_state=self.random_state_quantile,output_distribution='normal')
        self.scale_and_power.fit(data[self.numeric_features])
P
PyCaret 已提交
881 882 883 884 885 886
      elif  self.function_to_apply == 'robust':
        self.scale_and_power = RobustScaler()
        self.scale_and_power.fit(data[self.numeric_features])
      elif  self.function_to_apply == 'maxabs':
        self.scale_and_power = MaxAbsScaler()
        self.scale_and_power.fit(data[self.numeric_features])
P
pycaret 已提交
887 888 889 890 891

      else:
        return(None)
    else:
      return(None)
P
PyCaret 已提交
892
    
P
pycaret 已提交
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909

  
  def transform(self,dataset,y=None):
    data = dataset.copy()
    
    if len(self.numeric_features) > 0:
      self.data_t = pd.DataFrame(self.scale_and_power.transform(data[self.numeric_features]))
      # we need to set the same index as original data
      self.data_t.index = data.index
      self.data_t.columns = self.numeric_features
      for i in self.numeric_features:
        data[i]= self.data_t[i]
      return(data)
    
    else:
      return(data) 

P
PyCaret 已提交
910 911
  def fit_transform(self,dataset,y=None):
    data = dataset.copy()
P
pycaret 已提交
912
    self.fit(data)
P
PyCaret 已提交
913 914
    # convert target if appropriate
    # default behavious is quantile transformer
P
PyCaret 已提交
915 916 917
    # if ((self.ml_usecase == 'regression') and (self.transform_target == True)):
    #   self.scale_and_power_target = QuantileTransformer(random_state=self.random_state_quantile,output_distribution='normal')
    #   data[self.target]=self.scale_and_power_target.fit_transform(np.array(data[self.target]).reshape(-1,1))
P
PyCaret 已提交
918
      
P
pycaret 已提交
919
    return(self.transform(data))
P
PyCaret 已提交
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

# ______________________________________________________________________________________________________________________
# Scaling & Power Transform
class Target_Transformation(BaseEstimator,TransformerMixin):
  '''
    - Applies Power Transformation (yeo-johnson , Box-Cox) to target variable (Applicable to Regression only)
      - 'bc' for Box_Coc & 'yj' for yeo-johnson, default is Box-Cox
    - if target containes negtive / zero values , yeo-johnson is automatically selected 
    
  '''

  def __init__(self,target,function_to_apply='bc'):
    self.target = target
    self.function_to_apply = function_to_apply
    if self.function_to_apply == 'bc':
      self.function_to_apply = 'box-cox'
    else:
      self.function_to_apply = 'yeo-johnson'

  
  def fit(self,dataset,y=None):
    return(None)
    

  
  def transform(self,dataset,y=None):
    return(dataset) 

  def fit_transform(self,dataset,y=None):
    data = dataset.copy()
    # if target has zero or negative values use yj instead
    if any(data[self.target]<= 0):
      self.function_to_apply = 'yeo-johnson'
    # apply transformation
    self.p_transform_target = PowerTransformer(method=self.function_to_apply)
    data[self.target]=self.p_transform_target.fit_transform(np.array(data[self.target]).reshape(-1,1))
      
    return(data)
P
pycaret 已提交
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
# __________________________________________________________________________________________________________________________
# Time feature extractor
class Make_Time_Features(BaseEstimator,TransformerMixin):
  '''
    -Given a time feature , it extracts more features
    - Only accepts / works where feature / data type is datetime64[ns]
    - full list of features is:
      ['month','weekday',is_month_end','is_month_start','hour']
    - all extracted features are defined as string / object
    -it is recommended to run Define_dataTypes first
      Args: 
        time_feature: list of feature names as datetime64[ns] , default empty/none , if empty/None , it will try to pickup dates automatically where data type is datetime64[ns]
        list_of_features: list of required features , default value ['month','weekday','is_month_end','is_month_start','hour']

  '''

  def __init__(self,time_feature=[],list_of_features=['month','weekday','is_month_end','is_month_start','hour']):
    self.time_feature = time_feature
    self.list_of_features_o = list_of_features
    return(None)

  def fit(self,data,y=None):

    return(None)

  def transform(self,dataset,y=None):
    data = dataset.copy()

    # run fit transform first

    # start making features for every column in the time list
    for i in self.time_feature:
      # make month column if month is choosen
      if 'month' in self.list_of_features_o:
        data[i+"_month"] = [datetime.date(r).month for r in data[i]]
        data[i+"_month"] = data[i+"_month"].apply(str)

      # make weekday column if weekday is choosen ( 0 for monday 6 for sunday)
      if 'weekday' in self.list_of_features_o:
        data[i+"_weekday"] = [datetime.weekday(r) for r in data[i]]
        data[i+"_weekday"] = data[i+"_weekday"].apply(str)
      
      # make Is_month_end column  choosen
      if 'is_month_end' in self.list_of_features_o:
        data[i+"_is_month_end"] = [ 1 if calendar.monthrange(datetime.date(r).year,datetime.date(r).month)[1] == datetime.date(r).day  else 0 for r in data[i] ]
        data[i+"_is_month_end"] = data[i+"_is_month_end"].apply(str)
        
      
      # make Is_month_start column if choosen
      if 'is_month_start' in self.list_of_features_o:
        data[i+"_is_month_start"] = [ 1 if datetime.date(r).day == 1 else 0 for r in data[i] ]
        data[i+"_is_month_start"] = data[i+"_is_month_start"].apply(str)
      
      # make hour column if choosen
      if 'hour' in self.list_of_features_o:
        h = [ datetime.time(r).hour for r in data[i] ]
        if sum(h) > 0:  
          data[i+"_hour"] = h
          data[i+"_hour"] = data[i+"_hour"].apply(str)
    
    # we dont need time columns any more 
    data.drop(self.time_feature,axis=1,inplace=True)

    return(data)

  def fit_transform(self,dataset,y=None):
    data = dataset.copy()
    # if no columns names are given , then pick datetime columns
    if len(self.time_feature) == 0 :
      self.time_feature = [i for i in data.columns if data[i].dtype == 'datetime64[ns]']
    
    # now start making features for every column in the time list
    for i in self.time_feature:
      # make month column if month is choosen
      if 'month' in self.list_of_features_o:
        data[i+"_month"] = [datetime.date(r).month for r in data[i]]
        data[i+"_month"] = data[i+"_month"].apply(str)

      # make weekday column if weekday is choosen ( 0 for monday 6 for sunday)
      if 'weekday' in self.list_of_features_o:
        data[i+"_weekday"] = [datetime.weekday(r) for r in data[i]]
        data[i+"_weekday"] = data[i+"_weekday"].apply(str)
      
      # make Is_month_end column  choosen
      if 'is_month_end' in self.list_of_features_o:
        data[i+"_is_month_end"] = [ 1 if calendar.monthrange(datetime.date(r).year,datetime.date(r).month)[1] == datetime.date(r).day  else 0 for r in data[i] ]
        data[i+"_is_month_end"] = data[i+"_is_month_end"].apply(str)
        
      
      # make Is_month_start column if choosen
      if 'is_month_start' in self.list_of_features_o:
        data[i+"_is_month_start"] = [ 1 if datetime.date(r).day == 1 else 0 for r in data[i] ]
        data[i+"_is_month_start"] = data[i+"_is_month_start"].apply(str)
      
      # make hour column if choosen
      if 'hour' in self.list_of_features_o:
        h = [ datetime.time(r).hour for r in data[i] ]
        if sum(h) > 0:  
          data[i+"_hour"] = h
          data[i+"_hour"] = data[i+"_hour"].apply(str)
    
    # we dont need time columns any more 
    data.drop(self.time_feature,axis=1,inplace=True)

    return(data)

P
PyCaret 已提交
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
 #____________________________________________________________________________________________________________________________________________________________________
# Ordinal transformer
class Ordinal(BaseEstimator,TransformerMixin):
  '''
    - converts categorical features into ordinal values 
    - takes a dataframe , and information about column names and ordered categories as dict
    - returns float panda data frame
  '''

  def __init__(self, info_as_dict):
    self.info_as_dict = info_as_dict
    return(None)

  def fit(self,data,y=None):
    return(None)

  def transform(self,dataset,y=None):
    data = dataset.copy()
    new_data_test = pd.DataFrame(self.enc.transform(data[self.info_as_dict.keys()]),columns= self.info_as_dict.keys(),index= data.index)
    for i in self.info_as_dict.keys():
      data[i] = new_data_test[i]
    return(data)
P
pycaret 已提交
1086

P
PyCaret 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
  def fit_transform(self,dataset,y=None):
    data = dataset.copy()
    # creat categories from given keys in the data set
    cat_list = []
    for i in self.info_as_dict.values():
      i = [np.array(i)]
      cat_list = cat_list + i
    
    # now do fit transform 
    self.enc = OrdinalEncoder(cat_list)
    new_data_train = pd.DataFrame(self.enc.fit_transform(data.loc[:,self.info_as_dict.keys()]),columns=self.info_as_dict,index= data.index )
    # new_data = pd.DataFrame(self.enc.fit_transform(data.loc[:,self.info_as_dict.keys()]))
    for i in self.info_as_dict.keys():
      data[i] = new_data_train[i]
      
    return(data)
P
pycaret 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
# _______________________________________________________________________________________________________________________

# make dummy variables
class Dummify(BaseEstimator,TransformerMixin):
  '''
    - makes one hot encoded variables for dummy variable
    - it is HIGHLY recommended to run the Select_Data_Type class first
    - Ignores target variable

      Args: 
        target: string , name of the target variable
  '''

  def __init__(self,target):
    self.target = target
    
    # creat ohe object 
    self.ohe = OneHotEncoder(handle_unknown='ignore')
  
  def fit(self,dataset,y=None):
    data = dataset.copy()
    # will only do this if there are categorical variables 
    if len(data.select_dtypes(include=('object')).columns) > 0:
      # we need to learn the column names once the training data set is dummify
      # save non categorical data
      self.data_nonc = data.drop(self.target,axis=1,errors='ignore').select_dtypes(exclude=('object'))
      self.target_column =  data[[self.target]]
      # # plus we will only take object data types
      try:
        self.data_columns  = pd.get_dummies(data.drop(self.target,axis=1,errors='ignore').select_dtypes(include=('object'))).columns
      except:
        self.data_columns = []
      # # now fit the trainin column
      self.ohe.fit(data.drop(self.target,axis=1,errors='ignore').select_dtypes(include=('object')))
    else:
      None
    return(None)
 
  def transform(self,dataset,y=None):
    data = dataset.copy()
    # will only do this if there are categorical variables 
    if len(data.select_dtypes(include=('object')).columns) > 0:
      # only for test data
      self.data_nonc = data.drop(self.target,axis=1,errors='ignore').select_dtypes(exclude=('object'))
      # fit without target and only categorical columns
      array = self.ohe.transform(data.drop(self.target,axis=1,errors='ignore').select_dtypes(include=('object'))).toarray()
      data_dummies = pd.DataFrame(array,columns= self.data_columns)
      data_dummies.index = self.data_nonc.index
      #now put target , numerical and categorical variables back togather
      data = pd.concat((self.data_nonc,data_dummies),axis=1)
      del(self.data_nonc)
      return(data)
    else:
      return(data)

  def fit_transform(self,dataset,y=None):
    data = dataset.copy()
    # will only do this if there are categorical variables 
    if len(data.select_dtypes(include=('object')).columns) > 0:
      self.fit(data)
      # fit without target and only categorical columns
      array = self.ohe.transform(data.drop(self.target,axis=1,errors='ignore').select_dtypes(include=('object'))).toarray()
      data_dummies = pd.DataFrame(array,columns= self.data_columns)
      data_dummies.index = self.data_nonc.index
      # now put target , numerical and categorical variables back togather
      data = pd.concat((self.target_column,self.data_nonc,data_dummies),axis=1)
      # remove unwanted attributes
      del(self.target_column,self.data_nonc)
      return(data)
    else:
      return(data)

P
PyCaret 已提交
1175 1176 1177 1178 1179 1180 1181 1182
# _______________________________________________________________________________________________________________________
# Outlier
class Outlier(BaseEstimator,TransformerMixin):
  '''
    - Removes outlier using ABOD,KNN,IFO,PCA & HOBS using hard voting
    - Only takes numerical / One Hot Encoded features
  '''

P
PyCaret 已提交
1183
  def __init__(self,target,contamination=.20, random_state=42, methods=['knn','iso','pca']):
P
PyCaret 已提交
1184 1185 1186
    self.target = target
    self.contamination = contamination
    self.random_state = random_state
P
PyCaret 已提交
1187
    self.methods = methods
P
PyCaret 已提交
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212

    return(None)

  def fit(self,data,y=None):
    #self.abod.fit(data)
    return(None)

  def transform(self,data,y=None):
    return(data)

  def fit_transform(self,dataset,y=None):

    # dummify if there are any obects 
    if len(dataset.select_dtypes(include='object').columns)>0:
      self.dummy = Dummify(self.target)
      data = self.dummy.fit_transform(dataset)
    else:
      data = dataset.copy()

    # reduce data size for faster processing
    # try:
    #   data = data.astype('float16')
    # except:
    #   None

P
PyCaret 已提交
1213 1214 1215 1216 1217
    if 'knn' in self.methods:
      self.knn = KNN(contamination=self.contamination)
      self.knn.fit(data.drop(self.target,axis=1))
      knn_predict = self.knn.predict(data.drop(self.target,axis=1))
      data['knn'] = knn_predict
P
PyCaret 已提交
1218
    
P
PyCaret 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    if 'iso' in self.methods:
      self.iso = IForest(contamination=self.contamination,random_state=self.random_state,behaviour='new')
      self.iso.fit(data.drop(self.target,axis=1))
      iso_predict = self.iso.predict(data.drop(self.target,axis=1))
      data['iso'] = iso_predict

    if 'pca' in self.methods:
      self.pca = PCA_od(contamination=self.contamination,random_state=self.random_state)
      self.pca.fit(data.drop(self.target,axis=1))
      pca_predict = self.pca.predict(data.drop(self.target,axis=1))
      data['pca'] = pca_predict

    data['vote_outlier'] = 0
    
    for i in self.methods:
      data['vote_outlier'] = data['vote_outlier'] + data[i]
    
  
    # data['vote_outlier'] =  data['knn']  + data['iso'] + data['pca'] 
    self.outliers = data[data['vote_outlier']== len(self.methods)]
    # self.outliers = data[data['vote_outlier']==3]
P
PyCaret 已提交
1240 1241 1242
    
    return(dataset[[True if i not in self.outliers.index else False for i in dataset.index]])

P
pycaret 已提交
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265

#____________________________________________________________________________________________________________________________________________________________________
# Column Name cleaner transformer
class Clean_Colum_Names(BaseEstimator,TransformerMixin):
  '''
    - Cleans special chars that are not supported by jason format
  '''

  def __init__(self):
    return(None)

  def fit(self,data,y=None):
    return(None)

  def transform(self,dataset,y=None):
    data= dataset.copy()
    data.columns= data.columns.str.replace('[,}{\]\[\:\"\']','')
    return(data)

  def fit_transform(self,dataset,y=None):
    data= dataset.copy()
    data.columns= data.columns.str.replace('[,}{\]\[\:\"\']','')
    return(data)
P
PyCaret 已提交
1266 1267 1268
#__________________________________________________________________________________________________________________________________________________________________________
# Clustering entire data
class Cluster_Entire_Data(BaseEstimator,TransformerMixin):
P
pycaret 已提交
1269
  '''
P
PyCaret 已提交
1270 1271 1272 1273 1274
    - Applies kmeans clustering to the entire data set and produce clusters
    - Highly recommended to run the DataTypes_Auto_infer class first
      Args:
          target_variable: target variable (integer or numerical only)
          check_clusters_upto: to determine optimum number of kmeans clusters, set the uppler limit of clusters
P
pycaret 已提交
1275 1276
  '''

P
PyCaret 已提交
1277 1278 1279 1280 1281 1282
  def __init__(self, target_variable, check_clusters_upto=20, random_state=42):
    self.target = target_variable
    self.check_clusters = check_clusters_upto +1
    self.random_state = random_state
    
    
P
pycaret 已提交
1283 1284 1285 1286 1287

  def fit(self,data,y=None):
    return(None)

  def transform(self,data,y=None):
P
PyCaret 已提交
1288 1289 1290 1291 1292 1293 1294
    # first convert to dummy
    if len(data.select_dtypes(include='object').columns)>0:
      data_t1 = self.dummy.transform(data)
    else:
      data_t1 = data.copy()

    # # now make PLS 
P
PyCaret 已提交
1295 1296
    # data_t1 = self.pls.transform(data_t1)
    # data_t1 = self.pca.transform(data_t1)
P
PyCaret 已提交
1297 1298 1299 1300
    # now predict with the clustes
    predict =pd.DataFrame(self.k_object.predict(data_t1),index=data.index)
    data['data_cluster'] = predict
    data['data_cluster'] = data['data_cluster'].astype('object')
P
pycaret 已提交
1301 1302 1303
    return(data)

  def fit_transform(self,data,y=None):
P
PyCaret 已提交
1304 1305 1306 1307 1308 1309 1310 1311
    # first convert to dummy (if there are objects in data set)
    if len(data.select_dtypes(include='object').columns)>0:
      self.dummy = Dummify(self.target)
      data_t1 = self.dummy.fit_transform(data)
    else:
      data_t1 = data.copy()
    
    # now make PLS 
P
PyCaret 已提交
1312 1313 1314 1315
    # self.pls = PLSRegression(n_components=len(data_t1.columns)-1)
    # data_t1 = self.pls.fit_transform(data_t1.drop(self.target,axis=1),data_t1[self.target])[0]
    # self.pca = PCA(n_components=len(data_t1.columns)-1)
    # data_t1 = self.pca.fit_transform(data_t1.drop(self.target,axis=1))
P
PyCaret 已提交
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    
    # we are goign to make a place holder , for 2 to 20 clusters
    self.ph = pd.DataFrame(np.arange(2,self.check_clusters,1), columns= ['clusters']) 
    self.ph['Silhouette'] = float(0)
    self.ph['calinski'] = float(0)

    # Now start making clusters
    for k in self.ph.index:
        c =  self.ph['clusters'][k]
        self.k_object =  cluster.KMeans(n_clusters= c,init='k-means++',precompute_distances='auto',n_init=10,random_state=self.random_state)
        self.k_object.fit(data_t1)
        self.ph.iloc[k,1] = metrics.silhouette_score(data_t1,self.k_object.labels_)
        self.ph.iloc[k,2] = metrics.calinski_harabaz_score(data_t1,self.k_object.labels_)
    
    # now standardize the scores and make a total column
    m = MinMaxScaler((-1,1))
    self.ph['calinski'] = m.fit_transform(np.array(self.ph['calinski']).reshape(-1,1))
    self.ph['Silhouette'] = m.fit_transform(np.array(self.ph['Silhouette']).reshape(-1,1))
    self.ph['total']= self.ph['Silhouette'] + self.ph['calinski']
    # sort it by total column and take the first row column 0 , that would represent the optimal clusters
    self.clusters = int(self.ph[self.ph['total'] == max(self.ph['total'])]['clusters'])
    # Now make the final cluster object
    self.k_object =  cluster.KMeans(n_clusters= self.clusters,init='k-means++',precompute_distances='auto',n_init=10,random_state=self.random_state)
    # now do fit predict
    predict =pd.DataFrame(self.k_object.fit_predict(data_t1),index=data.index)
    data['data_cluster'] = predict
    data['data_cluster'] = data['data_cluster'].astype('object')

    return(data)
P
PyCaret 已提交
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
#____________________________________________________________________________________________________________________________________________
# take noneliner transformations
class Make_NonLiner_Features(BaseEstimator,TransformerMixin):
  '''
    - convert numerical features into polynomial features
    - it is HIGHLY recommended to run the Autoinfer_Data_Type class first
    - Ignores target variable
    - it picks up data type float64 as numerical 
    - for multiclass classification problem , set subclass arg to 'multi'

      Args: 
        target: string , name of the target variable
        Polynomial_degree: int ,default 2  
  '''

  def __init__(self,target,ml_usecase= 'classification',Polynomial_degree=2,other_nonliner_features= ['sin','cos','tan'],top_features_to_pick=.20,random_state=42,subclass='ignore'):
    self.target = target
    self.Polynomial_degree = Polynomial_degree
    self.ml_usecase = ml_usecase
    self.other_nonliner_features = other_nonliner_features
    self.top_features_to_pick = top_features_to_pick
    self.random_state = random_state
    self.subclass = subclass
  
  def fit(self,data,y=None):
    # nothing to learn
      return(None)
 
  def transform(self,dataset,y=None):# same application for test and train
    data = dataset.copy()
    
    self.numeric_columns = data.drop(self.target,axis=1,errors='ignore').select_dtypes(include="float64").columns
    if self.Polynomial_degree >= 2: # dont run anything if powr is les than 2
      #self.numeric_columns = data.drop(self.target,axis=1,errors='ignore').select_dtypes(include="float64").columns
      # start taking powers
      for i in range(2,self.Polynomial_degree+1):
        ddc_power = np.power(data[self.numeric_columns],i)
        ddc_col = list(ddc_power.columns)
        ii = str(i)
        ddc_col = [ddc_col + '_Power'+ ii for ddc_col in ddc_col]
        ddc_power.columns = ddc_col
        #put it back with data dummy
        #data = pd.concat((data,ddc_power),axis=1) 
    else:
       ddc_power = pd.DataFrame()
    
    # take sin:
    if 'sin' in self.other_nonliner_features:
      ddc_sin = np.sin(data[self.numeric_columns])
      ddc_col = list(ddc_sin.columns)
      ddc_col = ["sin("+ i +")" for i in ddc_col]
      ddc_sin.columns = ddc_col
      #put it back with data dummy
      #data = pd.concat((data,ddc_sin),axis=1) 
    else:
      ddc_sin = pd.DataFrame()


    # take cos:
    if 'cos' in self.other_nonliner_features:
      ddc_cos = np.cos(data[self.numeric_columns])
      ddc_col = list(ddc_cos.columns)
      ddc_col = ["cos("+ i +")" for i in ddc_col]
      ddc_cos.columns = ddc_col
      #put it back with data dummy
      #data = pd.concat((data,ddc_cos),axis=1)
    else:
       ddc_cos = pd.DataFrame()

    # take tan:
    if 'tan' in self.other_nonliner_features:
      ddc_tan = np.tan(data[self.numeric_columns])
      ddc_col = list(ddc_tan.columns)
      ddc_col = ["tan("+ i +")" for i in ddc_col]
      ddc_tan.columns = ddc_col
      #put it back with data dummy
      #data = pd.concat((data,ddc_tan),axis=1) 
    else:
       ddc_tan = pd.DataFrame()      
  
    #dummy_all
    dummy_all= pd.concat((data,ddc_power,ddc_sin,ddc_cos,ddc_tan),axis=1)
    # we can select top features using RF
    # # and we only want to do this if the dummy all have more than 50 features 
    # if len(dummy_all.columns) > 71:

  
    return(dummy_all[self.columns_to_keep])


  def fit_transform(self,dataset,y=None):
    
    data = dataset.copy()
    
    self.numeric_columns = data.drop(self.target,axis=1,errors='ignore').select_dtypes(include="float64").columns
    if self.Polynomial_degree >= 2: # dont run anything if powr is les than 2
      #self.numeric_columns = data.drop(self.target,axis=1,errors='ignore').select_dtypes(include="float64").columns
      # start taking powers
      for i in range(2,self.Polynomial_degree+1):
        ddc_power = np.power(data[self.numeric_columns],i)
        ddc_col = list(ddc_power.columns)
        ii = str(i)
        ddc_col = [ddc_col + '_Power'+ ii for ddc_col in ddc_col]
        ddc_power.columns = ddc_col
        #put it back with data dummy
        #data = pd.concat((data,ddc_power),axis=1) 
    else:
       ddc_power = pd.DataFrame()
    
    # take sin:
    if 'sin' in self.other_nonliner_features:
      ddc_sin = np.sin(data[self.numeric_columns])
      ddc_col = list(ddc_sin.columns)
      ddc_col = ["sin("+ i +")" for i in ddc_col]
      ddc_sin.columns = ddc_col
      #put it back with data dummy
      #data = pd.concat((data,ddc_sin),axis=1) 
    else:
      ddc_sin = pd.DataFrame()


    # take cos:
    if 'cos' in self.other_nonliner_features:
      ddc_cos = np.cos(data[self.numeric_columns])
      ddc_col = list(ddc_cos.columns)
      ddc_col = ["cos("+ i +")" for i in ddc_col]
      ddc_cos.columns = ddc_col
      #put it back with data dummy
      #data = pd.concat((data,ddc_cos),axis=1)
    else:
       ddc_cos = pd.DataFrame()

    # take tan:
    if 'tan' in self.other_nonliner_features:
      ddc_tan = np.tan(data[self.numeric_columns])
      ddc_col = list(ddc_tan.columns)
      ddc_col = ["tan("+ i +")" for i in ddc_col]
      ddc_tan.columns = ddc_col
      #put it back with data dummy
      #data = pd.concat((data,ddc_tan),axis=1) 
    else:
       ddc_tan = pd.DataFrame()      
  
    #dummy_all
    dummy_all= pd.concat((data[[self.target]],ddc_power,ddc_sin,ddc_cos,ddc_tan),axis=1)
    # we can select top features using our Feature Selection Classic transformer
    afs = Advanced_Feature_Selection_Classic(target=self.target,ml_usecase=self.ml_usecase,top_features_to_pick=self.top_features_to_pick,random_state=self.random_state,subclass=self.subclass)
    dummy_all_t = afs.fit_transform(dummy_all)

    data= pd.concat((data,dummy_all_t),axis=1)
     # # making sure no duplicated columns are there
    data = data.loc[:,~data.columns.duplicated()] 
    self.columns_to_keep = data.drop(self.target,axis=1).columns 

    return(data)

#______________________________________________________________________________________________________________________________________________________
#Feature Selection
class Advanced_Feature_Selection_Classic(BaseEstimator,TransformerMixin):
  '''
    - Selects important features and reduces the feature space. Feature selection is based on Random Forest , Light GBM and Correlation
    - to run on multiclass classification , set the subclass argument to 'multi'
  '''

  def __init__(self,target,ml_usecase='classification',top_features_to_pick=.10, random_state=42, subclass='ignore'):
    self.target= target
    self.ml_usecase = ml_usecase
    self.top_features_to_pick =1-top_features_to_pick
    self.random_state = random_state
    self.subclass = subclass

    return(None)

  def fit(self,dataset,y=None):
    return(None)

  def transform(self,dataset,y=None):
    # return the data with onlys specific columns
    data= dataset.copy()
P
PyCaret 已提交
1524 1525
    # self.selected_columns.remove(self.target)
    return(data[self.selected_columns_test])
P
PyCaret 已提交
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
    # return(data)

  def fit_transform(self,dataset,y=None):
    
    dummy_all = dataset.copy()

    # Random Forest
    max_fe = min(70, int(np.sqrt(len(dummy_all.columns))))
    max_sa = min(1000, int(np.sqrt(len(dummy_all))))

    if self.ml_usecase == 'classification':
      m = rfc(100,max_depth=5,max_features=max_fe,n_jobs=-1,max_samples=max_sa,random_state=self.random_state)
    else:
      m = rfr(100,max_depth=5,max_features=max_fe,n_jobs=-1,max_samples=max_sa,random_state=self.random_state)

    m.fit(dummy_all.drop(self.target,axis=1),dummy_all[self.target])
    # self.fe_imp_table= pd.DataFrame(m.feature_importances_,columns=['Importance'],index=dummy_all.drop(self.target,axis=1).columns).sort_values(by='Importance',ascending= False)
    self.fe_imp_table= pd.DataFrame(m.feature_importances_,columns=['Importance'],index=dummy_all.drop(self.target,axis=1).columns)
    self.fe_imp_table = self.fe_imp_table[self.fe_imp_table['Importance']>= self.fe_imp_table.quantile(self.top_features_to_pick)[0]]
    top = self.fe_imp_table.index
    dummy_all_columns_RF= dummy_all[top].columns


    #LightGBM
    max_fe = min(70, int(np.sqrt(len(dummy_all.columns))))
    max_sa = min(float(1000/len(dummy_all)), float(np.sqrt(len(dummy_all)/len(dummy_all))))

    if self.ml_usecase == 'classification':
      m = lgbmc(n_estimators=100,max_depth=5,n_jobs=-1,subsample=max_sa,random_state=self.random_state)
    else:
      m = lgbmr(n_estimators=100,max_depth=5,n_jobs=-1,subsample=max_sa,random_state=self.random_state)
    m.fit(dummy_all.drop(self.target,axis=1),dummy_all[self.target])
    # self.fe_imp_table= pd.DataFrame(m.feature_importances_,columns=['Importance'],index=dummy_all.drop(self.target,axis=1).columns).sort_values(by='Importance',ascending= False)
    self.fe_imp_table= pd.DataFrame(m.feature_importances_,columns=['Importance'],index=dummy_all.drop(self.target,axis=1).columns)
    self.fe_imp_table = self.fe_imp_table[self.fe_imp_table['Importance']>= self.fe_imp_table.quantile(self.top_features_to_pick)[0]]
    top = self.fe_imp_table.index
    dummy_all_columns_LGBM= dummy_all[top].columns


    # we can now select top correlated feature
    if self.subclass != 'multi':
      corr = pd.DataFrame(np.corrcoef(dummy_all.T))
      corr.columns = dummy_all.columns
      corr.index = dummy_all.columns
      # corr = corr[self.target].abs().sort_values(ascending=False)[0:self.top_features_to_pick+1]
      corr = corr[self.target].abs()
      corr = corr[corr.index!=self.target] # drop the target column
      corr = corr[corr >= corr.quantile(self.top_features_to_pick)]
      corr = pd.DataFrame(dict(features=corr.index,value=corr)).reset_index(drop=True)
      corr = corr.drop_duplicates(subset='value')
      corr = corr['features']
      # corr = pd.DataFrame(dict(features=corr.index,value=corr)).reset_index(drop=True)
      # corr = corr.drop_duplicates(subset='value')[0:self.top_features_to_pick+1]
      # corr = corr['features']
    else:
      corr = list()

    self.dummy_all_columns_RF = dummy_all_columns_RF
    self.dummy_all_columns_LGBM = dummy_all_columns_LGBM
    self.corr = corr

    self.selected_columns = list(set([self.target]+list(dummy_all_columns_RF) + list(corr) +list(dummy_all_columns_LGBM)))
    
P
PyCaret 已提交
1589
    self.selected_columns_test = dataset[self.selected_columns].drop(self.target,axis=1).columns
P
PyCaret 已提交
1590 1591
    return(dataset[self.selected_columns])
#_
P
PyCaret 已提交
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788

#_________________________________________________________________________________________________________________________________________
class Fix_multicollinearity(BaseEstimator,TransformerMixin):
  """
          Fixes multicollinearity between predictor variables , also considering the correlation between target variable.
          Only applies to regression or two class classification ML use case
          Takes numerical and one hot encoded variables only
            Args:
              threshold (float): The utmost absolute pearson correlation tolerated beyween featres from 0.0 to 1.0
              target_variable (str): The target variable/column name
              correlation_with_target_threshold: minimum absolute correlation required between every feature and the target variable , default 1.0 (0.0 to 1.0)
              correlation_with_target_preference: float (0.0 to 1.0), default .08 ,while choosing between a pair of features w.r.t multicol & correlation target , this gives 
              the option to favour one measur to another. e.g. if value is .6 , during feature selection tug of war, correlation target measure will have a higher say.
              A value of .5 means both measure have equal say 
  """
  # mamke a constructer
  
  def __init__ (self,threshold,target_variable,correlation_with_target_threshold= 0.0,correlation_with_target_preference=1.0):
      self.threshold = threshold
      self.target_variable = target_variable
      self.correlation_with_target_threshold= correlation_with_target_threshold
      self.target_corr_weight = correlation_with_target_preference
      self.multicol_weight = 1-correlation_with_target_preference
  
  # Make fit method
  
  def fit (self,data,y=None):
    '''
        Args:
            data = takes preprocessed data frame
        Returns:
            None
    '''
      
    #global data1
    self.data1 = data.copy()
    # try:
    #   self.data1 = self.data1.astype('float16')
    # except:
    #   None
    # make an correlation db with abs correlation db
    # self.data_c = self.data1.T.drop_duplicates()
    # self.data1 = self.data_c.T
    corr = pd.DataFrame(np.corrcoef(self.data1.T))
    corr.columns = self.data1.columns
    corr.index = self.data1.columns
    # self.corr_matrix = abs(self.data1.corr())
    self.corr_matrix = abs(corr)

    # for every diagonal value, make it Nan
    self.corr_matrix.values[tuple([np.arange(self.corr_matrix.shape[0])]*2)] = np.NaN
    
    # Now Calculate the average correlation of every feature with other, and get a pandas data frame
    self.avg_cor = pd.DataFrame(self.corr_matrix.mean())
    self.avg_cor['feature']= self.avg_cor.index
    self.avg_cor.reset_index(drop=True, inplace=True)
    self.avg_cor.columns =  ['avg_cor','features']
    
    # Calculate the correlation with the target
    self.targ_cor = pd.DataFrame(self.corr_matrix[self.target_variable].dropna())
    self.targ_cor['feature']= self.targ_cor.index
    self.targ_cor.reset_index(drop=True, inplace=True)
    self.targ_cor.columns =  ['target_variable','features']
    
    # Now, add a column for variable name and drop index
    self.corr_matrix['column'] = self.corr_matrix.index
    self.corr_matrix.reset_index(drop=True,inplace=True)
    
    # now we need to melt it , so that we can correlation pair wise , with two columns 
    self.cols =self.corr_matrix.column
    self.melt = self.corr_matrix.melt(id_vars= ['column'],value_vars=self.cols).sort_values(by='value',ascending=False).dropna()

    # now bring in the avg correlation for first of the pair
    self.merge = pd.merge(self.melt,self.avg_cor,left_on='column',right_on='features').drop('features',axis=1)

    # now bring in the avg correlation for second of the pair
    self.merge = pd.merge(self.merge,self.avg_cor,left_on='variable',right_on='features').drop('features',axis=1)

    # now bring in the target correlation for first of the pair
    self.merge = pd.merge(self.merge,self.targ_cor,left_on='column',right_on='features').drop('features',axis=1)

    # now bring in the avg correlation for second of the pair
    self.merge = pd.merge(self.merge,self.targ_cor,left_on='variable',right_on='features').drop('features',axis=1)

    # sort and save
    self.merge = self.merge.sort_values(by='value',ascending=False)

    # we need to now eleminate all the pairs that are actually duplicate e.g cor(x,y) = cor(y,x) , they are the same , we need to find these and drop them
    self.merge['all_columns'] = self.merge['column'] + self.merge['variable']

    # this puts all the coresponding pairs of features togather , so that we can only take one, since they are just the duplicates
    self.merge['all_columns'] = [sorted(i) for i in self.merge['all_columns'] ]

    # now sort by new column
    self.merge = self.merge.sort_values(by='all_columns')

    # take every second colums
    self.merge = self.merge.iloc[::2, :]

    # make a ranking column to eliminate features
    self.merge['rank_x'] = round(self.multicol_weight*(self.merge['avg_cor_y']- self.merge['avg_cor_x']) +  self.target_corr_weight*(self.merge['target_variable_x'] - self.merge['target_variable_y']),6) # round it to 6 digits
    self.merge1 = self.merge # delete here
    ## Now there will be rows where the rank will be exactly zero, these is where the value (corelartion between features) is exactly one ( like price and price^2)
    ## so in that case , we can simply pick one of the variable
    # but since , features can be in either column, we will drop one column (say 'column') , only if the feature is not in the second column (in variable column)
    # both equations below will return the list of columns to drop from here 
    # this is how it goes

    ## For the portion where correlation is exactly one !
    self.one = self.merge[self.merge['rank_x']==0]

    # this portion is complicated 
    # table one have all the paired variable having corelation of 1
    # in a nutshell, we can take any column (one side of pair) and delete the other columns (other side of the pair)
    # however one varibale can appear more than once on any of the sides , so we will run for loop to find all pairs...
    # here it goes
    # take a list of all (but unique ) variables that have correlation 1 for eachother, we will make two copies
    self.u_all = list(pd.unique(pd.concat((self.one['column'],self.one['variable']),axis=0)))
    self.u_all_1 = list(pd.unique(pd.concat((self.one['column'],self.one['variable']),axis=0)))
    # take a list of features (unique) for the first side of the pair
    self.u_column  = pd.unique(self.one['column'])
    
    # now we are going to start picking each variable from one column (one side of the pair) , check it against the other column (other side of the pair)
    # to pull all coresponding / paired variables  , and delete thoes newly varibale names from all unique list
    
    for i in self.u_column:
      #print(i)
      r = self.one[self.one['column']==i]['variable'].values
      for q in r:
        if q in self.u_all:
          #print("_"+q)
          self.u_all.remove(q)

    # now the unique column contains the varibales that should remain, so in order to get the variables that should be deleted :
    self.to_drop =(list(set(self.u_all_1)-set(self.u_all)))


    # self.to_drop_a =(list(set(self.one['column'])-set(self.one['variable'])))
    # self.to_drop_b =(list(set(self.one['variable'])-set(self.one['column'])))
    # self.to_drop = self.to_drop_a + self.to_drop_b

    ## now we are to treat where rank is not Zero and Value (correlation) is greater than a specific threshold
    self.non_zero = self.merge[(self.merge['rank_x']!= 0.0) & (self.merge['value'] >= self.threshold)]

    # pick the column to delete
    self.non_zero_list = list(np.where(self.non_zero['rank_x'] < 0 , self.non_zero['column'], self.non_zero['variable']))

    # add two list
    self.to_drop = self.to_drop + self.non_zero_list

    #make sure that target column is not a part of the list
    try:
        self.to_drop.remove(self.target_variable)
    except:
        self.to_drop
    
    self.to_drop = self.to_drop

    # now we want to keep only the columns that have more correlation with traget by a threshold
    self.to_drop_taret_correlation=[] 
    if self.correlation_with_target_threshold != 0.0:
      corr = pd.DataFrame(np.corrcoef(data.drop(self.to_drop,axis=1).T),columns= data.drop(self.to_drop,axis=1).columns,index=data.drop(self.to_drop,axis=1).columns)
      self.to_drop_taret_correlation = corr[self.target_variable].abs()
      # self.to_drop_taret_correlation = data.drop(self.to_drop,axis=1).corr()[self.target_variable].abs()
      self.to_drop_taret_correlation = self.to_drop_taret_correlation [self.to_drop_taret_correlation < self.correlation_with_target_threshold ]
      self.to_drop_taret_correlation = list(self.to_drop_taret_correlation.index)
      #self.to_drop = self.corr + self.to_drop
      try:
        self.to_drop_taret_correlation.remove(self.target_variable)
      except:
        self.to_drop_taret_correlation
      

  # now Transform
  def transform(self,dataset,y=None):
    '''
        Args:f
            data = takes preprocessed data frame
        Returns:
            data frame
    '''
    data = dataset.copy()
    data.drop(self.to_drop,axis=1,inplace=True)
    # now drop less correlated data
    data.drop(self.to_drop_taret_correlation,axis=1,inplace=True,errors='ignore')
    return(data)
  
  # fit_transform
  def fit_transform(self,data, y=None):
    
    '''
        Args:
            data = takes preprocessed data frame
        Returns:
            data frame
    '''
    self.fit(data)
P
pycaret 已提交
1789
    return(self.transform(data))
P
PyCaret 已提交
1790

P
PyCaret 已提交
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
#_______________________________________________________________________________________________________________________________________________________________________________________________
# custome DFS 
class DFS_Classic(BaseEstimator,TransformerMixin):
  '''
    - Automated feature interactions using multiplication, division , addition & substraction
    - Only accepts numeric / One Hot Encoded features
    - Takes DF, return same DF 
    - for Multiclass classification problem , set subclass arg as 'multi'
  '''

  def __init__(self,target,ml_usecase='classification',interactions=['multiply','divide','add','subtract'],top_features_to_pick_percentage=.05, random_state=42,subclass='ignore'):
    self.target= target
    self.interactions = interactions
    self.top_n_correlated = top_features_to_pick_percentage #(this will be 1- top_features , but handled in the Advance_feature_selection )
    self.ml_usecase = ml_usecase
    self.random_state = random_state
    self.subclass = subclass
    

    return(None)

  def fit(self,data,y=None):
    return(None)

  def transform(self,dataset,y=None):

    data= dataset.copy()
     # for multiplication:
    # we need bot catagorical and numerical columns

    if 'multiply' in self.interactions:
      
      data_multiply = pd.concat([data.drop(self.target,axis=1,errors='ignore').mul(col[1], axis="index") for col in data.drop(self.target,axis=1,errors='ignore').iteritems()], axis=1)
      data_multiply.columns = ["_multiply_".join([i, j]) for j in data.drop(self.target,axis=1,errors='ignore').columns for i in data.drop(self.target,axis=1,errors='ignore').columns]
      # we dont need to apply rest of conditions
      data_multiply.index = data.index 
    else:
      data_multiply= pd.DataFrame()
    
     # for division, we only want it to apply to numerical columns
    if 'divide' in self.interactions:
      
      data_divide = pd.concat([data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].div(col[1], axis="index") for col in data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].iteritems()], axis=1)
      data_divide.columns = ["_divide_".join([i, j]) for j in data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].columns for i in data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].columns]
      data_divide.replace([np.inf,-np.inf],0,inplace=True)
      data_divide.fillna(0,inplace=True)
      data_divide.index = data.index
    else:
      data_divide= pd.DataFrame()
    
     # for addition, we only want it to apply to numerical columns
    if 'add' in self.interactions:

      data_add = pd.concat([data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].add(col[1], axis="index") for col in data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].iteritems()], axis=1)
      data_add.columns = ["_add_".join([i, j]) for j in data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].columns for i in data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].columns]
      data_add.index = data.index
    else:
      data_add= pd.DataFrame()
    
    # for substraction, we only want it to apply to numerical columns
    if 'subtract' in self.interactions:
      
      data_substract = pd.concat([data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].sub(col[1], axis="index") for col in data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].iteritems()], axis=1)
      data_substract.columns = ["_subtract_".join([i, j]) for j in data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].columns for i in data.drop(self.target,axis=1,errors='ignore')[self.numeric_columns].columns]
      data_substract.index = data.index
    else:
      data_substract= pd.DataFrame()

    # get all the dummy data combined
    dummy_all = pd.concat((data,data_multiply,data_divide,data_add,data_substract),axis=1)
    del(data_multiply)
    del(data_divide)
    del(data_add)
    del(data_substract)
    # now only return the columns we want:
    return(dummy_all[self.columns_to_keep])

    

  def fit_transform(self,dataset,y=None):

    data= dataset.copy()

    # we need to seperate numerical and ont hot encoded columns
    # self.ohe_columns = [i if ((len(data[i].unique())==2) & (data[i].unique()[0] in [0,1]) & (data[i].unique()[1] in [0,1]) ) else None for i in data.drop(self.target,axis=1).columns]
    self.ohe_columns =[i for i in data.columns if len(data[i].unique()) == 2 and data[i].unique()[0] in [0,1] and data[i].unique()[1] in [0,1]]
    # self.ohe_columns = [i for i in self.ohe_columns if i is not None]
    self.numeric_columns = [i for i in data.drop(self.target,axis=1).columns if i not in self.ohe_columns]
    target_variable = data[[self.target]]

    # for multiplication:
    # we need bot catagorical and numerical columns

    if 'multiply' in self.interactions:
      data_multiply = pd.concat([data.drop(self.target,axis=1).mul(col[1], axis="index") for col in data.drop(self.target,axis=1).iteritems()], axis=1)
      data_multiply.columns = ["_multiply_".join([i, j]) for j in data.drop(self.target,axis=1).columns for i in data.drop(self.target,axis=1).columns]
      # we dont need columns that are self interacted
      col = ["_multiply_".join([i, j]) for j in data.drop(self.target,axis=1).columns for i in data.drop(self.target,axis=1).columns if i!=j]
      data_multiply = data_multiply[col]
      # we dont need columns where the sum of the total column is null (to catagorical variables never happening togather)
      col1 = [i for i in data_multiply.columns if np.nansum(data_multiply[i])!=0 ]
      data_multiply = data_multiply[col1]
      data_multiply.index = data.index
    else:
      data_multiply= pd.DataFrame()

    # for division, we only want it to apply to numerical columns
    if 'divide' in self.interactions:
      data_divide = pd.concat([data.drop(self.target,axis=1)[self.numeric_columns].div(col[1], axis="index") for col in data.drop(self.target,axis=1)[self.numeric_columns].iteritems()], axis=1)
      data_divide.columns = ["_divide_".join([i, j]) for j in data.drop(self.target,axis=1)[self.numeric_columns].columns for i in data.drop(self.target,axis=1)[self.numeric_columns].columns]
      # we dont need columns that are self interacted
      col = ["_divide_".join([i, j]) for j in data.drop(self.target,axis=1)[self.numeric_columns].columns for i in data.drop(self.target,axis=1)[self.numeric_columns].columns if i!=j]
      data_divide = data_divide[col]
      # we dont need columns where the sum of the total column is null (to catagorical variables never happening togather)
      col1 = [i for i in data_divide.columns if np.nansum(data_divide[i])!=0 ]
      data_divide = data_divide[col1]
      # additionally we need to fill anll the possible NaNs
      data_divide.replace([np.inf,-np.inf],0,inplace=True)
      data_divide.fillna(0,inplace=True)
      data_divide.index = data.index
    else:
      data_divide= pd.DataFrame()

    # for addition, we only want it to apply to numerical columns
    if 'add' in self.interactions:
      data_add = pd.concat([data.drop(self.target,axis=1)[self.numeric_columns].add(col[1], axis="index") for col in data.drop(self.target,axis=1)[self.numeric_columns].iteritems()], axis=1)
      data_add.columns = ["_add_".join([i, j]) for j in data.drop(self.target,axis=1)[self.numeric_columns].columns for i in data.drop(self.target,axis=1)[self.numeric_columns].columns]
      # we dont need columns that are self interacted
      col = ["_add_".join([i, j]) for j in data.drop(self.target,axis=1)[self.numeric_columns].columns for i in data.drop(self.target,axis=1)[self.numeric_columns].columns if i!=j]
      data_add = data_add[col]
      # we dont need columns where the sum of the total column is null (to catagorical variables never happening togather)
      col1 = [i for i in data_add.columns if np.nansum(data_add[i])!=0 ]
      data_add = data_add[col1]
      data_add.index = data.index
    else:
      data_add= pd.DataFrame()

    # for substraction, we only want it to apply to numerical columns
    if 'subtract' in self.interactions:
      data_substract = pd.concat([data.drop(self.target,axis=1)[self.numeric_columns].sub(col[1], axis="index") for col in data.drop(self.target,axis=1)[self.numeric_columns].iteritems()], axis=1)
      data_substract.columns = ["_subtract_".join([i, j]) for j in data.drop(self.target,axis=1)[self.numeric_columns].columns for i in data.drop(self.target,axis=1)[self.numeric_columns].columns]
      # we dont need columns that are self interacted
      col = ["_subtract_".join([i, j]) for j in data.drop(self.target,axis=1)[self.numeric_columns].columns for i in data.drop(self.target,axis=1)[self.numeric_columns].columns if i!=j]
      data_substract = data_substract[col]
      # we dont need columns where the sum of the total column is null (to catagorical variables never happening togather)
      col1 = [i for i in data_substract.columns if np.nansum(data_substract[i])!=0 ]
      data_substract = data_substract[col1]
      data_substract.index = data.index
    else:
      data_substract= pd.DataFrame()

    # get all the dummy data combined
    dummy_all = pd.concat((data_multiply,data_divide,data_add,data_substract),axis=1)
    del(data_multiply)
    del(data_divide)
    del(data_add)
    del(data_substract)

    dummy_all[self.target] = target_variable
    self.dummy_all = dummy_all

  
    # apply advanced feature selectio 
    afs = Advanced_Feature_Selection_Classic(target=self.target,ml_usecase=self.ml_usecase,top_features_to_pick=self.top_n_correlated , random_state=self.random_state, subclass=self.subclass)
    dummy_all_t = afs.fit_transform(dummy_all) 
    
    data_fe_final = pd.concat((data,dummy_all_t),axis=1)     # self.data_fe[self.corr]
    # # making sure no duplicated columns are there
    data_fe_final = data_fe_final.loc[:,~data_fe_final.columns.duplicated()] # new added
    # # remove thetarget column
    # # this is the final data we want that includes original , fe data plus impact of top n correlated
    self.columns_to_keep = data_fe_final.drop(self.target,axis=1).columns 
    del(dummy_all)
    del(dummy_all_t)
   
    return(data_fe_final)



P
pycaret 已提交
1970
#____________________________________________________________________________________________________________________________________________________________________
P
PyCaret 已提交
1971 1972
# Empty transformer
class Empty(BaseEstimator,TransformerMixin):
P
pycaret 已提交
1973
  '''
P
PyCaret 已提交
1974
    - Takes DF, return same DF 
P
pycaret 已提交
1975 1976
  '''

P
PyCaret 已提交
1977
  def __init__(self):
P
pycaret 已提交
1978 1979 1980 1981 1982
    return(None)

  def fit(self,data,y=None):
    return(None)

P
PyCaret 已提交
1983 1984
  def transform(self,data,y=None):
    return(data)
P
pycaret 已提交
1985

P
PyCaret 已提交
1986 1987 1988 1989
  def fit_transform(self,data,y=None):
    return(self.transform(data))

#____________________________________________________________________________________________________________________________________
P
PyCaret 已提交
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
# reduce feature space
class Reduce_Dimensions_For_Supervised_Path(BaseEstimator,TransformerMixin):
  '''
    - Takes DF, return same DF with different types of dimensionality reduction modles (pca_liner , pca_kernal, tsne , pls, incremental)
    - except pca_liner, every other method takes integer as number of components 
    - only takes numeric variables (float & One Hot Encoded)
    - it is intended to solve supervised ML usecases , such as classification / regression
  '''

  def __init__(self, target, method='pca_liner', variance_retained_or_number_of_components=.99, random_state=42):
    self.target= target
    self.variance_retained = variance_retained_or_number_of_components
    self.random_state= random_state
    self.method = method
    return(None)

  def fit(self,data,y=None):
    return(None)

  def transform(self,dataset,y=None):
P
PyCaret 已提交
2010
    if self.method in ['pca_liner' , 'pca_kernal', 'tsne' , 'incremental']: #if self.method in ['pca_liner' , 'pca_kernal', 'tsne' , 'incremental','psa']
P
PyCaret 已提交
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
      data_pca = self.pca.transform(dataset)
      data_pca = pd.DataFrame(data_pca)
      data_pca.columns = ["Component_"+str(i) for i in np.arange(1,len(data_pca.columns)+1)]
      data_pca.index = dataset.index
      return(data_pca)
    else:
      return(dataset)

  def fit_transform(self,dataset,y=None):

    if self.method == 'pca_liner':
P
pycaret 已提交
2022 2023 2024 2025 2026 2027 2028 2029
      self.pca = PCA(self.variance_retained,random_state=self.random_state)
      # fit transform
      data_pca = self.pca.fit_transform(dataset.drop(self.target,axis=1))
      data_pca = pd.DataFrame(data_pca)
      data_pca.columns = ["Component_"+str(i) for i in np.arange(1,len(data_pca.columns)+1)]
      data_pca.index = dataset.index
      data_pca[self.target] = dataset[self.target]
      return(data_pca)
P
PyCaret 已提交
2030 2031 2032 2033 2034 2035 2036 2037 2038
    elif self.method == 'pca_kernal': # take number of components only
      self.pca = KernelPCA(self.variance_retained,kernel='rbf',random_state=self.random_state,n_jobs=-1)
      # fit transform
      data_pca = self.pca.fit_transform(dataset.drop(self.target,axis=1))
      data_pca = pd.DataFrame(data_pca)
      data_pca.columns = ["Component_"+str(i) for i in np.arange(1,len(data_pca.columns)+1)]
      data_pca.index = dataset.index
      data_pca[self.target] = dataset[self.target]
      return(data_pca)
P
PyCaret 已提交
2039 2040 2041 2042 2043 2044 2045 2046 2047
    # elif self.method == 'pls': # take number of components only
    #   self.pca = PLSRegression(self.variance_retained,scale=False)
    #   # fit transform
    #   data_pca = self.pca.fit_transform(dataset.drop(self.target,axis=1),dataset[self.target])[0] 
    #   data_pca = pd.DataFrame(data_pca)
    #   data_pca.columns = ["Component_"+str(i) for i in np.arange(1,len(data_pca.columns)+1)]
    #   data_pca.index = dataset.index
    #   data_pca[self.target] = dataset[self.target]
    #   return(data_pca)
P
PyCaret 已提交
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
    elif self.method == 'tsne': # take number of components only
      self.pca = TSNE(self.variance_retained,random_state=self.random_state)
      # fit transform
      data_pca = self.pca.fit_transform(dataset.drop(self.target,axis=1))
      data_pca = pd.DataFrame(data_pca)
      data_pca.columns = ["Component_"+str(i) for i in np.arange(1,len(data_pca.columns)+1)]
      data_pca.index = dataset.index
      data_pca[self.target] = dataset[self.target]
      return(data_pca)
    elif self.method == 'incremental': # take number of components only
      self.pca = IncrementalPCA(self.variance_retained)
      # fit transform
      data_pca = self.pca.fit_transform(dataset.drop(self.target,axis=1))
      data_pca = pd.DataFrame(data_pca)
      data_pca.columns = ["Component_"+str(i) for i in np.arange(1,len(data_pca.columns)+1)]
      data_pca.index = dataset.index
      data_pca[self.target] = dataset[self.target]
      return(data_pca)
P
pycaret 已提交
2066 2067 2068 2069 2070 2071
    else:
      return(dataset)


#___________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
# preprocess_all_in_one
P
PyCaret 已提交
2072 2073 2074 2075
def Preprocess_Path_One(train_data,target_variable,ml_usecase=None,test_data =None,categorical_features=[],numerical_features=[],time_features=[],features_todrop=[],display_types=True,
                                imputation_type = "simple imputer" ,numeric_imputation_strategy='mean',categorical_imputation_strategy='not_available',
                                apply_zero_nearZero_variance = False,
                                club_rare_levels = False, rara_level_threshold_percentage =0.05,
P
PyCaret 已提交
2076 2077
                                apply_untrained_levels_treatment= False,untrained_levels_treatment_method = 'least frequent',
                                apply_ordinal_encoding = False, ordinal_columns_and_categories= {},
P
PyCaret 已提交
2078
                                apply_binning=False, features_to_binn =[],
P
PyCaret 已提交
2079 2080
                                apply_grouping= False , group_name=[] , features_to_group_ListofList=[[]],
                                apply_polynomial_trigonometry_features = False, max_polynomial=2,trigonometry_calculations=['sin','cos','tan'], top_poly_trig_features_to_select_percentage=.20,
P
pycaret 已提交
2081
                                scale_data= False, scaling_method='zscore',
P
PyCaret 已提交
2082 2083
                                Power_transform_data = False, Power_transform_method ='quantile',
                                target_transformation= False,target_transformation_method ='bc',
P
PyCaret 已提交
2084 2085
                                remove_outliers = False, outlier_contamination_percentage= 0.01,outlier_methods=['pca','iso','knn'],
                                apply_feature_selection = False, feature_selection_top_features_percentage=.80,
P
PyCaret 已提交
2086
                                remove_multicollinearity = False, maximum_correlation_between_features= 0.90,
P
PyCaret 已提交
2087
                                apply_feature_interactions= False, feature_interactions_to_apply=['multiply','divide','add','subtract'],feature_interactions_top_features_to_select_percentage=.01,
P
PyCaret 已提交
2088
                                cluster_entire_data= False, range_of_clusters_to_try=20, 
P
PyCaret 已提交
2089
                                apply_pca = False , pca_method = 'pca_liner',pca_variance_retained_or_number_of_components =.99 ,
P
pycaret 已提交
2090 2091 2092 2093 2094 2095 2096 2097
                                random_state=42

                               ):
  
  '''
    Follwoing preprocess steps are taken:
      - 1) Auto infer data types 
      - 2) Impute (simple or with surrogate columns)
P
PyCaret 已提交
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
      - 3) Drop categorical variables that have zero variance or near zero variance
      - 4) Club categorical variables levels togather as a new level (other_infrequent) that are rare / at the bottom 5% of the variable distribution
      - 5) Generate sub features from time feature such as 'month','weekday',is_month_end','is_month_start' & 'hour'
      - 6) Scales & Power Transform (zscore,minmax,yeo-johnson,quantile,maxabs,robust) , including option to transform target variable
      - 7) Apply binning to continious variable when numeric features are provided as a list 
      - 8) Detect & remove outliers using isolation forest, knn and PCA
      - 9) Apply clusters to segment entire data
      -10) One Hot / Dummy encoding
      -11) Remove special characters from column names such as commas, square brackets etc to make it competible with jason dependednt models
      -12) Fix multicollinearity
      -13) Apply diamension reduction techniques such as pca_liner, pca_kernal, incremental, tsne & pls
P
PyCaret 已提交
2109
          - except for pca_liner, all other method only takes number of component (as integer) i.e no variance explaination metohd available  
P
pycaret 已提交
2110
  '''
P
PyCaret 已提交
2111
  global c2, subcase
P
pycaret 已提交
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
  # WE NEED TO AUTO INFER the ml use case
  c1 = train_data[target_variable].dtype == 'int64'
  c2 = len(train_data[target_variable].unique()) <= 20
  c3 = train_data[target_variable].dtype == 'object'
  
  if ml_usecase is None:
    if ( ( (c1) & (c2) ) | (c3)   ):
      ml_usecase ='classification'
    else:
      ml_usecase ='regression'
  
P
PyCaret 已提交
2123
  if ((len(train_data[target_variable].unique()) > 2) and (ml_usecase != 'regression')):
P
PyCaret 已提交
2124
    subcase = 'multi'
P
PyCaret 已提交
2125 2126
  else:
    subcase = 'binary'
P
pycaret 已提交
2127 2128
  
  global dtypes 
P
PyCaret 已提交
2129
  dtypes = DataTypes_Auto_infer(target=target_variable,ml_usecase=ml_usecase,categorical_features=categorical_features,numerical_features=numerical_features,time_features=time_features,features_todrop=features_todrop,display_types=display_types)
P
pycaret 已提交
2130 2131 2132 2133

  
  # for imputation
  if imputation_type == "simple imputer":
P
PyCaret 已提交
2134
    global imputer
P
pycaret 已提交
2135 2136 2137
    imputer = Simple_Imputer(numeric_strategy=numeric_imputation_strategy, target_variable= target_variable,categorical_strategy=categorical_imputation_strategy)
  else:
    imputer = Surrogate_Imputer(numeric_strategy=numeric_imputation_strategy,categorical_strategy=categorical_imputation_strategy,target_variable=target_variable)
P
PyCaret 已提交
2138 2139 2140
  
  # for zero_near_zero
  if apply_zero_nearZero_variance == True:
P
PyCaret 已提交
2141
    global znz
P
PyCaret 已提交
2142 2143 2144 2145 2146
    znz = Zroe_NearZero_Variance(target=target_variable)
  else:
    znz = Empty()

  # for rare levels clubbing:
P
PyCaret 已提交
2147
  
P
PyCaret 已提交
2148
  if club_rare_levels == True:
P
PyCaret 已提交
2149
    global club_R_L
P
PyCaret 已提交
2150 2151 2152 2153
    club_R_L = Catagorical_variables_With_Rare_levels(target=target_variable,threshold=rara_level_threshold_percentage)
  else:
    club_R_L= Empty()

P
PyCaret 已提交
2154 2155 2156 2157 2158 2159 2160
  # untrained levels in test
  if apply_untrained_levels_treatment ==  True:
    global new_levels 
    new_levels = New_Catagorical_Levels_in_TestData(target=target_variable,replacement_strategy=untrained_levels_treatment_method)
  else:
    new_levels= Empty()

P
PyCaret 已提交
2161 2162 2163 2164 2165 2166 2167
  # ordinal coding
  if apply_ordinal_encoding == True:
    global ordinal
    ordinal = Ordinal(info_as_dict=ordinal_columns_and_categories)
  else:
    ordinal = Empty()

P
PyCaret 已提交
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181
  # grouping
  if apply_grouping == True:
    global group
    group = Group_Similar_Features(group_name=group_name,list_of_grouped_features=features_to_group_ListofList)
  else:
    group = Empty()

  # non_liner_features
  if apply_polynomial_trigonometry_features == True:
    global nonliner
    nonliner = Make_NonLiner_Features(target=target_variable,ml_usecase=ml_usecase,Polynomial_degree=max_polynomial,other_nonliner_features=trigonometry_calculations,top_features_to_pick=top_poly_trig_features_to_select_percentage,random_state=random_state,subclass=subcase)
  else:
    nonliner = Empty()

P
PyCaret 已提交
2182 2183
  # binning 
  if apply_binning == True:
P
PyCaret 已提交
2184
    global binn
P
PyCaret 已提交
2185 2186 2187 2188
    binn = Binning(features_to_discretize=features_to_binn)
  else:
    binn = Empty()

P
PyCaret 已提交
2189
  # scaling & power transform
P
pycaret 已提交
2190
  if scale_data == True:
P
PyCaret 已提交
2191
    global scaling 
P
PyCaret 已提交
2192
    scaling = Scaling_and_Power_transformation(target=target_variable,function_to_apply=scaling_method,random_state_quantile=random_state)
P
pycaret 已提交
2193 2194 2195 2196
  else: 
    scaling = Empty()
  
  if Power_transform_data== True:
P
PyCaret 已提交
2197 2198
    global P_transform
    P_transform = Scaling_and_Power_transformation(target=target_variable,function_to_apply=Power_transform_method,random_state_quantile=random_state)
P
pycaret 已提交
2199 2200
  else:
    P_transform= Empty()
P
PyCaret 已提交
2201 2202 2203 2204 2205 2206 2207 2208
  
  # target transformation
  if ((target_transformation == True) and (ml_usecase == 'regression')):
    global pt_target
    pt_target = Target_Transformation(target=target_variable,function_to_apply=target_transformation_method)
  else:
    pt_target = Empty()

P
pycaret 已提交
2209 2210 2211 2212 2213 2214

  # for Time Variables
  global feature_time
  feature_time = Make_Time_Features()
  global dummy
  dummy = Dummify(target_variable)
P
PyCaret 已提交
2215 2216 2217 2218

  # remove putliers
  if remove_outliers == True:
    global rem_outliers
P
PyCaret 已提交
2219
    rem_outliers= Outlier(target=target_variable,contamination=outlier_contamination_percentage,random_state=random_state,methods=outlier_methods )
P
PyCaret 已提交
2220 2221 2222 2223 2224 2225 2226 2227 2228
  else:
    rem_outliers = Empty()
  
  # cluster all data:
  if cluster_entire_data ==True:
    global cluster_all
    cluster_all = Cluster_Entire_Data(target_variable=target_variable,check_clusters_upto=range_of_clusters_to_try, random_state = random_state )
  else:
    cluster_all = Empty()
P
pycaret 已提交
2229 2230 2231
  
  # clean column names for special char
  clean_names =Clean_Colum_Names()
P
PyCaret 已提交
2232 2233 2234 2235 2236 2237 2238

  # feature selection 
  if apply_feature_selection == True:
    global feature_select
    feature_select = Advanced_Feature_Selection_Classic(target=target_variable,ml_usecase=ml_usecase,top_features_to_pick=feature_selection_top_features_percentage,random_state=random_state,subclass=subcase)
  else:
    feature_select= Empty()
P
pycaret 已提交
2239
  
P
PyCaret 已提交
2240
  # removing multicollinearity
P
PyCaret 已提交
2241 2242
  global fix_multi
  if remove_multicollinearity == True and subcase != 'multi':
P
PyCaret 已提交
2243
    fix_multi = Fix_multicollinearity(target_variable=target_variable,threshold=maximum_correlation_between_features)
P
PyCaret 已提交
2244 2245
  elif remove_multicollinearity == True and subcase == 'multi':
    fix_multi = Fix_multicollinearity(target_variable=target_variable,threshold=maximum_correlation_between_features,correlation_with_target_preference=0.0)
P
PyCaret 已提交
2246 2247
  else:
    fix_multi = Empty()
P
PyCaret 已提交
2248 2249 2250 2251 2252 2253 2254
  
  # apply dfs
  if apply_feature_interactions == True:
    global dfs
    dfs = DFS_Classic(target=target_variable,ml_usecase=ml_usecase,interactions=feature_interactions_to_apply,top_features_to_pick_percentage=feature_interactions_top_features_to_select_percentage,random_state=random_state,subclass=subcase )
  else:
    dfs= Empty()
P
PyCaret 已提交
2255

P
PyCaret 已提交
2256 2257 2258
  
  # apply pca
  if apply_pca == True:
P
PyCaret 已提交
2259
    global pca
P
PyCaret 已提交
2260 2261 2262
    pca = Reduce_Dimensions_For_Supervised_Path(target=target_variable,method = pca_method ,variance_retained_or_number_of_components=pca_variance_retained_or_number_of_components, random_state=random_state)
  else:
    pca= Empty()
P
pycaret 已提交
2263 2264 2265 2266 2267

  global pipe
  pipe = Pipeline([
                 ('dtypes',dtypes),
                 ('imputer',imputer),
P
PyCaret 已提交
2268 2269
                 ('znz',znz),
                 ('club_R_L',club_R_L),
P
PyCaret 已提交
2270
                 ('new_levels',new_levels),
P
PyCaret 已提交
2271
                 ('ordinal',ordinal),
P
pycaret 已提交
2272
                 ('feature_time',feature_time),
P
PyCaret 已提交
2273 2274
                 ('group',group),
                 ('nonliner',nonliner),
P
pycaret 已提交
2275 2276
                 ('scaling',scaling),
                 ('P_transform',P_transform),
P
PyCaret 已提交
2277 2278 2279 2280
                 ('pt_target',pt_target),
                 ('binn',binn),
                 ('rem_outliers',rem_outliers),
                 ('cluster_all',cluster_all),
P
pycaret 已提交
2281
                 ('dummy',dummy),
P
PyCaret 已提交
2282
                 ('clean_names',clean_names),
P
PyCaret 已提交
2283
                 ('feature_select',feature_select),
P
PyCaret 已提交
2284
                 ('fix_multi',fix_multi),
P
PyCaret 已提交
2285
                 ('dfs',dfs),
P
PyCaret 已提交
2286
                 ('pca',pca)
P
pycaret 已提交
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298
                 ])
  
  if test_data is not None:
    return(pipe.fit_transform(train_data),pipe.transform(test_data))
  else:
    return(pipe.fit_transform(train_data))



# ______________________________________________________________________________________________________________________________________________________
# preprocess_all_in_one_unsupervised
def Preprocess_Path_Two(train_data,ml_usecase=None,test_data =None,categorical_features=[],numerical_features=[],time_features=[],features_todrop=[],display_types=False,
P
PyCaret 已提交
2299
                                imputation_type = "simple imputer" ,numeric_imputation_strategy='mean',categorical_imputation_strategy='not_available',
P
PyCaret 已提交
2300 2301
                                apply_zero_nearZero_variance = False,
                                club_rare_levels = False, rara_level_threshold_percentage =0.05,
P
PyCaret 已提交
2302 2303
                                apply_untrained_levels_treatment= False,untrained_levels_treatment_method = 'least frequent',
                                apply_ordinal_encoding = False, ordinal_columns_and_categories= {}, 
P
PyCaret 已提交
2304
                                apply_binning=False, features_to_binn =[],
P
PyCaret 已提交
2305
                                apply_grouping= False , group_name=[] , features_to_group_ListofList=[[]],
P
pycaret 已提交
2306
                                scale_data= False, scaling_method='zscore',
P
PyCaret 已提交
2307
                                Power_transform_data = False, Power_transform_method ='quantile',
P
PyCaret 已提交
2308
                                remove_outliers = False, outlier_contamination_percentage= 0.01,outlier_methods=['pca','iso','knn'],
P
PyCaret 已提交
2309 2310
                                remove_multicollinearity = False, maximum_correlation_between_features= 0.90,  
                                apply_pca = False , pca_method = 'pca_liner',pca_variance_retained_or_number_of_components =.99 , 
P
pycaret 已提交
2311 2312 2313 2314 2315 2316
                                random_state=42

                               ):
  
  '''
    Follwoing preprocess steps are taken:
P
PyCaret 已提交
2317
      - THIS IS BUILt FOR UNSUPERVISED LEARNING , FOLLOWES SAME PATH AS Path_One
P
pycaret 已提交
2318 2319
      - 1) Auto infer data types 
      - 2) Impute (simple or with surrogate columns)
P
PyCaret 已提交
2320 2321 2322 2323 2324 2325
      - 3) Drop categorical variables that have zero variance or near zero variance
      - 4) Club categorical variables levels togather as a new level (other_infrequent) that are rare / at the bottom 5% of the variable distribution
      - 5) Generate sub features from time feature such as 'month','weekday',is_month_end','is_month_start' & 'hour'
      - 6) Scales & Power Transform (zscore,minmax,yeo-johnson,quantile,maxabs,robust) , including option to transform target variable
      - 7) Apply binning to continious variable when numeric features are provided as a list 
      - 8) Detect & remove outliers using isolation forest, knn and PCA
P
PyCaret 已提交
2326
      - 9) One Hot / Dummy encoding
P
PyCaret 已提交
2327 2328 2329
      -10) Remove special characters from column names such as commas, square brackets etc to make it competible with jason dependednt models
      -11) Fix multicollinearity
      -12) Apply diamension reduction techniques such as pca_liner, pca_kernal, incremental, tsne & pls
P
PyCaret 已提交
2330
          - except for pca_liner, all other method only takes number of component (as integer) i.e no variance explaination metohd available  
P
pycaret 已提交
2331 2332 2333 2334 2335
  '''
  
  # just make a dummy target variable
  target_variable = 'dummy_target'
  train_data[target_variable] = 2
P
PyCaret 已提交
2336 2337 2338
  # just to add diversified values to target
  train_data.loc[0:3,target_variable] = 3
 
P
pycaret 已提交
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
  # WE NEED TO AUTO INFER the ml use case
  c1 = train_data[target_variable].dtype == 'int64'
  c2 = len(train_data[target_variable].unique()) <= 20
  c3 = train_data[target_variable].dtype == 'object'
  
  # dummy usecase
  ml_usecase ='regression'
  

  global dtypes 
  dtypes = DataTypes_Auto_infer(target=target_variable,ml_usecase=ml_usecase,categorical_features=categorical_features,numerical_features=numerical_features,time_features=time_features,features_todrop=features_todrop,display_types=display_types)

  
  # for imputation
  global imputer
  if imputation_type == "simple imputer":
    imputer = Simple_Imputer(numeric_strategy=numeric_imputation_strategy, target_variable= target_variable,categorical_strategy=categorical_imputation_strategy)
  else:
    imputer = Surrogate_Imputer(numeric_strategy=numeric_imputation_strategy,categorical_strategy=categorical_imputation_strategy,target_variable=target_variable)
P
PyCaret 已提交
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
  
  # for zero_near_zero
  global znz
  if apply_zero_nearZero_variance == True:
    znz = Zroe_NearZero_Variance(target=target_variable)
  else:
    znz = Empty()
 
  # for rare levels clubbing:
  global club_R_L
  if club_rare_levels == True:
    club_R_L = Catagorical_variables_With_Rare_levels(target=target_variable,threshold=rara_level_threshold_percentage)
  else:
    club_R_L= Empty()
  
P
PyCaret 已提交
2373 2374 2375 2376 2377 2378 2379
  # untrained levels in test
  if apply_untrained_levels_treatment ==  True:
    global new_levels 
    new_levels = New_Catagorical_Levels_in_TestData(target=target_variable,replacement_strategy=untrained_levels_treatment_method)
  else:
    new_levels= Empty()
  
P
PyCaret 已提交
2380 2381 2382 2383 2384 2385 2386
  # ordinal coding
  if apply_ordinal_encoding == True:
    global ordinal
    ordinal = Ordinal(info_as_dict=ordinal_columns_and_categories)
  else:
    ordinal = Empty()
  
P
PyCaret 已提交
2387 2388 2389 2390 2391 2392 2393 2394
  # grouping
  if apply_grouping == True:
    global group
    group = Group_Similar_Features(group_name=group_name,list_of_grouped_features=features_to_group_ListofList)
  else:
    group = Empty()
  

P
PyCaret 已提交
2395 2396
  # binning 
  global binn
P
pycaret 已提交
2397

P
PyCaret 已提交
2398 2399 2400 2401 2402 2403
  if apply_binning == True:
    binn = Binning(features_to_discretize=features_to_binn)
  else:
    binn = Empty()
  
  # for scaling
P
pycaret 已提交
2404 2405
  global scaling ,P_transform
  if scale_data == True:
P
PyCaret 已提交
2406
    scaling = Scaling_and_Power_transformation(target=target_variable,function_to_apply=scaling_method,random_state_quantile=random_state)
P
pycaret 已提交
2407 2408 2409 2410
  else: 
    scaling = Empty()
  
  if Power_transform_data== True:
P
PyCaret 已提交
2411
    P_transform = Scaling_and_Power_transformation(target=target_variable,function_to_apply=Power_transform_method,random_state_quantile=random_state)
P
pycaret 已提交
2412 2413 2414 2415 2416 2417 2418 2419 2420
  else:
    P_transform= Empty()

  # for Time Variables
  global feature_time
  feature_time = Make_Time_Features()
  global dummy
  dummy = Dummify(target_variable)
  
P
PyCaret 已提交
2421 2422 2423
  # remove putliers
  if remove_outliers == True:
    global rem_outliers
P
PyCaret 已提交
2424
    rem_outliers= Outlier(target=target_variable,contamination=outlier_contamination_percentage,random_state=random_state,methods=outlier_methods )
P
PyCaret 已提交
2425 2426 2427
  else:
    rem_outliers = Empty()

P
pycaret 已提交
2428 2429 2430
  # clean column names for special char
  clean_names =Clean_Colum_Names()

P
PyCaret 已提交
2431 2432 2433 2434 2435 2436 2437
  # removing multicollinearity
  if remove_multicollinearity == True: 
    global fix_multi
    fix_multi = Fix_multicollinearity(target_variable=target_variable,threshold=maximum_correlation_between_features,correlation_with_target_preference=0.0)
  else:
    fix_multi = Empty()

P
pycaret 已提交
2438 2439 2440
  # apply pca
  global pca
  if apply_pca == True:
P
PyCaret 已提交
2441 2442
    pca = Reduce_Dimensions_For_Supervised_Path(target=target_variable,method = pca_method ,variance_retained_or_number_of_components=pca_variance_retained_or_number_of_components, random_state=random_state)
  
P
pycaret 已提交
2443 2444 2445 2446 2447 2448 2449
  else:
    pca= Empty()

  global pipe
  pipe = Pipeline([
                 ('dtypes',dtypes),
                 ('imputer',imputer),
P
PyCaret 已提交
2450 2451
                 ('znz',znz),
                 ('club_R_L',club_R_L),
P
PyCaret 已提交
2452
                 ('new_levels',new_levels),
P
PyCaret 已提交
2453
                 ('ordinal',ordinal),
P
pycaret 已提交
2454
                 ('feature_time',feature_time),
P
PyCaret 已提交
2455
                 ('group',group),
P
pycaret 已提交
2456 2457
                 ('scaling',scaling),
                 ('P_transform',P_transform),
P
PyCaret 已提交
2458 2459
                 ('binn',binn),
                 ('rem_outliers',rem_outliers),
P
pycaret 已提交
2460 2461
                 ('dummy',dummy),
                 ('clean_names',clean_names),
P
PyCaret 已提交
2462
                 ('fix_multi',fix_multi),
P
pycaret 已提交
2463 2464 2465 2466 2467 2468 2469 2470 2471
                 ('pca',pca)
                 ])
  
  if test_data is not None:
    train_t = pipe.fit_transform(train_data)
    test_t = pipe.transform(test_data)
    return(train_t.drop(target_variable,axis=1),test_t)
  else:
    train_t = pipe.fit_transform(train_data)
P
PyCaret 已提交
2472
    return(train_t.drop(target_variable,axis=1))