Machine Learning for Beginners in Python: How to Find Best Preprocessing Steps During Model Selection

Find Best Preprocessing Steps During Model Selection

We have to be careful to properly handle preprocessing when conducting model selection. First, GridSearchCV uses cross-validation to determine which model has the highest performance. However, in cross-validation we are in effect pretending that the fold held out as the test set is not seen, and thus not part of fitting any preprocessing steps (e.g. scaling or standardization). For this reason, we cannot preprocess the data then run GridSearchCV.

Second, some preprocessing methods have their own parameter which often have to be supplied by the user. By including candidate component values in the search space, they are treated like any other hyperparameter be to searched over.


/* Load libraries */
import numpy as np
from sklearn import datasets
from sklearn.feature_selection import SelectKBest
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

/* Set random seed */

Load Iris Dataset

/* Load data */
iris = datasets.load_iris()
X =
y =

Create Proprocessing Object

We are include two different preprocessing steps: principal component analysis and a k-best feature selection.

/* Create a combined preprocessing object */
preprocess = FeatureUnion([('pca', PCA()), ("kbest", SelectKBest(k=1))])

Create Pipeline

/* Create a pipeline */
pipe = Pipeline([('preprocess', preprocess), ('classifier', LogisticRegression())])

Create Search Space Of Hyperparameter Values

/* Create space of candidate values */
search_space = [{'preprocess__pca__n_components': [1, 2, 3],
                 'classifier__penalty': ['l1', 'l2'],
                 'classifier__C': np.logspace(0, 4, 10)}]

/* Create grid search */
clf = GridSearchCV(pipe, search_space, cv=5, verbose=0, n_jobs=-1)

/* Fit grid search */
best_model =, y)

View Best Model’s Hyperparamters

/* View best hyperparameters */
print('Best Number Of Princpal Components:', best_model.best_estimator_.get_params()['preprocess__pca__n_components'])
print('Best Penalty:', best_model.best_estimator_.get_params()['classifier__penalty'])
print('Best C:', best_model.best_estimator_.get_params()['classifier__C'])

Best Number Of Princpal Components: 3
Best Penalty: l1
Best C: 59.9484250319


Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.  

Google –> SETScholars

A list of Python, R and SQL Codes for Applied Machine Learning and Data  Science at by Coding Categories:

  1. Classification:
  2. Data Analytics:
  3. Data Science:
  4. Data Visualisation:
  5. Machine Learning Recipe:
  6. Pandas:
  7. Python:
  9. Supervised Learning:
  10. Tabular Data Analytics:
  11. End-to-End Data Science Recipes:
  12. Applied Statistics:
  13. Bagging Ensemble:
  14. Boosting Ensemble:
  15. CatBoost:
  16. Clustering:
  17. Data Analytics:
  18. Data Science:
  19. Data Visualisation:
  20. Decision Tree:
  21. LightGBM:
  22. Machine Learning Recipe:
  23. Multi-Class Classification:
  24. Neural Networks:
  25. Python Machine Learning:
  26. Python Machine Learning Crash Course:
  27. R Classification:
  28. R for Beginners:
  29. R for Business Analytics:
  30. R for Data Science:
  31. R for Data Visualisation:
  32. R for Excel Users:
  33. R Machine Learning:
  34. R Machine Learning Crash Course:
  35. R Regression:
  36. Regression:
  37. XGBOOST:
  38. Excel examples for beginners:
  39. C Programming tutorials & examples:
  40. Javascript tutorials & examples:
  41. Python tutorials & examples:
  42. R tutorials & examples:
  43. SQL tutorials & examples:


( FREE downloadable Mathematics Worksheet for Kids )