NotFittedError: This KNeighborsClassifier instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator

How to fix this

  from sklearn.datasets import load_iris
  import os
  import math
  from sklearn.neighbors import KNeighborsClassifier
  import numpy as np
  import csv
  import pandas as pd
   from pandas.plotting import scatter_matrix
  import matplotlib.pyplot as plt
  import seaborn as sns
  iris=load_iris()
  print(iris.keys())
  print(iris['target'].shape)
  from sklearn.model_selection import train_test_split 
  X_train,X_test,y_train,y_test=train_test_split(iris['data'],iris['target'],random_state=0)
print(y_train.shape)
print(X_train.shape)
iris_dataframe=pd.DataFrame(X_train,columns=iris.feature_names)
knn=KNeighborsClassifier(n_neighbors=1)
y_pred = knn.predict(X_train) //error:NotFittedError: This KNeighborsClassifier instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.

what is the error? please help me!!!! I don't know how to fix this

1 answer

  • answered 2021-06-10 11:22 Seon

    You'll want to start by training you K-means model (computing clusters on training data): knn.fit(X_train, y_train).

    You can then use it to classify your testing data, using the cluster centers computed during the training phase: y_pred = knn.predict(X_test).