Tune a pipeline without touching the final test.
Compare neighbor counts inside cross-validation, then evaluate the selected procedure once.
Why this workflow exists.
Tuning is part of learning from data. If several neighbor counts are compared against the final test and the best is reported, the test has influenced model choice. This recipe reserves a final test set first, searches candidate k values only within training data, and reports the selected pipeline's test score once.
The scaler sits inside the searched pipeline. In every cross-validation fold it learns scale from the fold's training rows, then applies that scale to validation rows. That keeps the full candidate procedure honest, rather than fitting a scaler once on all development rows before fold creation.
Code context. Python 3 with scikit-learn installed. The Wine dataset is bundled with the library.
The whole example.
from sklearn.datasets import load_wine
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=9
)
pipeline = make_pipeline(StandardScaler(), KNeighborsClassifier())
search = GridSearchCV(
pipeline,
param_grid={"kneighborsclassifier__n_neighbors": [3, 5, 9]},
cv=5,
)
search.fit(X_train, y_train)
print("chosen settings:", search.best_params_)
print("validation mean:", search.best_score_)
print("final test accuracy:", search.score(X_test, y_test))What each stage does.
load_wine supplies a feature table and category labels. The first split puts one quarter of rows aside. GridSearchCV receives a pipeline and three neighbor-count options. The double underscore in the parameter name identifies the n_neighbors setting inside the named KNeighborsClassifier step. It fits each candidate through five validation folds on X_train and y_train.
best_params_ and best_score_ describe the search within development data. GridSearchCV refits the selected pipeline on the full training portion by default. search.score then applies that finished pipeline to untouched X_test and y_test. That final number is the evaluation of the selected procedure, not a number used to choose a different k in this script.
What the output means.
The output names one selected neighbor count, its cross-validation mean, and one held-out test accuracy. A different split or candidate set could choose another count.
Where the example stops.
If the final test result inspires further tuning, it is no longer a fully independent final result. A new holdout or external evaluation may be needed for a revised model.