SKLearner Home | About | Contact | Examples

Scikit-Learn GridSearchCV VotingClassifier

Hyperparameter tuning is a crucial step in optimizing machine learning models for best performance. In this example, we’ll demonstrate how to use scikit-learn’s GridSearchCV to perform hyperparameter tuning for the VotingClassifier, a model that combines multiple machine learning classifiers to improve performance.

Grid search is a method for evaluating different combinations of model hyperparameters to find the best performing configuration. It exhaustively searches through a specified parameter grid, trains and evaluates the model for each combination using cross-validation, and selects the hyperparameters that yield the best performance metric.

The VotingClassifier is an ensemble method that combines the predictions of multiple models to enhance overall performance. It can use different voting strategies such as hard voting (majority voting) or soft voting (weighted average probabilities).

The key hyperparameters for VotingClassifier include the voting strategy (voting), which determines how the predictions of individual models are combined, and the weights assigned to each classifier (weights), used when soft voting. Additionally, the hyperparameters of the individual classifiers used in the ensemble need to be tuned.

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC

# Generate synthetic binary classification dataset
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=42)

# Split into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Define base classifiers
clf1 = LogisticRegression(random_state=42)
clf2 = DecisionTreeClassifier(random_state=42)
clf3 = SVC(probability=True, random_state=42)

# Define VotingClassifier
voting_clf = VotingClassifier(estimators=[('lr', clf1), ('dt', clf2), ('svc', clf3)], voting='soft')

# Define parameter grid
param_grid = {
    'lr__C': [0.1, 1, 10],
    'dt__max_depth': [3, 5, 7],
    'svc__C': [0.1, 1, 10],
    'voting': ['hard', 'soft']
}

# Perform grid search
grid_search = GridSearchCV(estimator=voting_clf,
                           param_grid=param_grid,
                           cv=5,
                           scoring='accuracy')
grid_search.fit(X_train, y_train)

# Report best score and parameters
print(f"Best score: {grid_search.best_score_:.3f}")
print(f"Best parameters: {grid_search.best_params_}")

# Evaluate on test set
best_model = grid_search.best_estimator_
accuracy = best_model.score(X_test, y_test)
print(f"Test set accuracy: {accuracy:.3f}")

Running the example gives an output like:

Best score: 0.930
Best parameters: {'dt__max_depth': 7, 'lr__C': 0.1, 'svc__C': 10, 'voting': 'hard'}
Test set accuracy: 0.920

The steps are as follows:

  1. Generate a synthetic binary classification dataset using scikit-learn’s make_classification function.
  2. Split the dataset into train and test sets using train_test_split.
  3. Define base classifiers: LogisticRegression, DecisionTreeClassifier, and SVC.
  4. Create a VotingClassifier using the base classifiers with soft voting.
  5. Define a parameter grid with different values for C (regularization strength) for logistic regression and SVC, max_depth for the decision tree, and the voting strategy.
  6. Perform grid search using GridSearchCV, specifying the VotingClassifier, parameter grid, 5-fold cross-validation, and accuracy scoring metric.
  7. Report the best cross-validation score and the best set of hyperparameters found by the grid search.
  8. Evaluate the best model on the hold-out test set and report the accuracy.

By using GridSearchCV, we can easily explore different hyperparameter settings and find the combination that maximizes the model’s performance. This automated approach saves time and effort compared to manual hyperparameter tuning and helps ensure we select the best configuration for our VotingClassifier model.



See Also