Search code examples
pythonpandasscikit-learnknn

How to Generate Multiple Predictions Output with KNN Model?


I am using predict() function to generate prediction from KNN model and instead of having one prediction, which is [10] in this case, I want to have the most likely classes.

Is it Possible ?

Here is my code:

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score


df = pd.read_excel("Test.xlsx")
X = df.iloc[:,:4]
y = np.array(df['Target']) 

# split into train and test
X_train, 
X_test, 
y_train, 
y_test = train_test_split(X, y, test_size=0.33, random_state=42)

# instantiate learning model (k = 7)
knn = KNeighborsClassifier(n_neighbors=7)

# fitting the model
knn.fit(X_train, y_train)

# predict the response
pred = knn.predict(X_test)

#Predict Output
pred= knn.predict([[2,3,90,600]]) 


**Output:**
**[10]**

Solution

  • You could add something like this:

    print(knn.predict_proba(X_test)

    This will print out something that may look like: [x1. x2. x3. x4.], showing the probabilities or the confidence for each class. This method will print out that format for each item in the testing set.