cancel
Showing results for 
Search instead for 
Did you mean: 
Machine Learning
cancel
Showing results for 
Search instead for 
Did you mean: 

Do One-Hot-Encoding (OHE) before or after split data to train and test dataframe

NhatHoang
Valued Contributor II

Hi,

I wonder that I should do OHE before or after I split data to build up a ML model.

Please give some advise.

1 ACCEPTED SOLUTION

Accepted Solutions

LandanG
Honored Contributor
Honored Contributor

Hi @Nhat Hoang​ ,

While not Databricks-specific, here's a good answer:

"If you perform the encoding before the split, it will lead to data leakage (train-test contamination). In this sense, you will introduce new data (integers of Label Encoders) and use it for your models thus it will affect the end predictions results (good validation scores but poor in deployment).

After the train and validation data category is already matched up, you can perform fit_transform on the train data, then only transform for the validation data - based on the encoding maps from the train data.

Almost all feature engineering like standardization, Normalisation etc should be done after the train test split. "

Additionally, if you were to run an AutoML experiment and look at the underlying notebook you should see that the data is split before encoding is applied.

View solution in original post

3 REPLIES 3

LandanG
Honored Contributor
Honored Contributor

Hi @Nhat Hoang​ ,

While not Databricks-specific, here's a good answer:

"If you perform the encoding before the split, it will lead to data leakage (train-test contamination). In this sense, you will introduce new data (integers of Label Encoders) and use it for your models thus it will affect the end predictions results (good validation scores but poor in deployment).

After the train and validation data category is already matched up, you can perform fit_transform on the train data, then only transform for the validation data - based on the encoding maps from the train data.

Almost all feature engineering like standardization, Normalisation etc should be done after the train test split. "

Additionally, if you were to run an AutoML experiment and look at the underlying notebook you should see that the data is split before encoding is applied.

NhatHoang
Valued Contributor II

Hi @Landan George​ ,

Thank you very much. It is clear for me now.

5 stars support, Databricks team. :)​

LandanG
Honored Contributor
Honored Contributor

Thank you @Nhat Hoang​, I'm glad I could help

Welcome to Databricks Community: Lets learn, network and celebrate together

Join our fast-growing data practitioner and expert community of 80K+ members, ready to discover, help and collaborate together while making meaningful connections. 

Click here to register and join today! 

Engage in exciting technical discussions, join a group with your peers and meet our Featured Members.