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

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

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.

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.

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.

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.

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.

Predict Credit Default | Give Me Some Credit Kaggle
In this data science project, you will predict borrowers chance of defaulting on credit loans by building a credit score prediction model.

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.

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.

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.