0% found this document useful (0 votes)
22 views7 pages

Hyperparameter Tuning in Python

Python tunning

Uploaded by

dharam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views7 pages

Hyperparameter Tuning in Python

Python tunning

Uploaded by

dharam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

HYPERPARAMETER TUNING

The process of finding the best set of hyperparameters for


a machine learning model
TYPES: Random Search, Grid Search, Genetic Algorithms,
Bayesian Optimization, etc. But we are going to consider
the manual search and the GridSearchCV techniques.

Hyperparameter Tuning for one model


# Import necessary libraries
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split, GridSearchCV,
RandomizedSearchCV
from [Link] import SVC
from [Link] import accuracy_score
import warnings
# Ignore all warnings
[Link]("ignore")

# Load the Iris dataset


iris = datasets.load_iris()

# Create a DataFrame using pandas


iris_df = [Link](data=[Link], columns=iris.feature_names)

# Add the target column to the DataFrame


iris_df['target'] = [Link]

# Display the first few rows of the dataset


print("First few rows of the Iris dataset:")
print(iris_df.head())

First few rows of the Iris dataset:


sepal length (cm) sepal width (cm) petal length (cm) petal width
(cm) \
0 5.1 3.5 1.4
0.2
1 4.9 3.0 1.4
0.2
2 4.7 3.2 1.3
0.2
3 4.6 3.1 1.5
0.2
4 5.0 3.6 1.4
0.2

target
0 0
1 0
2 0
3 0
4 0

# specify the features and the target


X = [Link]
y = [Link]

# Split the data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.6, random_state=42)

Manual Search
# Choose the model (SVM in this case) with specific hyperparameters
model = SVC(C=100, kernel='rbf', gamma=10)

# Fit your model


[Link](X_train, y_train)

SVC(C=100, gamma=10)

y_predict = [Link](X_test)
y_predict

array([1, 2, 2, 1, 1, 0, 1, 2, 1, 1, 2, 0, 0, 0, 0, 1, 2, 1, 1, 2, 0,
2,
0, 2, 2, 2, 2, 2, 0, 0, 2, 2, 1, 0, 0, 2, 1, 0, 0, 2, 2, 1, 1,
0,
0, 1, 1, 2, 1, 2, 1, 2, 1, 0, 2, 1, 0, 0, 2, 1, 2, 2, 0, 0, 1,
0,
1, 2, 0, 1, 2, 2, 2, 2, 1, 1, 2, 1, 0, 1, 2, 0, 0, 1, 1, 0, 2,
0,
0, 2])

accuracy = accuracy_score(y_test,y_predict)
accuracy
0.9

GridSearchCV
# Define the hyperparameter grid for GridSearchCV
param_grid_gridsearch = {
'C': [0.1, 1, 10, 100],
'kernel': ['linear', 'rbf', 'poly'],
'gamma': [0.01, 0.1, 1, 'auto']
}

# Create a new model for GridSearchCV


model_gridsearch = SVC()

# Perform GridSearchCV
grid_search = GridSearchCV(model_gridsearch,
param_grid=param_grid_gridsearch, scoring='accuracy', cv=5)
grid_search.fit(X_train, y_train)

GridSearchCV(cv=5, estimator=SVC(),
param_grid={'C': [0.1, 1, 10, 100],
'gamma': [0.01, 0.1, 1, 'auto'],
'kernel': ['linear', 'rbf', 'poly']},
scoring='accuracy')

# Get the best hyperparameters from GridSearchCV


best_params_grid = grid_search.best_params_

# Print the optimal hyperparameters


print("Optimal Hyperparameters from GridSearchCV:")
print(best_params_grid)

Optimal Hyperparameters from GridSearchCV:


{'C': 10, 'gamma': 0.01, 'kernel': 'linear'}

# Train models with the best hyperparameters


best_model_grid = grid_search.best_estimator_

# Evaluate models on the test set


y_pred_grid = best_model_grid.predict(X_test)

# Check the accuracy


accuracy_grid = accuracy_score(y_test, y_pred_grid)
accuracy_grid

0.9777777777777777
Hyperparameter Tuning for Multiple Models

Manual Search
from [Link] import RandomForestClassifier
from sklearn.linear_model import LogisticRegression

# Define the SVM model


model1 = SVC(C=0.1, kernel='linear', gamma=0.01)

# Fit the model


[Link](X_train, y_train)

SVC(C=0.1, gamma=0.01, kernel='linear')

# Predict the test set


y1_predict = [Link](X_test)
y1_predict

array([1, 0, 2, 1, 1, 0, 1, 2, 1, 1, 2, 0, 0, 0, 0, 1, 2, 1, 1, 2, 0,
2,
0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 1, 0, 0, 2, 1, 0, 0, 0, 2, 1, 1,
0,
0, 1, 2, 2, 1, 2, 1, 2, 1, 0, 2, 1, 0, 0, 0, 1, 2, 0, 0, 0, 1,
0,
1, 2, 0, 1, 2, 0, 1, 2, 1, 1, 2, 1, 0, 1, 2, 0, 0, 1, 2, 0, 2,
0,
0, 1])

# Check for the accuracy


accuracy1 = accuracy_score(y_test, y1_predict)
accuracy1

0.9777777777777777

# Define the RF model


model2 = RandomForestClassifier(n_estimators=50, max_depth=10,
min_samples_split=2)

# Fit the model


[Link](X_train, y_train)

RandomForestClassifier(max_depth=10, n_estimators=50)
# Predict the test set
y2_predict = [Link](X_test)
y2_predict

array([1, 0, 2, 1, 1, 0, 1, 2, 1, 1, 2, 0, 0, 0, 0, 1, 2, 1, 1, 2, 0,
2,
0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 1, 0, 0, 2, 1, 0, 0, 0, 2, 1, 1,
0,
0, 1, 1, 2, 1, 2, 1, 2, 1, 0, 2, 1, 0, 0, 0, 1, 2, 0, 0, 0, 1,
0,
1, 2, 0, 1, 2, 0, 2, 2, 1, 1, 2, 1, 0, 1, 2, 0, 0, 1, 2, 0, 2,
0,
0, 2])

# Check for the accuracy


accuracy2 = accuracy_score(y_test, y2_predict)
accuracy2

0.9666666666666667

# Define the LR model


model3 = LogisticRegression(C=0.1, penalty='l1', solver='liblinear')

# Fit the model


[Link](X_train, y_train)

LogisticRegression(C=0.1, penalty='l1', solver='liblinear')

# Predict the testset


y3_predict = [Link](X_test)
y3_predict

array([2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, 2, 2, 2, 2, 0,
2,
0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 2, 2, 2,
0,
0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 0, 0, 2, 2, 0, 0, 0, 2,
0,
2, 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 0, 2, 2, 0, 2,
0,
0, 2])

# Check for the accuracy


accuracy3 = accuracy_score(y_test, y3_predict)
accuracy3

0.6777777777777778
Using GridSearchCV
# Define models
models = {
'SVM': SVC(),
'Random Forest': RandomForestClassifier(),
'Logistic Regression': LogisticRegression()
}

# Define hyperparameter grids for each model


param_grid = {
'SVM': {'C': [0.1, 1, 10, 100], 'kernel': ['linear', 'rbf',
'poly'], 'gamma': [0.01, 0.1, 1, 'auto']},
'Random Forest': {'n_estimators': [10, 50, 100, 200], 'max_depth':
[None, 10, 20, 30], 'min_samples_split': [2, 5, 10]},
'Logistic Regression': {'C': [0.1, 1, 10, 100], 'penalty': ['l1',
'l2'], 'solver': ['liblinear']}
}

import warnings
# Ignore all warnings
[Link]("ignore")

# Perform GridSearchCV for each model


best_models = {}

for name, model in [Link]():


grid_search = GridSearchCV(model, param_grid=param_grid[name],
scoring='accuracy', cv=5)
grid_search.fit(X_train, y_train)
best_models[name] = grid_search.best_estimator_

# Print optimal hyperparameters for each model


print(f"{name} - Optimal Hyperparameters:
{grid_search.best_params_}")

SVM - Optimal Hyperparameters: {'C': 10, 'gamma': 0.01, 'kernel':


'linear'}
Random Forest - Optimal Hyperparameters: {'max_depth': None,
'min_samples_split': 10, 'n_estimators': 50}
Logistic Regression - Optimal Hyperparameters: {'C': 10, 'penalty':
'l2', 'solver': 'liblinear'}

# Evaluate best models on the test set


for name, model in best_models.items():
y_pred = [Link](X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"{name} - Test Accuracy: {accuracy}")
SVM - Test Accuracy: 0.9777777777777777
Random Forest - Test Accuracy: 0.9666666666666667
Logistic Regression - Test Accuracy: 0.9555555555555556

Thank You

Name: Clement Asare

Email: clementasare081@[Link]

ORCID: 0009-0000-2684-7611

YouTube: [Link]

Common questions

Powered by AI

GridSearchCV improves the accuracy of a machine learning model compared to manual search by systematically exploring multiple combinations of hyperparameters and selecting the best performing set based on cross-validation scores. For instance, using GridSearchCV on the SVM model resulted in optimal hyperparameters ('C': 10, 'gamma': 0.01, 'kernel': 'linear'), which led to an accuracy of 0.9778, compared to the 0.9 accuracy when using manually set hyperparameters ('C': 100, 'kernel': 'rbf', 'gamma': 10). This method optimizes model parameters more effectively than manual search, resulting in improved performance .

The identified optimal hyperparameters for the SVM model using GridSearchCV were 'C': 10, 'gamma': 0.01, and 'kernel': 'linear'. These settings resulted in a higher test accuracy of 0.9778, compared to other tested configurations. The impact on model performance is significant, as these hyperparameters allow the SVM to better generalize from the training data, reducing both overfitting and underfitting .

When choosing hyperparameters for the SVM model using manual search, considerations should include understanding the impact of 'C' and 'gamma' on the model. 'C' controls the trade-off between maximizing the margin and minimizing classification error, while 'gamma' defines the influence of individual training examples. Choosing a higher 'C' might result in overfitting if the dataset contains noise, whereas a low 'C' value might result in underfitting. For 'gamma', a low value means a wider window of influence for support vectors, potentially leading to underfitting. The manual approach requires a solid understanding of these hyperparameters' effects and extensive trial and error, guided by observing model performance on separate validation sets .

The document identifies the optimal hyperparameters for RandomForest as 'max_depth': None, 'min_samples_split': 10, and 'n_estimators': 50. These settings enhance model efficiency by allowing the trees to grow without a maximum depth limit, which can provide deeper insights into the data hierarchy. A higher 'min_samples_split' reduces overfitting, ensuring splits occur only when a sufficient sample can provide meaningful partitions. Meanwhile, setting 'n_estimators' to 50 provides a sufficient number of trees to ensure stability and robustness in predictions without being overly computationally expensive .

The primary techniques for hyperparameter tuning introduced in the document are manual search and GridSearchCV. Manual search involves manually selecting hyperparameters based on intuition or trial and error, fitting the model, and evaluating the results. In contrast, GridSearchCV systematically searches through a predefined parameter grid, testing all possible combinations of the specified hyperparameters, while using cross-validation to evaluate model performance. This results in an exhaustive search for optimal hyperparameters but can be computationally expensive and time-intensive compared to manual search .

Hyperparameter tuning for RandomForestClassifier differs from SVM in the specific parameters being optimized. For RandomForest, the parameter grid includes 'n_estimators' (number of trees in the forest), 'max_depth' (maximum depth of the tree), and 'min_samples_split' (minimum number of samples required to split an internal node), reflecting the model’s architecture and complexity. In contrast, SVM's parameter grid focuses on 'C' (penalty parameter of the error term), 'gamma' (kernel coefficient), and 'kernel' type, which are directly related to the decision boundary and margin. The tuning process for each model focuses on different aspects of model complexity and generalization abilities .

For a single model evaluation, GridSearchCV is employed by specifying a hyperparameter grid specific to that model. This is shown with the SVM model, where a grid of 'C', 'kernel', and 'gamma' values is tested to find the optimal settings. For multiple models, GridSearchCV is adapted to separately define hyperparameter grids for each model type, such as SVM, Random Forest, and Logistic Regression. Each model is then evaluated independently using its grid, allowing for model-specific optimizations and comparisons across different model architectures. This comprehensive approach enables the selection of the best performing model and configuration tailored to the dataset .

GridSearchCV has the advantage of exhaustively searching through all specified combinations of hyperparameters, ensuring that the best possible combination is found as long as the grid is sufficiently comprehensive. This thoroughness can result in maximum model optimization. However, it is computationally expensive and may be impractical with large datasets or extensive hyperparameter spaces. Though not discussed in detail, RandomizedSearchCV, by contrast, samples a specified number of random hyperparameter combinations, which can be faster and more computationally feasible, especially when the hyperparameter space is large. The document suggests GridSearchCV for its ability to comprehensively test all combinations, hence optimizing performance as in the SVM example, where optimal parameters were found using a grid approach .

The document indicates that after hyperparameter tuning with GridSearchCV, each model exhibited distinct performance outcomes: SVM achieved the highest test accuracy (0.9778), indicating its effectiveness in capturing underlying data patterns with optimal parameters. Random Forest, with a slightly lower accuracy (0.9667), is robust due to its ensemble approach, yet may be less precise in specific scenarios compared to SVM. Logistic Regression, while achieving a relatively lower accuracy (0.9556), is simpler and computationally less intensive. These performances imply that in contexts requiring highest accuracy and computational resources are available, SVM is preferred. Conversely, Random Forest is ideal for balanced robustness and performance, while Logistic Regression suits cases prioritizing interpretability and simplicity over top-tier accuracy .

Using GridSearchCV, the SVM model achieved a test accuracy of 0.9778, indicating it performed the best among the models tested. The Random Forest model followed with a test accuracy of 0.9667, while Logistic Regression scored the lowest with an accuracy of 0.9556. These metrics suggest that under the conditions and datasets used, the SVM with optimal hyperparameters provided the most accurate predictions, while Random Forest and Logistic Regression also performed well but were slightly less accurate .

You might also like