Prediction Goes Wrong in this

The program is wroking but in my csv file prediction is 1.0 everywhere and so my accuracy is 34%.Can you help me by telling whats wrong in this code.I am giving the link to the CB ide https://ide.codingblocks.com/s/240898

hey @Sid10 ,
your all predictions were coming 1.0 because you are not actually looping every point in your KNN algorithm , you have placed return statement inside your for loop ( check for loop at line no. 21 and return statement at line no. 32 ) .
So just return the value outside and for loop it will work fine .

And comment line no. 26 , as in for loop at 2 iteration it will give error as numpy arrays don’t support append function.
You can have a reference at this code for the above changes: https://ide.codingblocks.com/s/241038

I hope this would resolve your doubt .
Happy learning :slight_smile:.

Hi . I got correct result but can you please tell me again why was that return statement causing an error?

Also what exactly went wrong in vals.append line ? in your code also it was present.Sorry :neutral_face:but im really confused

hey @Sid10 , to perform KNN perfectly you need to iterate over all the points in the dataset , calculate distances and hence find the nearest cluster to which it belongs. But in your code you were checking only the first point due to return statement and the first point belongs to class 1 . ( see below code to understand it )
line no. 23

vals.append( (d,y[i]) ) # here i =0 so you are always getting y[0] , which is 1.

Hence you were achieving all predictions as 1.0

numpy arrays doesn’t have any attribute append as list does. So , we just don’t have to convert our list to a numpy array , else if convert it ,we will get an error stating that numpy arrays doesn’t have any attribute append.

I hope you might have understand it now and your doubt has been resolved.
Enjoy coding :slight_smile:.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.