The Wayback Machine - https://web.archive.org/web/20241007065108/https://www.geeksforgeeks.org/svm-hyperparameter-tuning-using-gridsearchcv-ml/
Open In App

SVM Hyperparameter Tuning using GridSearchCV | ML

Last Updated : 11 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Machine Learning model is defined as a mathematical model with a number of parameters that need to be learned from the data. However, there are some parameters, known as Hyperparameters and those cannot be directly learned. They are commonly chosen by humans based on some intuition or hit and trial before the actual training begins. These parameters exhibit their importance by improving the performance of the model such as its complexity or its learning rate. Models can have many hyper-parameters and finding the best combination of parameters can be treated as a search problem.
SVM also has some hyper-parameters (like what C or gamma values to use) and finding optimal hyper-parameter is a very hard task to solve. But it can be found by just trying all combinations and see what parameters work best. The main idea behind it is to create a grid of hyper-parameters and just try all of their combinations (hence, this method is called Gridsearch, But don’t worry! we don’t have to do it manually because Scikit-learn has this functionality built-in with GridSearchCV.
GridSearchCV takes a dictionary that describes the parameters that could be tried on a model to train it. The grid of parameters is defined as a dictionary, where the keys are the parameters and the values are the settings to be tested.
This article demonstrates how to use the GridSearchCV searching method to find optimal hyper-parameters and hence improve the accuracy/prediction results 
 

Import necessary libraries and get the Data:

We’ll use the built-in breast cancer dataset from Scikit Learn. We can get with the load function:

Python3




import pandas as pd
import numpy as np
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.datasets import load_breast_cancer
from sklearn.svm import SVC
  
cancer = load_breast_cancer()
  
# The data set is presented in a dictionary form:
print(cancer.keys())


dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names', 'filename'])

Now we will extract all features into the new data frame and our target features into separate data frames. 

Python3




df_feat = pd.DataFrame(cancer['data'],
                       columns = cancer['feature_names'])
  
# cancer column is our target
df_target = pd.DataFrame(cancer['target'], 
                     columns =['Cancer'])
  
print("Feature Variables: ")
print(df_feat.info())




Python3




print("Dataframe looks like : ")
print(df_feat.head())


Train Test Split

Now we will split our data into train and test set with a 70: 30 ratio 

Python3




from sklearn.model_selection import train_test_split
  
X_train, X_test, y_train, y_test = train_test_split(
                        df_feat, np.ravel(df_target),
                test_size = 0.30, random_state = 101)


Train the Support Vector Classifier without Hyper-parameter Tuning –

First, we will train our model by calling the standard SVC() function without doing Hyperparameter Tuning and see its classification and confusion matrix. 

Python3




# train the model on train set
model = SVC()
model.fit(X_train, y_train)
  
# print prediction results
predictions = model.predict(X_test)
print(classification_report(y_test, predictions))



We got 61 % accuracy but did you notice something strange? 
Notice that recall and precision for class 0 are always 0. It means that the classifier is always classifying everything into a single class i.e class 1! This means our model needs to have its parameters tuned.
Here is when the usefulness of GridSearch comes into the picture. We can search for parameters using GridSearch!
 

Use GridsearchCV

One of the great things about GridSearchCV is that it is a meta-estimator. It takes an estimator like SVC and creates a new estimator, that behaves exactly the same – in this case, like a classifier. You should add refit=True and choose verbose to whatever number you want, the higher the number, the more verbose (verbose just means the text output describing the process).

Python3




from sklearn.model_selection import GridSearchCV
  
# defining parameter range
param_grid = {'C': [0.1, 1, 10, 100, 1000], 
              'gamma': [1, 0.1, 0.01, 0.001, 0.0001],
              'kernel': ['rbf']} 
  
grid = GridSearchCV(SVC(), param_grid, refit = True, verbose = 3)
  
# fitting the model for grid search
grid.fit(X_train, y_train)


What fit does is a bit more involved than usual. First, it runs the same loop with cross-validation, to find the best parameter combination. Once it has the best combination, it runs fit again on all data passed to fit (without cross-validation), to build a single new model using the best parameter setting.
You can inspect the best parameters found by GridSearchCV in the best_params_ attribute, and the best estimator in the best_estimator_ attribute: 

Python3




# print best parameter after tuning
print(grid.best_params_)
  
# print how our model looks after hyper-parameter tuning
print(grid.best_estimator_)



Then you can re-run predictions and see a classification report on this grid object just like you would with a normal model.

Python3




grid_predictions = grid.predict(X_test)
  
# print classification report
print(classification_report(y_test, grid_predictions))



We have got almost 95 % prediction result.



Similar Reads

Hyperparameter tuning using GridSearchCV and KerasClassifier
Hyperparameter tuning is done to increase the efficiency of a model by tuning the parameters of the neural network. Some scikit-learn APIs like GridSearchCV and RandomizedSearchCV are used to perform hyper parameter tuning. In this article, you'll learn how to use GridSearchCV to tune Keras Neural Networks hyper parameters. Approach: We will wrap K
2 min read
Hyperparameter tuning SVM parameters using Genetic Algorithm
The performance support Vector Machines (SVMs) are heavily dependent on hyperparameters such as the regularization parameter (C) and the kernel parameters (gamma for RBF kernel). Genetic Algorithms (GAs) leverage evolutionary principles to search for optimal hyperparameter values. This article explores the use of Genetic Algorithms for tuning SVM p
9 min read
Random Forest Hyperparameter Tuning in Python
In this article, we shall implement Random Forest Hyperparameter Tuning in Python using Sci-kit Library. Sci-kit aka Sklearn is a Machine Learning library that supports many Machine Learning Algorithms, Pre-processing Techniques, Performance Evaluation metrics, and many other algorithms. Ensemble Techniques are considered to give a good accuracy sc
5 min read
Cross-validation and Hyperparameter tuning of LightGBM Model
In a variety of industries, including finance, healthcare, and marketing, machine learning models have become essential for resolving challenging real-world issues. Gradient boosting techniques have become incredibly popular among the myriad of machine learning algorithms due to their remarkable prediction performance. Due to its speed and effectiv
14 min read
CatBoost Cross-Validation and Hyperparameter Tuning
CatBoost is a powerful gradient-boosting algorithm of machine learning that is very popular for its effective capability to handle categorial features of both classification and regression tasks. To maximize the potential of CatBoost, it's essential to fine-tune its hyperparameters which can be done by Cross-validation. Cross-validation is a crucia
11 min read
Hyperparameter tuning
A Machine Learning model is defined as a mathematical model with several parameters that need to be learned from the data. By training a model with existing data, we can fit the model parameters. However, there is another kind of parameter, known as Hyperparameters, that cannot be directly learned from the regular training process. They are usually
11 min read
How to tune a Decision Tree in Hyperparameter tuning
Decision trees are powerful models extensively used in machine learning for classification and regression tasks. The structure of decision trees resembles the flowchart of decisions helps us to interpret and explain easily. However, the performance of decision trees highly relies on the hyperparameters, selecting the optimal hyperparameter can sign
14 min read
Hyperparameter Tuning in Linear Regression
Linear regression is one of the simplest and most widely used algorithms in machine learning. Despite its simplicity, it can be quite powerful, especially when combined with proper hyperparameter tuning. Hyperparameter tuning is the process of tuning a machine learning model's parameters to achieve optimal results. This article will delve into the
7 min read
HyperParameter Tuning: Fixing Overfitting in Neural Networks
Overfitting is a pervasive problem in neural networks, where the model becomes too specialized to the training data and fails to generalize well to new, unseen data. This issue can be addressed through hyperparameter tuning, which involves adjusting various parameters to optimize the performance of the model. In this article, we will delve into the
6 min read
Hyperparameter tuning with Ray Tune in PyTorch
Hyperparameter tuning is a crucial step in the machine learning pipeline that can significantly impact the performance of a model. Choosing the right set of hyperparameters can be the difference between an average model and a highly accurate one. Ray Tune is an industry-standard tool for distributed hyperparameter tuning that integrates seamlessly
8 min read
Hyperparameter Tuning with R
In R Language several techniques and packages can be used to optimize these hyperparameters, leading to better, more reliable models. in this article, we will discuss all the techniques and packages for Hyperparameter Tuning with R. What are Hyperparameters?Hyperparameters are the settings that control how a machine-learning model learns from data.
5 min read
Hyperparameter tuning with Optuna in PyTorch
Hyperparameter tuning is a critical step in the machine learning pipeline, often determining the success of a model. Optuna is a powerful and flexible framework for hyperparameter optimization, designed to automate the search for optimal hyperparameters. When combined with PyTorch, a popular deep learning library, Optuna can significantly enhance m
5 min read
Implementing SVM and Kernel SVM with Python's Scikit-Learn
In this article we will implement a classification model using Scikit learn implementation for SVM model in Python. Then we will try to understand what is a kernel and how it can helps us to achieve better performance by learning non-linear boundaries in the dataset. What is a SVM algorithm? Support vector machines (SVMs) are a type of supervised l
6 min read
DaskGridSearchCV - A competitor for GridSearchCV
The buzzwords in the field of Data Science such as Machine Learning, Artificial Intelligence and Deep Learning are appearing at the maximum number of places on the Internet in recent time. Everyone wants to try out different models of Machine Learning and Deep Learning and achieve the best results possible. There are some computational limits for s
7 min read
Demonstration of multi-metric evaluation on cross_val_score and GridSearchCV in Scikit Learn
In scikit learn, we can demonstrate multi-metric evaluation with the help of two functions cross_val_score and GridSearchCV. They help you check the performance of the model based on multiple metrics with a single click rather than writing repetitive code. In this article, we will first discuss the implementation of cross_val_score and then GridSea
4 min read
Performing Feature Selection with gridsearchcv in Sklearn
Feature selection is a crucial step in machine learning, as it helps to identify the most relevant features in a dataset that contribute to the model's performance. One effective way to perform feature selection is by combining it with hyperparameter tuning using GridSearchCV from scikit-learn. In this article, we will delve into the details of how
4 min read
Why Does Not GridSearchCV Give Best Score-R?
GridSearchCV is a popular tool in machine learning, especially when tuning hyperparameters. Although it is primarily associated with Python's sci-kit-learn, a similar concept is used in R through various packages like caret and mlr. However, there are times when the grid search does not yield the best possible score, which can be puzzling. This art
5 min read
Comparing Randomized Search and Grid Search for Hyperparameter Estimation in Scikit Learn
Hyperparameters are the parameters that determine the behavior and performance of a machine-learning model. These parameters are not learned during training but are instead set prior to training. The process of finding the optimal values for these hyperparameters is known as hyperparameter optimization, and it is an important step in the developmen
8 min read
Hyperparameter Optimization Based on Bayesian Optimization
In this article we explore what is hyperparameter optimization and how can we use Bayesian Optimization to tune hyperparameters in various machine learning models to obtain better prediction accuracy. Before we dive into the how's of implementing Bayesian Optimization, let us learn what is meant by hyperparameters and hyperparameter optimization. H
7 min read
Tuning Machine Learning Models using Caret package in R
Machine Learning is an important part of Artificial Intelligence for data analysis. It is widely used in many sectors such as healthcare, E-commerce, Finance, Recommendations, etc. It plays an important role in understanding the trends and patterns in our data to predict useful information that can be used for better decision-making. There are thre
15+ min read
Transfer learning & fine-tuning using Keras
Transfer learning is a powerful technique used in deep learning tasks. Here, a model developed for a particular task is reused as a starting point for a model on the second task. Thus, transfer learning uses the knowledge gained from a pre-trained model and allows faster convergence with better performance, especially when the data is limited. On t
7 min read
ML | Using SVM to perform classification on a non-linear dataset
Prerequisite: Support Vector Machines Definition of a hyperplane and SVM classifier: For a linearly separable dataset having n features (thereby needing n dimensions for representation), a hyperplane is basically an (n - 1) dimensional subspace used for separating the dataset into two sets, each set containing data points belonging to a different c
4 min read
How to Make Better Models in Python using SVM Classifier and RBF Kernel
As machine learning models continue to become more popular and widespread, it is important for data scientists and developers to understand how to build the best models possible. One powerful tool that can be used to improve the accuracy and performance of machine learning models is the support vector machine (SVM) classifier, which is a type of li
5 min read
Using a Hard Margin vs Soft Margin in SVM
In this article, we delve into the differences between using a hard margin and a soft margin in SVM and explore the scenarios where each approach is most suitable. Margin in Support Vector Machines (SVMs)Support Vector Machines (SVMs) aim to find a decision boundary (hyperplane) that maximally separates data points belonging to different classes. I
10 min read
Visualizing Support Vector Machines (SVM) using Python
Support Vector Machines (SVMs) are powerful supervised learning models used for classification and regression tasks. A key factor behind their popularity is their ability to handle both linear and non-linear data effectively. In this article, we will explore visualizing SVMs using Python and popular libraries like scikit-learn and Matplotlib. Suppo
6 min read
Image classification using Support Vector Machine (SVM) in Python
Support Vector Machines (SVMs) are a type of supervised machine learning algorithm that can be used for classification and regression tasks. In this article, we will focus on using SVMs for image classification. When a computer processes an image, it perceives it as a two-dimensional array of pixels. The size of the array corresponds to the resolut
9 min read
How to fix issue "SVM using scikit learn runs endlessly and never completes execution"
Support Vector Machines (SVM) are widely used in machine learning for classification and regression tasks due to their effectiveness and robustness. However, you might encounter an issue where the SVM algorithm runs endlessly and never completes execution. This article provides a comprehensive guide to diagnosing and resolve this issue by breaking
3 min read
Multi-class classification using Support Vector Machines (SVM)
Support Vector Machines (SVM) are widely recognized for their effectiveness in binary classification tasks. However, real-world problems often require distinguishing between more than two classes. This is where multi-class classification comes into play. While SVMs are inherently binary classifiers, they can be extended to handle multi-class classi
6 min read
Sklearn | Model Hyper-parameters Tuning
Hyperparameter tuning is the process of finding the optimal values for the hyperparameters of a machine-learning model. Hyperparameters are parameters that control the behaviour of the model but are not learned during training. Hyperparameter tuning is an important step in developing machine learning models because it can significantly improve the
12 min read
Universal Language Model Fine-tuning (ULMFit) in NLP
In this article, We will understand the Universal Language Model Fine-tuning (ULMFit) and its applications in the real-world scenario. This article will give a brief idea about ULMFit working and the concept behind it. What is ULMFit?ULMFit, short for Universal Language Model Fine-tuning, is a revolutionary approach in natural language processing (
9 min read