Module 12 · K nearest neighbors · Lesson 49 of 66

Classify by your neighbors

Predict a class from the closest examples, scale the features first, and choose K with the elbow method.

In this lesson · about 25 minutes

  • Explain how K nearest neighbors decides a class
  • Standardize features with StandardScaler
  • Pick a good K by plotting the error rate

K nearest neighbors (KNN) may be the simplest classifier there is. To classify a new point, it finds the K training points closest to it and takes a vote: the most common class among those neighbors wins. Training is just remembering the data.

  • A small K (like 1) follows every quirk of the training data, so it's noisy.
  • A large K smooths things out, but can blur real boundaries between classes.

Because KNN measures distance, every feature must be on the same scale. Otherwise a column measured in thousands drowns out one measured in fractions. StandardScaler rescales every column to an average of 0 and a standard deviation of 1.

Mystery data

A company has sent us a data set with the column names hidden: ten unnamed features and a TARGET CLASS of 0 or 1. KNN doesn't care what the columns mean.

Exercise

Scale the features

Create a StandardScaler called scaler, fit it to every column except TARGET CLASS, and transform those columns into scaled_features. Then make a DataFrame df_feat of the scaled values with the original column names (df.columns[:-1]) and show its head.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('Classified_Data.csv', index_col=0)

Exercise

Start with K = 1

The scaled data is split for you (test_size=0.30, random_state=101). Create a KNeighborsClassifier with n_neighbors=1 called knn, fit it, and save its predictions as pred. Then print the confusion matrix.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('Classified_Data.csv', index_col=0)
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
scaler = StandardScaler()
scaler.fit(df.drop('TARGET CLASS', axis=1))
scaled_features = scaler.transform(df.drop('TARGET CLASS', axis=1))
X_train, X_test, y_train, y_test = train_test_split(scaled_features, df['TARGET CLASS'],
                                                    test_size=0.30, random_state=101)

The elbow method

Which K is best? Try many and measure the error rate, the share of test points the model gets wrong, for each. Plot error against K: the error usually drops, then levels off. Pick a K where it has flattened, the "elbow".

Exercise

Find the elbow

Build a list error_rate: for each K from 1 to 39, fit a KNN model and append the mean of pred_i != y_test. Then plot range(1, 40) against error_rate.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('Classified_Data.csv', index_col=0)
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
scaler = StandardScaler()
scaler.fit(df.drop('TARGET CLASS', axis=1))
scaled_features = scaler.transform(df.drop('TARGET CLASS', axis=1))
X_train, X_test, y_train, y_test = train_test_split(scaled_features, df['TARGET CLASS'],
                                                    test_size=0.30, random_state=101)

Retrain with a better K

The error levels off in the twenties. Compare K = 1 with K = 23.

Exercises solved: 0 of 3

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.