Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

367
Visualizações
KNeighborsClassifier with cross-validation returns perfect accuracy when k=1

I'm training a KNN classifier using scikit-learn's KNeighborsClassifier with cross validation:

k=1
param_space = {'n_neighbors': [k]}
model = KNeighborsClassifier(n_neighbors=k, metric='euclidean')
search = GridSearchCV(model, param_space, cv=cv, verbose=10, n_jobs=8)
search.fit(X_df, y_df)
preds = search.best_estimator_.predict(X_df)

when k=1 and with any cv value (lets say cv=4), I'm getting perfect score

from sklearn.metrics import confusion_matrix
tn, fp, fn, tp = confusion_matrix(y_df, preds).ravel()
f1 = tp / (tp + 0.5 * (fp + fn))
# f1 is perfect 1

It is important to say that I use this method on multiple datasets, and every time k=1 the score is a perfect 1. I tried doing it on random data and still got f1=1.

Is there any known bug with KNeighborsClassifier when k=1? Maybe I'm missing something else? Thanks in advance.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Your predictions are from the best_estimator_, which is a copy of the estimator with the optimal hyperparameters (according to the cross-validation scores) refitted to the entire training set. So the confusion matrix you generate is really a training score, and for 1-neighbors that's trivially perfect (the nearest neighbor of a point is itself).

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda