Supervised learning is where you have input variables (x) and an output variable (Y) and you use an algorithm to learn the mapping function $f$ from the input to the output.
$Y = f(X)$
The goal is to approximate the mapping function so well that when you have new input data (x) that you can predict the output variables (Y) for that data.
It is called supervised learning because the process of an algorithm learning from the training dataset can be thought of as a teacher supervising the learning process. We know the correct answers, the algorithm iteratively makes predictions on the training data and is corrected by the teacher. Learning stops when the algorithm achieves an acceptable level of performance.
The $k$-Nearest Neighbors algorithm ($k$-NN for short) is a very simple technique. The entire training dataset is stored. When a prediction is required, the $k$-most similar records to a new record from the training dataset are then located. From these neighbors, a summarized prediction is made. Once the neighbors are discovered, the summary prediction can be made by returning the most common outcome (for classification problems) or taking the average (for regression problems).
As usual, we need to import necessary python modules:
import numpy as np
import pandas as pa
Two additional modules for data visualisation:
from matplotlib import pyplot as plt
import seaborn as sns
sns.set()
We will illustrate our first supervised learning algorithm using it for breast cancer prediction. For this purpose, we will load a related datset which is included in the standard datasets of sklearn. Later, we will discuss how we can work with our own dataset.
from sklearn.datasets import load_breast_cancer
sklearn datasets are well formated. They come with a set of functions that can be used to get information about them or to visualise them:
breast_cancer = load_breast_cancer()
print(breast_cancer.DESCR)
print(breast_cancer.feature_names)
In the sequel, we will not consider all the dataset. We will explain concepts and $k$-NN algorithm using only two columns (together with predicted class):
Note that function Categorical encodes the two classes as 0 and 1.
X = pa.DataFrame(breast_cancer.data, columns=breast_cancer.feature_names)
X = X[['mean area', 'mean compactness']]
y = pa.Categorical.from_codes(breast_cancer.target, breast_cancer.target_names)
y = pa.get_dummies(y, drop_first=True)
Now, we will split the dataset into two subsets: one for the training and the other for the test. For this, we will import the necessary function:
from sklearn.model_selection import train_test_split
We split the dataset into two subsets. The default ration for the test subset is 25%. However, we can modify it using parameter test_size.
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
Now, we can train our supervised learning model using $k$-NN:
import warnings
warnings.filterwarnings("ignore")
from sklearn.neighbors import KNeighborsClassifier
k = 5
knn = KNeighborsClassifier(n_neighbors=k, metric='euclidean')
knn.fit(X_train, y_train)
Once the model is trained, we can use it to predict the values for the test subset:
y_pred = knn.predict(X_test)
sns.scatterplot(
x='mean area',
y='mean compactness',
hue='benign',
data=X_test.join(y_test, how='outer')
)
plt.scatter(
X_test['mean area'],
X_test['mean compactness'],
c=y_pred,
cmap='coolwarm',
alpha=0.7
)
We can compute the confusion matrix:
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
print(cm)
End then, compute the accuracy of the model:
acc = np.sum(np.diag(cm))/np.sum(cm)
print('{:.2%}'.format(acc))
k-nn is among the simplest supervised learning algorithms. Indeed, the only hyper-parameter to define k. Thus, we can write a very simple algorithm to find the best value for k:
def best_model_search(X_train, X_test, y_train, y_test, n=10, patience=3):
k = 1
best_acc = 0
best_model = None
while k <n and patience >0 :
knn = KNeighborsClassifier(n_neighbors=k, metric='euclidean')
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
acc = np.sum(np.diag(cm))/np.sum(cm)
print('{:.2%}'.format(acc))
if acc > best_acc:
best_acc = acc
best_model = knn
patience = patience -1
k = k+1
return best_model,k, best_acc
knn, k, acc = best_model_search(X_train, X_test, y_train, y_test, patience=10)
print(k, '{:.2%}'.format(acc))