In this post, we are gonna make a machine learning program using KNN model. For this, you have to install a IDE to write and compile the code in it. I have used VS Code in the program below, you also need to install python and libraries like pandas, numpy and sklearn in the command prompt. Here we are gonna do vehicle evaluation and you have to get car.data file from the link below:
Data Source : car.data
python file link : car data prediction model
Preview:
# these libraries are used in the program below.
import pandas as pd
import numpy as np
import sklearn
from sklearn import neighbors, metrics
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
# read the data we need for our prediction model
data = pd.read_csv("C:\data\car.data")
#copy all the needed values to x and y
x= data[["buying","maint","safety"]].values
y=data[["class"]]
#converting the strings into unique values
# y data
label_mapping = {
"unacc":0,
"acc":1,
"good":2,
"vgood":3,
}
y["class"]=y["class"].map(label_mapping)
y = np.array(y)
# arrange the X data
Le= LabelEncoder()
for i in range(len(x[0])):
x[:,i]=Le.fit_transform(x[:,i])
#create model
# we have to first split the data into training and testing data using train_test_split function
# here we are using KNN model to predict the y_test data
knn= neighbors.KNeighborsClassifier(n_neighbors=25, weights="uniform")
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
knn.fit(x_train, y_train)
prediction=knn.predict(x_test)
accuracy= metrics.accuracy_score(y_test, prediction)
print(accuracy)
a=137 #enter any value of the y_test data and compare it with the predicted value of KNNN model.
print("actual value : ", y[a])
print("predicted value:", knn.predict(x)[a])
0 Comments