How to tune Hyper parameters using Grid Search in Python?

How to tune Hyper parameters using Grid Search in Python?

How to tune Hyper parameters using Grid Search in Python?

This recipe helps you tune Hyper parameters using Grid Search in Python


Recipe Objective

Many a times while working on a dataset and using a Machine Learning model we don"t know which set of hyperparameters will give us the best result. Passing all sets of hyperparameters manually through the model and checking the result might be a hectic work and may not be possible to do.

To get the best set of hyperparameters we can use Grid Search. Grid Search passes all combinations of hyperparameters one by one into the model and check the result. Finally it gives us the set of hyperparemeters which gives the best result after passing in the model.

So this recipe is a short example of how can tune Hyper-parameters using Grid Search in Python

Step 1 - Import the library - GridSearchCv

import numpy as np from sklearn import linear_model, datasets from sklearn.model_selection import GridSearchCV

Here we have imported various modules like datasets, linear_model and GridSearchCV from differnt libraries. We will understand the use of these later while using it in the in the code snipet.
For now just have a look on these imports.

Step 2 - Setup the Data

Here we have used datasets to load the inbuilt wine dataset and we have created objects X and y to store the data and the target value respectively. dataset = datasets.load_wine() X = y =

Step 3 - Using Model

Here, we are using Logistic Regression as a Machine Learning model to use GridSearchCV. So we have created an object Logistic. logistic = linear_model.LogisticRegression()

Step 5 - Parameters to be optimized

Logistic Regression requires two parameters "C" and "penalty" to be optimised by GridSearchCV. So we have set these two parameters as a list of values form which GridSearchCV will select the best value of parameter. C = np.logspace(0, 4, 10) penalty = ["l1", "l2"] hyperparameters = dict(C=C, penalty=penalty)

Step 6 - Using GridSearchCV and Printing Results

Before using GridSearchCV, lets have a look on the important parameters.

  • estimator: In this we have to pass the models or functions on which we want to use GridSearchCV
  • param_grid: Dictionary or list of parameters of models or function in which GridSearchCV have to select the best.
  • Scoring: It is used as a evaluating metric for the model performance to decide the best hyperparameters, if not especified then it uses estimator score.
Making an object clf for GridSearchCV and fitting the dataset i.e X and y clf = GridSearchCV(logistic, hyperparameters, cv=5, verbose=0) best_model =, y) Now we are using print statements to print the results. It will give the values of hyperparameters as a result. print("Best Penalty:", best_model.best_estimator_.get_params()["penalty"]) print("Best C:", best_model.best_estimator_.get_params()["C"]) As an output we get:

Best Penalty: l1
Best C: 59.94842503189409

Relevant Projects

Natural language processing Chatbot application using NLTK for text classification
In this NLP AI application, we build the core conversational engine for a chatbot. We use the popular NLTK text classification library to achieve this.

Build an Image Classifier for Plant Species Identification
In this machine learning project, we will use binary leaf images and extracted features, including shape, margin, and texture to accurately identify plant species using different benchmark classification techniques.

Customer Churn Prediction Analysis using Ensemble Techniques
In this machine learning churn project, we implement a churn prediction model in python using ensemble techniques.

Data Science Project on Wine Quality Prediction in R
In this R data science project, we will explore wine dataset to assess red wine quality. The objective of this data science project is to explore which chemical properties will influence the quality of red wines.

Machine Learning project for Retail Price Optimization
In this machine learning pricing project, we implement a retail price optimization algorithm using regression trees. This is one of the first steps to building a dynamic pricing model.

Music Recommendation System Project using Python and R
Machine Learning Project - Work with KKBOX's Music Recommendation System dataset to build the best music recommendation engine.

PySpark Tutorial - Learn to use Apache Spark with Python
PySpark Project-Get a handle on using Python with Spark through this hands-on data processing spark python tutorial.

Ensemble Machine Learning Project - All State Insurance Claims Severity Prediction
In this ensemble machine learning project, we will predict what kind of claims an insurance company will get. This is implemented in python using ensemble machine learning algorithms.

Loan Eligibility Prediction using Gradient Boosting Classifier
This data science in python project predicts if a loan should be given to an applicant or not. We predict if the customer is eligible for loan based on several factors like credit score and past history.

Learn to prepare data for your next machine learning project
Text data requires special preparation before you can start using it for any machine learning project.In this ML project, you will learn about applying Machine Learning models to create classifiers and learn how to make sense of textual data.