In the print dialog, choose "Save as PDF" as the destination.
Machine Learning, Week 5
Classify a new sample by asking its K closest neighbours, then build, score and tune the model with scikit-learn.
StandardScaler and say why distance needs itKNeighborsClassifier, then read a confusion matrix, accuracy, precision and recallWeek 5 of the plan
| Part | What we do | Time |
|---|---|---|
| 1 | The idea, and a worked example by hand | 30 min |
| 2 | Notebook 1: scaling, fitting, evaluating | 25 min |
| 3 | Choosing K with the elbow method | 10 min |
| 4 | Notebook 2 on iris, mistakes, your project | 20 min |
| 5 | Practice with answers, then takeaways | 35 min |
Part 1
Similar inputs have similar labels
| Term | In the iris data |
|---|---|
Features X | sepal length, sepal width, petal length, petal width (cm) |
Label y | species: 0 setosa, 1 versicolor, 2 virginica |
| Training set | the flowers the model stores |
| Query | a new flower whose species we want |
| K | how many neighbours vote, n_neighbors in scikit-learn |
fit needs to do)x is a training row, q is the query, n is the number of featuresBy hand
Nine real iris flowers, two features: petal length and petal width in cm. The new flower is (4.7, 1.7).
| Flower | Species | (length, width) |
|---|---|---|
| F1 | setosa | (1.4, 0.2) |
| F2 | versicolor | (4.7, 1.6) |
| F3 | versicolor | (5.0, 1.7) |
| F4 | versicolor | (5.1, 1.6) |
| F5 | versicolor | (4.9, 1.5) |
| Flower | Species | (length, width) |
|---|---|---|
| F6 | virginica | (4.9, 1.8) |
| F7 | virginica | (4.8, 1.8) |
| F8 | virginica | (5.0, 1.5) |
| F9 | virginica | (5.1, 1.8) |
Difference = flower minus query, for length and for width
| Flower | Differences | Squared distance |
|---|---|---|
| F1 | -3.30, -1.50 | 10.89 + 2.25 = 13.14 |
| F2 | 0, -0.10 | 0 + 0.01 = 0.01 |
| F3 | +0.30, 0 | 0.09 + 0 = 0.09 |
| F4 | +0.40, -0.10 | 0.16 + 0.01 = 0.17 |
| F5 | +0.20, -0.20 | 0.04 + 0.04 = 0.08 |
| Flower | Differences | Squared distance |
|---|---|---|
| F6 | +0.20, +0.10 | 0.04 + 0.01 = 0.05 |
| F7 | +0.10, +0.10 | 0.01 + 0.01 = 0.02 |
| F8 | +0.30, -0.20 | 0.09 + 0.04 = 0.13 |
| F9 | +0.40, +0.10 | 0.16 + 0.01 = 0.17 |
| Rank | Flower | Species | Distance d |
|---|---|---|---|
| 1 | F2 | versicolor | √0.01 = 0.100 |
| 2 | F7 | virginica | √0.02 = 0.141 |
| 3 | F6 | virginica | √0.05 = 0.224 |
| 4 | F5 | versicolor | √0.08 = 0.283 |
| 5 | F3 | versicolor | √0.09 = 0.300 |
Part 2
Scale, split, fit, evaluate
https://colab.research.google.com/github/
tirthajyoti/Machine-Learning-with-Python/blob/
master/Classification/KNN_Classification.ipynbimport pandas as pd
import numpy as np
url = ("https://raw.githubusercontent.com/"
"tirthajyoti/Machine-Learning-with-Python/"
"master/Datasets/Classified%20Data")
df = pd.read_csv(url, index_col=0)
df.info()WTT, PTI, ...)TARGET CLASS, with values 0 and 1StandardScaler rescales every feature to mean 0 and standard deviation 1, so each one gets a fair sayRow 0 of WTT: x = 0.913917, mean 0.949682, standard deviation 0.289490
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(df.drop('TARGET CLASS', axis=1))
scaled_features = scaler.transform(df.drop('TARGET CLASS', axis=1))
df_feat = pd.DataFrame(scaled_features, columns=df.columns[:-1])
df_feat.head()from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
scaled_features, df['TARGET CLASS'], test_size=0.50, random_state=101)
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train, y_train)
pred = knn.predict(X_test)print(confusion_matrix(y_test, pred))
| Predicted 0 | Predicted 1 | |
|---|---|---|
| Actual 0 | 233 | 17 |
| Actual 1 | 24 | 226 |
Part 3
The elbow method
error_rate = []
for i in range(1, 60):
knn = KNeighborsClassifier(n_neighbors=i)
knn.fit(X_train, y_train)
pred_i = knn.predict(X_test)
error_rate.append(np.mean(pred_i != y_test))Error rate on the 500 test rows
| K | Error rate | Wrong rows |
|---|---|---|
| 1 | 0.082 | 41 |
| 2 | 0.094 | 47 |
| 5 | 0.054 | 27 |
| 11 | 0.048 | 24 |
| 24 | 0.046 | 23 |
Part 4
150 samples, three species
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['class'] = iris.target
df['class name'] = iris.target_names[iris['target']]
df.head()
sns.pairplot(df)x_train, x_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=0)
model = KNeighborsClassifier()
model.fit(x_train, y_train)
model.score(x_test, y_test)predicted_class = model.predict([[5.6, 4.4, 1.2, 0.4]])
print(predicted_class)
print(iris.target_names[predicted_class[0]])model.kneighbors lists them: all five are setosa, a 5 to 0 vote
| Neighbour | Species | Distance |
|---|---|---|
| (5.7, 4.4, 1.5, 0.4) | setosa | 0.3162 |
| (5.8, 4, 1.2, 0.2) | setosa | 0.4899 |
| (5.2, 4.1, 1.5, 0.1) | setosa | 0.6557 |
| (5.4, 3.9, 1.7, 0.4) | setosa | 0.7348 |
| (5.7, 3.8, 1.7, 0.3) | setosa | 0.7937 |
confusion_matrix(y_test, model.predict(x_test))
| Pred. setosa | Pred. versicolor | Pred. virginica | |
|---|---|---|---|
| setosa | 11 | 0 | 0 |
| versicolor | 0 | 12 | 1 |
| virginica | 0 | 0 | 6 |
Before you practise
predict: it needs [[...]]"Classified Data" in Colab from a folder that does not have itYour team project
KNeighborsClassifier and predict the test setclassification_reportPart 5
About 30 minutes, answers follow each task
About 10 minutes
Answers
| Rank | Flower | Species | Squared distance |
|---|---|---|---|
| 1 | F9 | virginica | 0.0025 |
| 2 | F3 | versicolor | 0.0125 |
| 3 | F4 | versicolor | 0.0225 |
| 4 | F6 | virginica | 0.0425 |
| 5 | F8 | virginica | 0.0725 |
Answers
About 5 minutes
| Predicted 0 | Predicted 1 | |
|---|---|---|
| Actual 0 | 238 | 12 |
| Actual 1 | 12 | 238 |
About 5 minutes
One feature has the five values 4, 6, 8, 10, 12
About 10 minutes
model.score(x_test, y_test)[[6.0, 2.9, 4.5, 1.5]] and print its species namemodel.kneighbors on it: how did its five neighbours vote?Answers
| Question | Answer |
|---|---|
Species of [6.0, 2.9, 4.5, 1.5] | versicolor |
| The five neighbours | 4 versicolor, 1 virginica |
| Nearest neighbour | (6.1, 3, 4.6, 1.4), distance 0.2000 |
| Score 1.0 at K = | 1, 4 and 6 to 15 |
| Score 0.9667 at K = | 2, 3, 5 |
Mahmoud Abas|K-Nearest Neighbors Classification