Aller au contenu

Les K plus proches voisins

Importer KNeighborsClassifier

from sklearn.neighbors import KNeighborsClassifier

Code complet

# coding : utf-8

'''
    Scikit-learn Challenge
    #01 : K Nearest Neighbors
'''

# Packages
import pickle
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

# Get data
X, y = load_iris(return_X_y=True)

# Design model
clf = KNeighborsClassifier(n_neighbors=5)

# Train model
clf.fit(X, y)

# Evaluate model
y_pred = clf.predict(X)
score = accuracy_score(y, y_pred)
print('Accuracy score: ', round(score, 2))

# Inference
output = clf.predict([[1.5, 0.24, 2.6, 0.1]])[0]
print('Predcited class: ', output)

# Save model
with open('output/model.pkl', 'wb') as f:
    pickle.dump(obj=clf, file=f)

Références

  • Référence 1
  • Référence 2

Pour plus d'information merci de visiter .