+91 81900 98289

K-nearest neighbors

This K-nearest neighbors lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

K-nearest neighbors predicts a new point from the labels of the closest known points.

k is how many neighbours you ask. An even k can tie, so an odd k is a common choice.

Example 1: Start here

Scale the columns first, or a column with large numbers dominates the distance.

points = [(1, "A"), (2, "A"), (8, "B")] # a list; the values stay in this order query = 3 # a whole number nearest = sorted(points, key=lambda item: abs(item[0] - query))[:2] # a new list, sorted print(nearest)

Example 2: Add two rows

K-nearest neighbors applies one operation to every number. zip pairs the rows, and the list keeps each sum.

left = [1, 2, 31] # a list; the values stay in this order right = [10, 20, 30] # a list; the values stay in this order print([a + b for a, b in zip(left, right)]) # pair the lists, then combine each pair

Example 3: Average a column

The average is the total divided by how many numbers you have. That is the same summary a statistics page starts with.

scores = [70, 31, 90] # a list; the values stay in this order print(sum(scores) / len(scores)) # len counts the items

Example 4: Keep values above a line

A cutoff drops the low values. Change 80 and run the example again to see who remains.

scores = [70, 31, 90] # a list; the values stay in this order print([score for score in scores if score >= 80]) # keep the items that pass the test
Scale the columns first, or a column with large numbers dominates the distance.
Call Now 81900 98289