How to select model using Grid Search in Python?

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

In [1]:
## How to select model using Grid Search in Python
def Snippet_144():
    print(format('How to select model using Grid Search in Python','*^82'))

    import warnings

    # load libraries
    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

    # Set random seed

    # Load Iris Dataset
    iris = datasets.load_iris()
    X =
    y =

    # Create Pipeline With Model Selection Search Space
    pipe = Pipeline([('classifier', RandomForestClassifier())])

    # Create space of candidate learning algorithms and their hyperparameters
    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]

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

    # Conduct Model Selection Using Grid Search
    best_model =, y)

    # View best model
    print(); print(best_model.best_estimator_.get_params()['classifier'])

*****************How to select model using Grid Search in Python******************

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

Identifying Product Bundles from Sales Data Using R Language
In this data science project in R, we are going to talk about subjective segmentation which is a clustering technique to find out product bundles in sales data.

Zillow’s Home Value Prediction (Zestimate)
Data Science Project in R -Build a machine learning algorithm to predict the future sale prices of homes.

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.

Data Science Project - Instacart Market Basket Analysis
Data Science Project - Build a recommendation engine which will predict the products to be purchased by an Instacart consumer again.

Data Science Project in Python on BigMart Sales Prediction
The goal of this data science project is to build a predictive model and find out the sales of each product at a given Big Mart store.

Perform Time series modelling using Facebook Prophet
In this project, we are going to talk about Time Series Forecasting to predict the electricity requirement for a particular house using Prophet.

Forecast Inventory demand using historical sales data in R
In this machine learning project, you will develop a machine learning model to accurately forecast inventory demand based on historical sales data.

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.

Data Science Project-All State Insurance Claims Severity Prediction
Data science project in R to develop automated methods for predicting the cost and severity of insurance claims.

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.