SKLearner Home | About | Contact | Examples

Scikit-Learn GridSearchCV KNeighborsClassifier

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 KNeighborsClassifier, a popular algorithm for classification tasks.

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.

KNeighborsClassifier is a distance-based algorithm that assigns class labels based on the classes of the nearest neighbors. It is simple and effective for many classification tasks.

The key hyperparameters for KNeighborsClassifier include the number of neighbors (n_neighbors), which determines how many nearest neighbors to use for classification; the weight function (weights), which defines whether all neighbors are weighted equally or by distance; and the distance metric (metric), which specifies how distances between points are calculated.

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.neighbors import KNeighborsClassifier

# 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 parameter grid
param_grid = {
    'n_neighbors': [3, 5, 7],
    'weights': ['uniform', 'distance'],
    'metric': ['euclidean', 'manhattan']
}

# Perform grid search
grid_search = GridSearchCV(estimator=KNeighborsClassifier(),
                           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.941
Best parameters: {'metric': 'euclidean', 'n_neighbors': 7, 'weights': 'distance'}
Test set accuracy: 0.950

The steps are as follows:

  1. Generate a synthetic binary classification dataset using make_classification.
  2. Split the dataset into train and test sets using train_test_split.
  3. Define the parameter grid with different values for n_neighbors, weights, and metric hyperparameters.
  4. Perform grid search using GridSearchCV, specifying the KNeighborsClassifier, parameter grid, 5-fold cross-validation, and accuracy scoring metric.
  5. Report the best cross-validation score and best set of hyperparameters found by grid search.
  6. Evaluate the best model on the hold-out test set and report the accuracy.

By using GridSearchCV, we can efficiently explore different hyperparameter settings for KNeighborsClassifier and identify the optimal configuration, saving time and effort compared to manual tuning and ensuring the best performance for our model.



See Also