How to select model using Grid Search in Python?

This recipe helps you select model using Grid Search in Python

Recipe Objective

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

To get the best model we can use Grid Search. Grid Search passes all models that we want one by one and check the result. Finally it gives us the model which gives the best result.

So this recipe is a short example of how we can select model using Grid Search in Python.

Learn to Build a Multi Class Image Classification Model in Python from Scratch

Step 1 - Import the library - GridSearchCv

import numpy as np from sklearn import datasets from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline np.random.seed(0)

Here we have imported various modules like datasets, Logistic Regression, Random Forest Classifier 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 iris dataset and we have created objects X and y to store the data and the target value respectively. iris = datasets.load_iris() X = iris.data y = iris.target

Step 3 - Model and its Parameter

Here, we are using pipeline and defining search space from which grid serch will select a model which will give the best result. pipe = Pipeline([("classifier", RandomForestClassifier())]) search_space = [{"classifier": [LogisticRegression()], "classifier__penalty": ["l1", "l2"], "classifier__C": np.logspace(0, 4, 10) }, {"classifier": [RandomForestClassifier()], "classifier__n_estimators": [10, 100, 1000], "classifier__max_features": [1, 2, 3] }]

Step 4 - 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 model, if not especified then it uses estimator score.
  • cv : In this we have to pass a interger value, as it signifies the number of splits that is needed for cross validation. By default is set as five.
  • n_jobs : This signifies the number of jobs to be run in parallel, -1 signifies to use all processor.

Making an object grid_GBC for GridSearchCV and fitting the dataset i.e X and y clf = GridSearchCV(pipe, search_space, cv=5, verbose=0, n_jobs = -1) best_model = clf.fit(X, y) Now we are using print statements to print the results. It will give best model as a result. print(best_model.best_estimator_.get_params()["classifier"]) As an output we get:

LogisticRegression(C=7.742636826811269, class_weight=None, dual=False,
          fit_intercept=True, intercept_scaling=1, max_iter=100,
          multi_class="warn", n_jobs=None, penalty="l1", random_state=None,
          solver="warn", tol=0.0001, verbose=0, warm_start=False)

Download Materials


What Users are saying..

profile image

Ray han

Tech Leader | Stanford / Yale University
linkedin profile url

I think that they are fantastic. I attended Yale and Stanford and have worked at Honeywell,Oracle, and Arthur Andersen(Accenture) in the US. I have taken Big Data and Hadoop,NoSQL, Spark, Hadoop... Read More

Relevant Projects

BigMart Sales Prediction ML Project in Python
The goal of the BigMart Sales Prediction ML project is to build and evaluate different predictive models and determine the sales of each product at a store.

Credit Card Fraud Detection as a Classification Problem
In this data science project, we will predict the credit card fraud in the transactional dataset using some of the predictive models.

Recommender System Machine Learning Project for Beginners-4
Collaborative Filtering Recommender System Project - Comparison of different model based and memory based methods to build recommendation system using collaborative filtering.

Langchain Project for Customer Support App in Python
In this LLM Project, you will learn how to enhance customer support interactions through Large Language Models (LLMs), enabling intelligent, context-aware responses. This Langchain project aims to seamlessly integrate LLM technology with databases, PDF knowledge bases, and audio processing agents to create a comprehensive customer support application.

BERT Text Classification using DistilBERT and ALBERT Models
This Project Explains how to perform Text Classification using ALBERT and DistilBERT

Demand prediction of driver availability using multistep time series analysis
In this supervised learning machine learning project, you will predict the availability of a driver in a specific area by using multi step time series analysis.

Build a Customer Churn Prediction Model using Decision Trees
Develop a customer churn prediction model using decision tree machine learning algorithms and data science on streaming service data.

Build a Music Recommendation Algorithm using KKBox's Dataset
Music Recommendation Project using Machine Learning - Use the KKBox dataset to predict the chances of a user listening to a song again after their very first noticeable listening event.

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.

Time Series Python Project using Greykite and Neural Prophet
In this time series project, you will forecast Walmart sales over time using the powerful, fast, and flexible time series forecasting library Greykite that helps automate time series problems.

OSZAR »