Project 1 Solution

$35.00 $30.80

Description

Implement k nearest neighbors (kNN) from scratch in Python. You may use any of the standard packages in the Anaconda distribution (e.g., numpy). Your kNN should use the p-norms to measure distance.

 

The public interface consists of three methods.

 

  1. The constructor. This should take as optional arguments

 

k, the number of neighbors to use, with the default value 5, and

 

p, specifying which p-norm to use. The value p = 1 should be an acceptable value.

 

  1. The fit() method. This builds the classi er from the training data. The training data are numpy arrays. The features are organized with one instance per row.

 

  1. The predict() method. This makes predictions. The input is a numpy array of features, one instance per row. This method should return a numpy array containing the predicted class labels.

 

You are free to implement any internal methods that you wish.

 

c l a s s kNN :                          
def               i n i t         ( s e l f , k=5,   p =2):    
  ’ ’ ’                          
  k :  t h e  number o f  n e i g h b o r s used  i n c l a s s i f i c a t i o n
  p :  s p e c i f i e s   t h e  p norm t o u s e  
  ’ ’ ’                          
  pass                          
def f i t ( s e l f ,  X   t r a i n , y   t r a i n ) :  
  ’ ’ ’                          
  X     t r a i n :  numpy a r r a y     o f f e a t u r e s , one  i n s t a n c e  p e r  row
  y   t r a i n : numpy a r r a y     o f l a b e l s  
         
  ’ ’ ’                          
  pass                          
def p r e d i c t ( s e l f , X   t e s t ) :      

 

’ ’ ’

 

X:  numpy  a r r a y o f f e a t u r e s , one  i n s t a n c e p e r  row

 

’ ’ ’

 

pass

 

 

 

 

 

1