How to select model using Grid Search in Python?
MODEL SELECTION DATA CLEANING PYTHON DATA MUNGING MACHINE LEARNING RECIPES PANDAS CHEATSHEET     ALL TAGS

How to select model using Grid Search in Python?

How to select model using Grid Search in Python?

This recipe helps you select model using Grid Search in Python

0

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.

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)

Relevant Projects

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.

Solving Multiple Classification use cases Using H2O
In this project, we are going to talk about H2O and functionality in terms of building Machine Learning models.

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

Predict Census Income using Deep Learning Models
In this project, we are going to work on Deep Learning using H2O to predict Census income.

German Credit Dataset Analysis to Classify Loan Applications
In this data science project, you will work with German credit dataset using classification techniques like Decision Tree, Neural Networks etc to classify loan applications using R.

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.

Deep Learning with Keras in R to Predict Customer Churn
In this deep learning project, we will predict customer churn using Artificial Neural Networks and learn how to model an ANN in R with the keras deep learning package.

Predict Employee Computer Access Needs in Python
Data Science Project in Python- Given his or her job role, predict employee access needs using amazon employee database.

Mercari Price Suggestion Challenge Data Science Project
Data Science Project in Python- Build a machine learning algorithm that automatically suggests the right product prices.

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.