Menu

Hyperparameter Tuning Using GridSearchCV

Hyperparameter Tuning Using GridSearchCV

Instead of selecting the number of neighbors manually, use GridSearchCV to identify the optimal value.

Code

parameters = {
'n_neighbors': range(2, 51)
}
grid = GridSearchCV(
KNeighborsRegressor(),
parameters,
cv=5
)
grid.fit(
X_train,
Y_train
)
print(grid.best_params_)

Explanation

GridSearchCV automatically evaluates multiple values of K using cross-validation and selects the value that produces the best performance.