Skip to content

KNN as a Feature Engine with Imbalanced Data (Part 2)

By William Rodriguez
InsightsData Science

KNN as a Feature Engine can aid in ensemble learning by quantifying anecdotal knowledge through supervised machine learning.

Executive overview

KNN as a Feature Engine can aid in ensemble learning by quantifying anecdotal knowledge through supervised machine learning.

A good example would be targeting a minority group of customers who are known to have a desirable trait (e.g., similar features/patterns in customer behavior indicative of higher ‘value’ buyers, etc.).

Part two of this two-part series incorporates the KNN Feature Engine from part one into different ensemble models and reviews the findings.

The details

The full model can be reviewed in our video walkthrough on YouTube. We walk through the code to help you understand this template, fast!

Part one (updates)

Since the last post, there have been momentous changes to the code that warrant a part one update. In this section, we will go over the high-level details (as it pertains to continuing with part two) so that we can continue with our ‘ensemble-journey’.

Summary of part one updates:

  • The prototype ‘bias’ feature is now working! This allows us to train, fit, and generalize models as the data has real abnormalities to exploit.
  • A validate/test/deploy paradigm has been adopted, allowing us to test trained models on a hold-out set to authenticate generalization capabilities! This also allows us to control data leakage, enabling stronger, more reliable models!
  • An ensemble of changes, including new functions, loops, and other coding enhancements, makes the code more resilient, readable, functional, and robust than before!

As it relates to part one, the training output needs to be updated to show new outputs based on training changes (see below):

Validation results at K = 3 with bias on: F1 rises from 4.22% with no change to 30.66% with ENN, as each resampling step is added

As you can see, we are still tracking with a standard ‘value-increase’ as we process this imbalanced data (the no-transformation starting point is not valid; see the editor's note under the code). However, the surprise comes when applying the ‘best’ model to the test set. You can see a nearly 20% decrease in precision, recall, and F1 score (17.7, 15.3, 17.2% decrease respectively)! This is a huge hit to the most important metrics, and it also portrays a more important story: our model doesn’t generalize to new data well. This means we were overfitting the noise and not the signal.

Best validation output per transformation; the best ENN model scores a 32.29% F1 on validation but drops to 26.75% on the test set

To combat this, we select another model that predicts and generalizes well, and we use that for our ensemble learning model.

An alternative ENN model with K = 19 scores a 30.7% F1 on validation and 29.03% on test, a much smaller drop

Here is a ChatGPT excerpt on ‘considering generalization’:

ChatGPT answer on judging generalization: compare validation and test results against a baseline, the business objective and trade-offs
ChatGPT closing note: always test the final model on new, unseen data that was not used anywhere in modeling, including cross-validation

Finally, we deploy this model and compare the results against the ‘randomized control’ benchmark from part one in this series. You can see the massive gains in predictive power over random chance alone. This output will feed into part two of this model, where we combine this feature-engine/pseudo-label into our ensemble model.

Deployed ENN model vs. the random control: precision up 108.47%, recall up 72.15% and F1 up 101.32%

For more information on the part one update and the training data, please reference the addendum at the bottom of this article.

The code

KNN as a feature engine (part one updated, R)

##########################
## Establish Environment
##########################
## Packages
  library('pacman')
  pacman::p_load(dplyr,rpart,FNN,performanceEstimation,unbalanced, caret, mgcv)
## User Defined Parameters
  ## KNN Objectives
    Model_Evaluation <- 'DEPLOY' ## VALIDATE | TEST | DEPLOY
    KNN_TrainSet_Change <- 'ENN' ## NONE | SCALE | SMOTE | TOMEK | ENN
  ## KNN Parameters
    KNN_K = 19 ##Run once (K=1),then run 'TEST-K' script below for optimization
    SMOTE_PrcOver = 3
    SMOTE_PrcUnder = 1.34
    ENN_K = 3
  ## Dataset Parameters
    df_Size <- 10000 ## Magnitude of 10 (e.g., 10, 100, 1000, etc.)
    df_Imbal <- 0.1 ## Works best <= 0.5
    df_Bias <- 'BIAS' ## NONE | BIAS << None = Random, Bias = Bias data
  ## Splits
    Pc_Train = .80
    Pc_valid = .5 ##Allocates this percentage of remaining data to valid
## Data
  set.seed(2023)
  Index <- 1 + (0:(df_Size - 1)) * 1
  df<-data.frame(IndexID=as.factor(Index),y=rep(as.factor(c('0','1'))
      ,times=c(ceiling(as.integer(df_Size*(1-df_Imbal)))
               ,ceiling(as.integer(df_Size*df_Imbal)))))
  df$x1=if(df_Bias=='BIAS'){ifelse(df$y=='1',rnorm(sum(df$y=='1'),sd=0.5)
                                   ,rnorm(sum(df$y=='0')))}else{rnorm(df_Size)}
  df$x2=if(df_Bias=='BIAS'){ifelse(df$y=='1',rnorm(sum(df$y=='1'),sd=0.5)
                                   ,rnorm(sum(df$y=='0')))}else{rnorm(df_Size)}
## Functions
  knn_predict <-function(train_Data, test_Data, train_Class, K_param){
    knn(train=train_Data,test=test_Data,cl=train_Class,prob=TRUE,k=K_param)}
  knn_evaluate <- function(Type, Knn_Model, TestClass){
    cm <- table ( TestClass, Knn_Model )
    print ( cm )
    if(all(c(0,1) %in% Knn_Model)) {
        Accuracy <- round( (cm[1,1]+cm[2,2]) / sum(cm[]), digits = 4) * 100
        Precision <- round( cm[2,2] / sum(cm[,2]), digits = 4)* 100
        Specificity <- round( cm[1,1] / sum(cm[1,]), digits = 4)* 100
        Recall <- round( cm[2,2] / sum(cm[2,]), digits = 4)* 100
        F1Score<- round(2*((Precision*Recall)/(Precision+Recall)),digits=2)
      print( paste('Model=',Type,': Accuracy=',Accuracy,'% | Precision='
                ,Precision,'% | Specificity=',Specificity,'% | Recall=',Recall
                ,'% | F1Score=',F1Score,'%'))
      }else{print(paste('Model=',Model_Evaluation
              ,': Only one class predicted. Metrics cannot be calculated.'))}}
##########################
## KNN PREP: Split, Scale, SMOTE, TOMEK, ENN
##########################
## Shuffle & SPLIT
  df <- sample_frac(df,1)
  tIndex<-createDataPartition(df$y,p=Pc_Train,list=FALSE,times=1)
  vIndex<-createDataPartition(df$y[-tIndex],p=Pc_valid,list=FALSE,times=1)
    train <- df[tIndex,]
    valid <- df[-tIndex,][vIndex,]
    test <- df[-tIndex,][-vIndex,]
## SCALE
  train_scale <- scale ( train[,3:4] )
  test_scale <- scale ( test[,3:4] )
  valid_scale <- scale ( valid[,3:4] )
## SMOTE
  train_scale_smote <-
    performanceEstimation::smote(y~x1+x2,data=mutate(as.data.frame(train_scale)
                ,y=train[,2]),perc.over=SMOTE_PrcOver,perc.under=SMOTE_PrcUnder)
## TOMEK
  Tomek <- ubTomek( train_scale_smote[,-3], train_scale_smote[,3] )
    train_scale_smote_TOMEK <- cbind(Tomek$Y, Tomek$X)
    colnames( train_scale_smote_TOMEK) <- c("y", "x1" , "x2")
## ENN
  ENN <- ubENN( train_scale_smote[,-3], train_scale_smote[,3] , k = ENN_K )
    train_scale_smote_ENN <- cbind(ENN$Y, ENN$X)
    colnames( train_scale_smote_ENN) <- c("y", "x1" , "x2")
##########################
## KNN
##########################
## KNN Evaluation Parameters
  KNN_Train <-
    if (KNN_TrainSet_Change %in% 'NONE') { train[,3:4]
      } else if(KNN_TrainSet_Change %in% 'SCALE') {train_scale
      } else if(KNN_TrainSet_Change %in% 'SMOTE') {train_scale_smote[,-3]
      } else if(KNN_TrainSet_Change %in% 'TOMEK') {train_scale_smote_TOMEK[,-1]
      } else if(KNN_TrainSet_Change %in% 'ENN') {train_scale_smote_ENN[,-1]
      }
  KNN_TrainClass <-
    if (KNN_TrainSet_Change %in% c('NONE','SCALE')) {train[,2]
      } else if (KNN_TrainSet_Change %in% 'SMOTE') {train_scale_smote[,3]
      } else if (KNN_TrainSet_Change %in% 'TOMEK') {train_scale_smote_TOMEK[,1]
      } else if (KNN_TrainSet_Change %in% 'ENN') {train_scale_smote_ENN[,1]
      }
  KNN_Test_Tr<-if(KNN_TrainSet_Change == 'NONE'){train[,3:4]}else{train_scale}
  KNN_Test_V<-if(KNN_TrainSet_Change == 'NONE'){valid[,3:4]}else{valid_scale}
  KNN_Test_Tt<-if(KNN_TrainSet_Change == 'NONE'){test[,3:4]}else{test_scale}
  KNN_TestClass_Tr <- train[,2]
  KNN_TestClass_V <- valid[,2]
  KNN_TestClass_Tt <-test[,2]
## KNN MODELS
  KNN_Model_Train <- knn_predict(KNN_Train, KNN_Test_Tr, KNN_TrainClass, KNN_K)
  KNN_Model_Valid <- knn_predict(KNN_Train, KNN_Test_V, KNN_TrainClass, KNN_K)
  KNN_Model_Test <- knn_predict(KNN_Train, KNN_Test_Tt, KNN_TrainClass, KNN_K)
## KNN as Feature Engine (PSEUDO-LABELING|SELF-TRAINING)
if(Model_Evaluation=='VALIDATE'){
  knn_evaluate('Validate', KNN_Model_Valid, KNN_TestClass_V )} else
  if(Model_Evaluation=='TEST')
    {knn_evaluate('Test',KNN_Model_Test,KNN_TestClass_Tt)} else
  if(Model_Evaluation=='DEPLOY') {
  ## Feature Engineering
    ## Training set for Ensemble Learning (Part 2)
      KNN_Model_Final <- knn_predict(KNN_Train, KNN_Train,KNN_TrainClass, KNN_K)
      KNN_Train_Final <- mutate(as.data.frame(KNN_Train),y=KNN_TrainClass)
        KNN_Train_Final$Class <- KNN_Model_Final
        KNN_Train_Final$ClassScore <- attr( KNN_Model_Final, "prob" )
        ##View Train Evaluation:
          # knn_evaluate('FINAL', KNN_Train_Final[,4], KNN_Train_Final[,3] )
    ## Test & Validation sets for Ensemble (Part 2)
      KNN_Test_Tr <- mutate(as.data.frame(KNN_Test_Tr),y=KNN_TestClass_Tr)
        KNN_Test_Tr$Class <- KNN_Model_Train
        KNN_Test_Tr$ClassScore <- attr(KNN_Model_Train, "prob")
      KNN_Test_V <- mutate(as.data.frame(KNN_Test_V),y=KNN_TestClass_V)
        KNN_Test_V$Class <- KNN_Model_Valid
        KNN_Test_V$ClassScore <- attr(KNN_Model_Valid, "prob")
      KNN_Test_Tt <- mutate(as.data.frame(KNN_Test_Tt),y=KNN_TestClass_Tt)
        KNN_Test_Tt$Class <- KNN_Model_Test
        KNN_Test_Tt$ClassScore <- attr(KNN_Model_Test, "prob" )
    ## Review Results So Far
    df_results <- rbind ( KNN_Test_V, KNN_Test_Tr , KNN_Test_Tt )
      knn_evaluate('DEPLOY',df_results[,4],df_results[,3])
    ##Clear Memory
    rm(df_results)
}

Testing K (part one updated, R)

k_values <- c(3, 5, 7, 15, 19)  # List of K values to iterate over
 
for (k in k_values) {
  KNN_Model_Valid <- knn_predict(KNN_Train, KNN_Test_V, KNN_TrainClass, k)
  knn_evaluate(paste('K=', k, sep=''), KNN_Model_Valid, KNN_TestClass_V)
}

Ensemble learning (part two, R)

##########################
## Establish Environment
##########################
## User Defined Parameters
  Model_Evaluation <- 'VALIDATE' ## VALIDATE | TEST | DEPLOY
  FeatureEngine_Avail <- 'N' ## Y | N
  Tree_y_Weight = .5 ## 0 through 1
  Tree_cp = .01
  Tree_minsplit = 10
## Other Parameters
  set.seed(2023)
  ## Functions
  Model_Predict<-function(model,eval_data,model_name){
    predictions <- if(model_name=='Tree'){predict(model,newdata=eval_data)}else
      predict(model, newdata = eval_data, type = "response")
    ifelse(predictions >= .5, 1, 0)
  }
  Model_Evalaute<-function(model,eval_data_class,model_name){
    cm <- if (model_name == 'Tree') {
        table ( eval_data_class, model[,2] )
        } else table ( eval_data_class, as.vector(model) )
    print ( cm )
    if(all(c(0,1) %in% model)) {
        Accuracy <- round( (cm[1,1]+cm[2,2]) / sum(cm[]), digits = 4) * 100
        Precision <- round( cm[2,2] / sum(cm[,2]), digits = 4)* 100
        Specificity <- round( cm[1,1] / sum(cm[1,]), digits = 4)* 100
        Recall <- round( cm[2,2] / sum(cm[2,]), digits = 4)* 100
        F1Score<- round(2*((Precision*Recall)/(Precision+Recall)),digits=2)
      print( paste('Model=',model_name,': Accuracy=',Accuracy,'% | Precision='
                ,Precision,'% | Specificity=',Specificity,'% | Recall=',Recall
                ,'% | F1Score=',F1Score,'%'))
      }else{print(paste('Model=',model_name
              ,': Only one class predicted. Metrics cannot be calculated.'))}
  }
  ## Other
  if(FeatureEngine_Avail=="Y"){
        Columns<-c('y','x1','x2','Class')#,'ClassScore')
        selected_cols<-c('x1','x2','Class')#,'ClassScore')
        Formula=y~x1+x2+Class#+ClassScore
      } else if (FeatureEngine_Avail=="N"){
        Columns<-c('y','x1','x2')
        selected_cols<-c('x1','x2')
        Formula=y~x1+x2
  }
##########################
## ENSEMBLE PREP
##########################
  Enmbl_Training <- KNN_Train_Final[Columns]
  Enmbl_Vld <- KNN_Test_V[Columns] ## Ensemble Valid
  Enmbl_Tst <- KNN_Test_Tt[Columns] ## Ensemble Test
  Enmbl_Trn <- KNN_Test_Tr[Columns] ## Ensemble Train
  weights = ifelse(Enmbl_Training$y == 1, Tree_y_Weight, (1-Tree_y_Weight))
 
##########################
## ENSEMBLE MODELS
##########################
## Models || GAM note: variable optimization: y ~ s(x)...
GAM<-gam(as.formula(Formula),data=Enmbl_Training,family=binomial())
GLM<-glm(y~.,data=Enmbl_Training,family=binomial(link="logit"))
Tree<-rpart(y~.,data=Enmbl_Training,method="class", weights = weights
            ,control = rpart.control(cp=Tree_cp, minsplit = Tree_minsplit)
            )
## Predictions
GAM_Pred_Tr<-Model_Predict(GAM,as.data.frame(Enmbl_Trn[selected_cols]),'GAM')
GAM_Pred_V<-Model_Predict(GAM,as.data.frame(Enmbl_Vld[selected_cols]),'GAM')
GAM_Pred_Tt<-Model_Predict(GAM,as.data.frame(Enmbl_Tst[selected_cols]),'GAM')
GLM_Pred_Tr<-Model_Predict(GLM,as.data.frame(Enmbl_Trn[selected_cols]),'GLM')
GLM_Pred_V<-Model_Predict(GLM,as.data.frame(Enmbl_Vld[selected_cols]),'GLM')
GLM_Pred_Tt<-Model_Predict(GLM,as.data.frame(Enmbl_Tst[selected_cols]),'GLM')
Tree_Pred_Tr<-Model_Predict(Tree,as.data.frame(Enmbl_Trn[selected_cols]),'Tree')
Tree_Pred_V<-Model_Predict(Tree,as.data.frame(Enmbl_Vld[selected_cols]),'Tree')
Tree_Pred_Tt<-Model_Predict(Tree,as.data.frame(Enmbl_Tst[selected_cols]),'Tree')
## Evaluations
if (Model_Evaluation == "VALIDATE") {
    Model_Evalaute(GAM_Pred_V,Enmbl_Vld$y,'GAM' )
    Model_Evalaute(GLM_Pred_V,Enmbl_Vld$y,'GLM' )
    Model_Evalaute(Tree_Pred_V,Enmbl_Vld$y,'Tree' )
  } else if (Model_Evaluation == "TEST") {
    Model_Evalaute(GAM_Pred_Tt,Enmbl_Tst$y,'GAM' )
    Model_Evalaute(GLM_Pred_Tt,Enmbl_Tst$y,'GLM' )
    Model_Evalaute(Tree_Pred_Tt,Enmbl_Tst$y,'Tree' )
  } else if(Model_Evaluation=='DEPLOY') {
    ## Predict Over Train
      Enmbl_Trn$GAMClass <- GAM_Pred_Tr
      Enmbl_Trn$GLMClass <- GLM_Pred_Tr
      Enmbl_Trn$TreeClass <- Tree_Pred_Tr[,2]
    ## Predict Over Valid
      Enmbl_Vld$GAMClass <- GAM_Pred_V
      Enmbl_Vld$GLMClass <- GLM_Pred_V
      Enmbl_Vld$TreeClass <- Tree_Pred_V[,2]
    ## Predict Over Test
      Enmbl_Tst$GAMClass <- GAM_Pred_Tt
      Enmbl_Tst$GLMClass <- GLM_Pred_Tt
      Enmbl_Tst$TreeClass <- Tree_Pred_Tt[,2]
    ## Combine
      Ensemble_Final<-rbind(Enmbl_Trn,Enmbl_Vld,Enmbl_Tst)
    ## Evaluate >> Code differently based on variables available
      if ( FeatureEngine_Avail == 'Y' ) {
        Model_Evalaute (Ensemble_Final[,5],Ensemble_Final[,1],'GAM' )
        Model_Evalaute (Ensemble_Final[,6],Ensemble_Final[,1],'GLM' )
        Model_Evalaute (Ensemble_Final[,7],Ensemble_Final[,1],' Tree' )
      } else {
        Model_Evalaute (Ensemble_Final[,4],Ensemble_Final[,1],'GAM' )
        Model_Evalaute (Ensemble_Final[,5],Ensemble_Final[,1],'GLM' )
        Model_Evalaute (Ensemble_Final[,6],Ensemble_Final[,1],' Tree' )
      }
}

Part two

Overview

This section will evaluate the impact of using K-Nearest Neighbors (KNN) as a feature engine on our imbalanced dataset, where the data distribution is skewed towards one class. The output of the KNN algorithm will serve as an attribute for subsequent ensemble learning models, a combination of various machine learning algorithms to achieve better predictive performance. However, it is important to note that our findings here may not necessarily guarantee similar results in different contexts. Our primary aim is to present a comprehensive example, highlight significant methodologies, and provide you with an additional tool for your data science toolkit.

With that said, let’s dive right into the code!

Section one: establish environments

Section one is broken into two main subsections: User Defined Parameters and ‘Other’. We will cover each subsection respectively.

R code for the ensemble Establish Environment section: evaluation mode, feature-engine switch, tree weight, cp and minsplit, plus predict and evaluate functions
  • User Defined Parameters
    • Model_Evaluation: This determines the model’s evaluation. ‘Validate’ runs the model over the validation dataset, ‘test’ runs the model over the test dataset, and ‘deploy’ evaluates the whole model, generating an output.
    • FeatureEngine_Avail: This includes/excludes the KNN-Feature-Engine parameters from part one. Y includes, N excludes.
    • Tree_y_Weight: Controls the weights parameter from rpart. Technical information on the parameter can be found in the rpart reference manual on CRAN; a general overview can be found on Stack Overflow: “How to apply weights in rpart?”
    • Tree_cp: Controls the cp parameter from rpart; it’s a pruning technique that functions as follows: “don’t split a partition if the new partition does not ‘significantly’ reduce the impurity” (Bruce & Bruce, p.226). Technical information on the parameter can be found in the rpart reference manual on CRAN.
    • Tree_minsplit: Controls the minsplit parameter from rpart. It’s a pruning technique: “Avoid splitting a partition if a resulting subpartition is too small, or if a terminal leaf is too small” (Bruce & Bruce, p.226). Technical information on the parameter can be found in the rpart reference manual on CRAN; a general overview can be found on Medium: “Minsplit and Minbucket”
  • Other Parameters
    • set.seed: enables replicable randomness. More information here: Statology, “How (And When) to Use set.seed in R”
    • Functions
      • Model_Predict: accepts inputs and outputs the ‘predictions’ from the desired model.
        • Input 1, model: this is the model as defined in section ‘Ensemble Models’ > ‘Models’
        • Input 2, eval_data: this is the dataset to be predicted over
        • Input 3, model_name: this is a user-defined model name. Please use ‘Tree’ for decision trees
      • Model_Evalaute: accepts inputs and evaluates the output from Model_Predict.
        • Input 1, model: this is the model to be evaluated from ‘Ensemble Models’ > ‘Predictions’
        • Input 2, eval_data_class: these are the respective classifiers for the Model_Predict eval_data
        • Input 3, model_name: this is a user-defined model name. Please use ‘Tree’ for decision trees
    • Other: These are other dynamic parameters that update based on the output from FeatureEngine_Avail.

Section two: ensemble prep

This is a very simple section that establishes ensemble dataset names. Additionally, weights are created based on the User Defined Parameter Tree_y_Weight and the Enmbl_Training dataset.

R code for the ensemble prep section: naming the training, validation, test and train sets and building class weights from Tree_y_Weight

Section three: ensemble models

This section procures the models, makes predictions, and outputs the evaluations based on the user-defined response for Model_Evaluation.

R code for the ensemble models section: fitting GAM, GLM and rpart decision tree models, predicting on each set, and evaluating by mode

Models

Three models are being utilized in this ensemble script: GAM, GLM, and Decision Tree. Each will be evaluated separately to review their efficacy over this dataset. As noted in the script, GAM can be further optimized by adding automatic knots for spline terms (Bruce & Bruce, p.170); a good overview can be found on Stack Overflow: “mgcv: How to set number and / or locations of knots for splines”.

Predictions

Predictions are evaluated for each model over each dataset (train/valid/test). This is done so predictions aren’t duplicated based on the ‘model evaluation’ (i.e., reduce duplicative code). Terms for the custom function can be found above for the Model_Evalaute function.

Evaluations

This section evaluates the model based on the user-defined Model_Evaluation. Model_Evaluation == VALIDATE will predict and evaluate over the validate set, Model_Evaluation == TEST will predict and evaluate over the test set, and Model_Evaluation == DEPLOY will predict over the train, validate, and testing sets, merge the results, and then procure the results based on whether the user added the KNN feature engine.

Results

Let me reiterate that we have developed three models which offer users a variety of training options for their datasets. It's crucial to remember that these models' performance may vary across different applications, so the superior performance of a model on a randomized dataset does not automatically translate into all scenarios. Now, let's explore the performance of these models!

Model comparison

Initially, we test our ensemble method's efficacy by comparing results with and without the KNN Feature Engine. Without KNN features, the highest performing ‘Validate’ model was the Decision Tree Model (weight of 0.5). With KNN features, it was the same Decision Tree Model, but with a reduced weight of 0.25. The comparison of the validation outputs is shown below.

Validation results: the decision tree with KNN features beats the tree without them on accuracy, precision, specificity and F1, but loses 28.92% recall

Model evaluation on new data

Next, we evaluate each model on new data (‘TEST’) and assess their generalization capabilities. The Decision Tree Model with KNN once again outshines the same model without KNN, showing improvement in all performance metrics except Recall. This can be explained by the precision-recall trade-off, a phenomenon where an increase in precision often leads to a decrease in recall (for more information on the precision-recall trade-off, refer to this Medium article). However, this relationship isn't always the case. Both models generalize well, with a deviance of less than 5%.

Test results: the decision tree with KNN features again improves accuracy 21.55%, precision 20.3% and F1 5.36%, with recall down 31.76%
Generalization test: both trees change less than 2.5% on every metric between validation and test, so neither overfits the validation set

Model selection and deployment

Finally, we select and deploy the highest-performing model, the Decision Tree with KNN features, and compare its performance against random chance and the standalone KNN model.

Deployed tree with KNN features vs. random chance and standalone KNN: F1 rises to 36.07%, 7.54% above KNN alone, while recall falls 23.97%

As shown, the ensemble Decision Tree model outperforms the standalone KNN model in all scenarios except recall. Interestingly, without the KNN feature engine, the ensemble model wouldn't perform as well as the standalone KNN model! You can observe this by evaluating the earlier ‘Tree (No KNN)’ model.

The tree without KNN features scores below standalone KNN on accuracy, precision, specificity and F1, beating it only on recall by 1.89%

Conclusion

From these results, it's fair to say that incorporating KNN as a feature engine significantly enhances the performance of the Decision Tree Model.

Final consideration

In conclusion, this script is intended to enrich your data science toolkit. For future enhancements, we suggest incorporating auto-hyperparameter tuning and delving deeper into each model's optimization. Even in its current form, we believe this script and its analysis can effectively guide users on how to utilize KNN as a feature engine for imbalanced datasets. We hope you find this resource valuable and look forward to your feedback.

If you want help putting models like these to work on your own data, reach out to Analytical Ants.

Addendum: part 1 updates

Code overview

Below are sections with significant code differences. These are quick explanations.

Section: establish environments

  • User Defined Parameters
    • (Splits) Pc_Train is the percentage of the data frame used for training data.
    • (Splits) Pc_Valid is the percentage of the remaining dataset used for the valid dataset.
  • Functions
    • knn_predict: This function evaluates the KNN model over the inputs. train_Data is the training dataset, test_Data is the testing dataset, train_Class is the classification data for the train_Data, and K_param is the K value for the model.
    • knn_evaluate: This function evaluates the KNN model from knn_predict. Type is a user-defined model type (e.g., test, validate, etc.), Knn_Model is the KNN model to be evaluated, and TestClass holds the classifications for the test_Data used in the knn_predict model.

Section: KNN prep

Shuffle & Split: This section now splits into three datasets for train, valid, and test.

Section: KNN

This section now encompasses the old ‘KNN (Training)’ and ‘KNN as a Feature Engine’ sections.

KNN Models: Updated for three models for train, test, and validate.

KNN as a Feature Engine: This section now deploys the appropriate KNN model and evaluation based on the user-defined Model_Evaluation. The final ‘Deploy’ section deploys predictions to the train, test, valid, and training datasets. The difference between train and training datasets is that the train dataset is pre-SMOTE data. The train, test, and valid sets are merged for evaluation and then cleared from memory for space.

Section: testing K

This section greatly simplifies the KNN testing script as it now loops through custom functions based on the defined k_values provided. Update these k_values to update k-tested values.

Training model outputs

Below are the training model outputs with the highest F1 score per category (corresponding to ‘Best Output’ per ‘part one updates’ table above) highlighted in yellow.

Validation output by K with no training-set change; K = 5 is highlighted as best with a 4.48% F1, and K of 15 or more predicts no positives
Validation output by K with scaling only; K = 3 is highlighted as best with a 13.42% F1
Validation output by K for SMOTE at 25%, 33% and 50% minority; the 50% distribution with K = 19 is highlighted as best with a 31.49% F1
Validation output by K for Tomek links after SMOTE at 25%, 33% and 50%; 50% with K = 7 is highlighted as best with a 30.77% F1
Validation output by K for ENN after SMOTE at 25% minority, at ENN_K of 3, 7 and 9
ENN (SMOTE = 25%)
Validation output by K for ENN after SMOTE at 33% minority, at ENN_K of 3, 7 and 9
ENN (SMOTE = 33%)
Validation output by K for ENN after SMOTE at 50% minority; ENN_K = 3 with K = 7 is highlighted as best with a 32.29% F1
ENN (SMOTE = 50%)

References

  1. “Practical Statistics for Data Scientists”, Peter Bruce & Andrew Bruce. Amazon (affiliate link)
KNN Feature Engine for Ensemble Models in R (Part 2) | Analytical Ants