Learn practical skills, build real-world projects, and advance your career
from sklearn.neighbors import KNeighborsClassifier
import sklearn.datasets

newsgroups = sklearn.datasets.fetch_20newsgroups_vectorized()
X, y = newsgroups.data, newsgroups.target

print(X.shape)
print(y.shape)
(11314, 130107) (11314,)
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y)
# Create and fit the model
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)

# Predict on the test features, print the results
pred = knn.predict(X_test)[0]
print("Prediction for test example 0:", pred)
Prediction for test example 0: 0
knn.score(X_test, y_test)
0.5630965005302226