Really simple and easy K-Nearest Neighbors algorithm from scratch in Python
Algorithm for finding nearest neighbors fastest
K-Nearest Neighbors Algorithm From Scratch In Python
Really well explained
More on reddit.comProblem: Algorithm in Python : k-Nearest Neighbor
First, your code breaks on line 2, since you haven't indented after the
def.You can't call a file
.txtin Windows AFAIK.Why are you calling your file handle k? That makes absolutely no sense.
fwould be a better name (or evenfile_handle). Which is also what your code later uses... Also, you're calling it with a function parameter k, which you're overwriting (and then do nothing with).'s are used to escape characters, which will introduce bugs. Use
r'C:\Users\filename.txt'instead (note the prepended r, short for raw).You're not closing your file handle. You need to do
f.close()once you've done reading the file. Even better is to use this idiom:with open(FILENAME) as f:
lines = f.readlines()This will open file FILENAME and read the lines as a list into a variable named lines, and then close the file.
array(p_lat)
Python doesn't have arrays.
p_latis already a list, simply return that. You could turn it into a tuple (which is like a list but it cannot be changed), but there's little reason to do that.
You're clearly writing the entire code without running it. Don't do that. As a beginner, write one or two lines at a time and print the results, so you know what's happening. KNN isn't super complicated to implement, but the way you're doing it you're only going to confuse yourself.
More on reddit.com