Question: Assignment 1 : K - nearest neighbors classifier ( KNN ) Mandatory. You are required to submit Python code with extension . py
Assignment : Knearest neighbors classifier KNN
Mandatory. You are required to submit Python code with extension py that includes an implementation of a KNN classifier and a test on it You can use the attached template knnpy including a minimum test and fill the unimplemented parts there.
The submitted code must include comments that explain what the code does for every functional block you don't have to write comments linebyline
Hint. It may be useful to know that a vector X of numpy.ndarray can be sorted according to values in a vector d of numpy. ndarray by: X Xdargsort
where dargsort returns a vector n such that ni is an index at which the value di should be in sorting d; see the documentation of numpy. argsort for detail. You may use this tip for sorting K training data points X according to the distances d from them to a given input.
This is the template code that I want you to fill out and the goal of it is to get an accuracy of over
class KNearestNeighborsClassifier:
# K: the number of training data points joining the voting
def initself K:
self.K K
# fit: train this model on training inputs X and outputs Y
# X: training inputs npndarray
# shape: # of data points, # of features
# Y: training outputs npndarray
# shape: # of data points
def fitself X Y:
# TODO: IMPLEMENT ME
pass
# predict: classify given data points
# X: inputs to the classifier npndarray
# shape: # of data points, # of features
def predictself X:
# TODO: IMPLEMENT ME
# Hint: Euclid distances between the training inputs X and
# prediction inputs X with shape # of data points, # of features are
# calculuated by numpysqrtX Xsumaxis
pass
# check this is a main file
if namemain:
import numpy as np
from sklearn.datasets import loadiris
from sklearn.modelselection import traintestsplit
irisdataset loadiris
Xtrain, Xtest, Ytrain, Ytest traintestsplitirisdataset.data,
irisdataset.target,
randomstate
knn KNearestNeighborsClassifier
knnfitXtrain, Ytrain
Xtestpredict knnpredictXtest
accuracy npsumYtest Xtestpredict Ytest.shape
printacc: accuracy
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
