Skip to content
ImagineWorld

A Tour of Machine Learning Classifiers Using Scikit-Learn

node_idnode-book_machine-learning-with-pytorch-and-scikit-learn_chapter-03-a-tour-of-machine-learning-classifiers-using-scikit-learn
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleA Tour of Machine Learning Classifiers Using Scikit-Learn
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 3 — A Tour of Machine Learning Classifiers Using Scikit-Learn

Section titled “Chapter 3 — A Tour of Machine Learning Classifiers Using Scikit-Learn”

In this chapter, we will take a tour of a selection of popular and powerful machine learning algorithms that are commonly used in academia as well as in industry. While learning about the differences between several supervised learning algorithms for classification, we will also develop an appreciation of their individual strengths and weaknesses. In addition, we will take our first steps with the scikit-learn library, which offers a user-friendly and consistent interface for using those algorithms efficiently and productively.

The topics that will be covered throughout this chapter are as follows:

  • An introduction to robust and popular algorithms for classification, such as logistic regression, support vector machines, decision trees, and k-nearest neighbors
  • Examples and explanations using the scikit-learn machine learning library, which provides a wide variety of machine learning algorithms via a user-friendly Python API
  • Discussions about the strengths and weaknesses of classifiers with linear and nonlinear decision boundaries

Choosing an appropriate classification algorithm for a particular problem task requires practice and experience; each algorithm has its own quirks and is based on certain assumptions. To paraphrase the no free lunch theorem by David H. Wolpert, no single classifier works best across all possible scenarios (The Lack of A Priori Distinctions Between Learning Algorithms, Wolpert, David H, Neural Computation 8.7 (1996): 1341-1390). In practice, it is always recommended that you compare the performance of at least a handful of different learning algorithms to select the best model for the particular problem; these may differ in the number of features or examples, the amount of noise in a dataset, and whether the classes are linearly separable.

Eventually, the performance of a classifier—computational performance as well as predictive power—depends heavily on the underlying data that is available for learning. The five main steps that are involved in training a supervised machine learning algorithm can be summarized as follows:

  1. Selecting features and collecting labeled training examples
  2. Choosing a performance metric
  3. Choosing a learning algorithm and training a model
  4. Evaluating the performance of the model
  5. Changing the settings of the algorithm and tuning the model.

Since the approach of this book is to build machine learning knowledge step by step, we will mainly focus on the main concepts of the different algorithms in this chapter and revisit topics such as feature selection and preprocessing, performance metrics, and hyperparameter tuning for more detailed discussions later in the book.

First steps with scikit-learn – training a perceptron

Section titled “First steps with scikit-learn – training a perceptron”

In Chapter 2, Training Simple Machine Learning Algorithms for Classification, you learned about two related learning algorithms for classification, the perceptron rule and Adaline, which we implemented in Python and NumPy by ourselves. Now we will take a look at the scikit-learn API, which, as mentioned, combines a user-friendly and consistent interface with a highly optimized implementation of several classification algorithms. The scikit-learn library offers not only a large variety of learning algorithms, but also many convenient functions to preprocess data and to fine-tune and evaluate our models. We will discuss this in more detail, together with the underlying concepts, in Chapter 4, Building Good Training Datasets – Data Preprocessing, and Chapter 5, Compressing Data via Dimensionality Reduction.

To get started with the scikit-learn library, we will train a perceptron model similar to the one that we implemented in Chapter 2. For simplicity, we will use the already familiar Iris dataset throughout the following sections. Conveniently, the Iris dataset is already available via scikit-learn, since it is a simple yet popular dataset that is frequently used for testing and experimenting with algorithms. Similar to the previous chapter, we will only use two features from the Iris dataset for visualization purposes.

We will assign the petal length and petal width of the 150 flower examples to the feature matrix, X, and the corresponding class labels of the flower species to the vector array, y:

>>> from sklearn import datasets
>>> import numpy as np
>>> iris = datasets.load_iris()
>>> X = iris.data[:, [2, 3]]
>>> y = iris.target
>>> print('Class labels:', np.unique(y))
Class labels: [0 1 2]

The np.unique(y) function returned the three unique class labels stored in iris.target, and as we can see, the Iris flower class names, Iris-setosa, Iris-versicolor, and Iris-virginica, are already stored as integers (here: 0, 1, 2). Although many scikit-learn functions and class methods also work with class labels in string format, using integer labels is a recommended approach to avoid technical glitches and improve computational performance due to a smaller memory footprint; furthermore, encoding class labels as integers is a common convention among most machine learning libraries.

To evaluate how well a trained model performs on unseen data, we will further split the dataset into separate training and test datasets. In Chapter 6, Learning Best Practices for Model Evaluation and Hyperparameter Tuning, we will discuss the best practices around model evaluation in more detail. Using the train_test_split function from scikit-learn’s model_selection module, we randomly split the X and y arrays into 30 percent test data (45 examples) and 70 percent training data (105 examples):

>>> from sklearn.model_selection import train_test_split
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, test_size=0.3, random_state=1, stratify=y
... )

Note that the train_test_split function already shuffles the training datasets internally before splitting; otherwise, all examples from class 0 and class 1 would have ended up in the training datasets, and the test dataset would consist of 45 examples from class 2. Via the random_state parameter, we provided a fixed random seed (random_state=1) for the internal pseudo-random number generator that is used for shuffling the datasets prior to splitting. Using such a fixed random_state ensures that our results are reproducible.

Lastly, we took advantage of the built-in support for stratification via stratify=y. In this context, stratification means that the train_test_split method returns training and test subsets that have the same proportions of class labels as the input dataset. We can use NumPy’s bincount function, which counts the number of occurrences of each value in an array, to verify that this is indeed the case:

>>> print('Labels counts in y:', np.bincount(y))
Labels counts in y: [50 50 50]
>>> print('Labels counts in y_train:', np.bincount(y_train))
Labels counts in y_train: [35 35 35]
>>> print('Labels counts in y_test:', np.bincount(y_test))
Labels counts in y_test: [15 15 15]

Many machine learning and optimization algorithms also require feature scaling for optimal performance, as we saw in the gradient descent example in Chapter 2. Here, we will standardize the features using the StandardScaler class from scikit-learn’s preprocessing module:

>>> from sklearn.preprocessing import StandardScaler
>>> sc = StandardScaler()
>>> sc.fit(X_train)
>>> X_train_std = sc.transform(X_train)
>>> X_test_std = sc.transform(X_test)

Using the preceding code, we loaded the StandardScaler class from the preprocessing module and initialized a new StandardScaler object that we assigned to the sc variable. Using the fit method, StandardScaler estimated the parameters, μ\mu (sample mean) and σ\sigma (standard deviation), for each feature dimension from the training data. By calling the transform method, we then standardized the training data using those estimated parameters, μ\mu and σ\sigma. Note that we used the same scaling parameters to standardize the test dataset so that both the values in the training and test dataset are comparable with one another.

Having standardized the training data, we can now train a perceptron model. Most algorithms in scikit-learn already support multiclass classification by default via the one-versus-rest (OvR) method, which allows us to feed the three flower classes to the perceptron all at once. The code is as follows:

>>> from sklearn.linear_model import Perceptron
>>> ppn = Perceptron(eta0=0.1, random_state=1)
>>> ppn.fit(X_train_std, y_train)

The scikit-learn interface will remind you of our perceptron implementation in Chapter 2. After loading the Perceptron class from the linear_model module, we initialized a new Perceptron object and trained the model via the fit method. Here, the model parameter, eta0, is equivalent to the learning rate, eta, that we used in our own perceptron implementation.

As you will remember from Chapter 2, finding an appropriate learning rate requires some experimentation. If the learning rate is too large, the algorithm will overshoot the global loss minimum. If the learning rate is too small, the algorithm will require more epochs until convergence, which can make the learning slow—especially for large datasets. Also, we used the random_state parameter to ensure the reproducibility of the initial shuffling of the training dataset after each epoch.

Having trained a model in scikit-learn, we can make predictions via the predict method, just like in our own perceptron implementation in Chapter 2. The code is as follows:

>>> y_pred = ppn.predict(X_test_std)
>>> print('Misclassified examples: %d' % (y_test != y_pred).sum())
Misclassified examples: 1

Executing the code, we can see that the perceptron misclassifies 1 out of the 45 flower examples. Thus, the misclassification error on the test dataset is approximately 0.022, or 2.2 percent (145≈0.022\frac{1}{45}\approx 0.022).

Classification error versus accuracy

Instead of the misclassification error, many machine learning practitioners report the classification accuracy of a model, which is simply calculated as follows:

1–error = 0.978, or 97.8 percent

Whether we use the classification error or accuracy is merely a matter of preference.

Note that scikit-learn also implements a large variety of different performance metrics that are available via the metrics module. For example, we can calculate the classification accuracy of the perceptron on the test dataset as follows:

>>> from sklearn.metrics import accuracy_score
>>> print('Accuracy: %.3f' % accuracy_score(y_test, y_pred))
Accuracy: 0.978

Here, y_test is the true class labels and y_pred is the class labels that we predicted previously. Alternatively, each classifier in scikit-learn has a score method, which computes a classifier’s prediction accuracy by combining the predict call with accuracy_score, as shown here:

>>> print('Accuracy: %.3f' % ppn.score(X_test_std, y_test))
Accuracy: 0.978

Overfitting

Note that we will evaluate the performance of our models based on the test dataset in this chapter. In Chapter 6, you will learn about useful techniques, including graphical analysis, such as learning curves, to detect and prevent overfitting. Overfitting, which we will return to later in this chapter, means that the model captures the patterns in the training data well but fails to generalize well to unseen data.

Finally, we can use our plot_decision_regions function from Chapter 2 to plot the decision regions of our newly trained perceptron model and visualize how well it separates the different flower examples. However, let’s add a small modification to highlight the data instances from the test dataset via small circles:

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
def plot_decision_regions(X, y, classifier, test_idx=None,
resolution=0.02):
# setup marker generator and color map
markers = ('o', 's', '^', 'v', '<')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
# plot the decision surface
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
lab = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
lab = lab.reshape(xx1.shape)
plt.contourf(xx1, xx2, lab, alpha=0.3, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
# plot class examples
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y == cl, 0],
y=X[y == cl, 1],
alpha=0.8,
c=colors[idx],
marker=markers[idx],
label=f'Class {cl}',
edgecolor='black')
# highlight test examples
if test_idx:
# plot all examples
X_test, y_test = X[test_idx, :], y[test_idx]
plt.scatter(X_test[:, 0], X_test[:, 1],
c='none', edgecolor='black', alpha=1.0,
linewidth=1, marker='o',
s=100, label='Test set')

With the slight modification that we made to the plot_decision_regions function, we can now specify the indices of the examples that we want to mark on the resulting plots. The code is as follows:

>>> X_combined_std = np.vstack((X_train_std, X_test_std))
>>> y_combined = np.hstack((y_train, y_test))
>>> plot_decision_regions(X=X_combined_std,
... y=y_combined,
... classifier=ppn,
... test_idx=range(105, 150))
>>> plt.xlabel('Petal length [standardized]')
>>> plt.ylabel('Petal width [standardized]')
>>> plt.legend(loc='upper left')
>>> plt.tight_layout()
>>> plt.show()

As we can see in the resulting plot, the three flower classes can’t be perfectly separated by a linear decision boundary:

Figure 3.1: Decision boundaries of a multi-class perceptron model fitted to the Iris dataset
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

However, remember from our discussion in Chapter 2 that the perceptron algorithm never converges on datasets that aren’t perfectly linearly separable, which is why the use of the perceptron algorithm is typically not recommended in practice. In the following sections, we will look at more powerful linear classifiers that converge to a loss minimum even if the classes are not perfectly linearly separable.

Additional perceptron settings

The Perceptron, as well as other scikit-learn functions and classes, often has additional parameters that we omit for clarity. You can read more about those parameters using the help function in Python (for instance, help(Perceptron)) or by going through the excellent scikit-learn online documentation at http://scikit-learn.org/stable/.

Modeling class probabilities via logistic regression

Section titled “Modeling class probabilities via logistic regression”

Although the perceptron rule offers a nice and easy-going introduction to machine learning algorithms for classification, its biggest disadvantage is that it never converges if the classes are not perfectly linearly separable. The classification task in the previous section would be an example of such a scenario. The reason for this is that the weights are continuously being updated since there is always at least one misclassified training example present in each epoch. Of course, you can change the learning rate and increase the number of epochs, but be warned that the perceptron will never converge on this dataset.

To make better use of our time, we will now take a look at another simple, yet more powerful, algorithm for linear and binary classification problems: logistic regression. Note that, despite its name, logistic regression is a model for classification, not regression.

Logistic regression and conditional probabilities

Section titled “Logistic regression and conditional probabilities”

Logistic regression is a classification model that is very easy to implement and performs very well on linearly separable classes. It is one of the most widely used algorithms for classification in industry. Similar to the perceptron and Adaline, the logistic regression model in this chapter is also a linear model for binary classification.

Logistic regression for multiple classes

Note that logistic regression can be readily generalized to multiclass settings, which is known as multinomial logistic regression, or softmax regression. More detailed coverage of multinomial logistic regression is outside the scope of this book, but the interested reader can find more information in my lecture notes at https://sebastianraschka.com/pdf/lecture-notes/stat453ss21/L08_logistic__slides.pdf or https://www.youtube.com/watch?v=L0FU8NFpx4E.

Another way to use logistic regression in multiclass settings is via the OvR technique, which we discussed previously.

To explain the main mechanics behind logistic regression as a probabilistic model for binary classification, let’s first introduce the odds: the odds in favor of a particular event. The odds can be written as p(1−p)\frac{p}{(1-p)}, where p stands for the probability of the positive event. The term “positive event” does not necessarily mean “good,” but refers to the event that we want to predict, for example, the probability that a patient has a certain disease given certain symptoms; we can think of the positive event as class label y = 1 and the symptoms as features x. Hence, for brevity, we can define the probability p as p := p(y = 1|x), the conditional probability that a particular example belongs to a certain class 1 given its features, x.

We can then further define the logit function, which is simply the logarithm of the odds (log-odds):

logit⁡(p)=log⁡p1−p\operatorname{logit}(p)=\log\frac{p}{1-p}

Note that log refers to the natural logarithm, as it is the common convention in computer science. The logit function takes input values in the range 0 to 1 and transforms them into values over the entire real-number range.

Under the logistic model, we assume that there is a linear relationship between the weighted inputs (referred to as net inputs in Chapter 2) and the log-odds:

logit⁡(p)=w1x1+⋯+wmxm+b=∑j=1mwjxj+b=wTx+b\operatorname{logit}(p)=w_1x_1+\cdots+w_mx_m+b=\sum_{j=1}^{m}w_jx_j+b=w^Tx+b

While the preceding describes an assumption we make about the linear relationship between the log-odds and the net inputs, what we are actually interested in is the probability p, the class-membership probability of an example given its features. While the logit function maps the probability to a real-number range, we can consider the inverse of this function to map the real-number range back to a [0, 1] range for the probability p.

This inverse of the logit function is typically called the logistic sigmoid function, which is sometimes simply abbreviated to sigmoid function due to its characteristic S-shape:

σ(z)=11+e−z\sigma(z)=\frac{1}{1+e^{-z}}

Here, z is the net input, the linear combination of weights, and the inputs (that is, the features associated with the training examples):

z = wTx + b

Now, let’s simply plot the sigmoid function for some values in the range –7 to 7 to see how it looks:

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> def sigmoid(z):
... return 1.0 / (1.0 + np.exp(-z))
>>> z = np.arange(-7, 7, 0.1)
>>> sigma_z = sigmoid(z)
>>> plt.plot(z, sigma_z)
>>> plt.axvline(0.0, color='k')
>>> plt.ylim(-0.1, 1.1)
>>> plt.xlabel('z')
>>> plt.ylabel('$\sigma (z)$')
>>> # y axis ticks and gridline
>>> plt.yticks([0.0, 0.5, 1.0])
>>> ax = plt.gca()
>>> ax.yaxis.grid(True)
>>> plt.tight_layout()
>>> plt.show()

As a result of executing the previous code example, we should now see the S-shaped (sigmoidal) curve:

Figure 3.2: A plot of the logistic sigmoid function
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

We can see that σ(z)\sigma(z) approaches 1 if z goes toward infinity (z→∞) since e–z becomes very small for large values of z. Similarly, σ(z)\sigma(z) goes toward 0 for z→–∞ as a result of an increasingly large denominator. Thus, we can conclude that this sigmoid function takes real-number values as input and transforms them into values in the range [0, 1] with an intercept at σ(0)=0.5\sigma(0)=0.5.

To build some understanding of the logistic regression model, we can relate it to Chapter 2. In Adaline, we used the identity function, σ(z)=z\sigma(z)=z, as the activation function. In logistic regression, this activation function simply becomes the sigmoid function that we defined earlier.

The difference between Adaline and logistic regression is illustrated in the following figure, where the only difference is the activation function:

Figure 3.3: Logistic regression compared to Adaline
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

The output of the sigmoid function is then interpreted as the probability of a particular example belonging to class 1, σ(z)=p(y=1∣x;w,b)\sigma(z)=p(y=1|x;w,b), given its features, x, and parameterized by the weights and bias, w and b. For example, if we compute σ(z)=0.8\sigma(z)=0.8 for a particular flower example, it means that the chance that this example is an Iris-versicolor flower is 80 percent. Therefore, the probability that this flower is an Iris-setosa flower can be calculated as p(y = 0|x; w, b) = 1 – p(y = 1|x; w, b) = 0.2, or 20 percent.

The predicted probability can then simply be converted into a binary outcome via a threshold function:

y^={1if σ(z)≥0.50otherwise\hat{y}=\begin{cases}1&\text{if }\sigma(z)\ge0.5\\0&\text{otherwise}\end{cases}

If we look at the preceding plot of the sigmoid function, this is equivalent to the following:

y^={1if z≥0.00otherwise\hat{y}=\begin{cases}1&\text{if }z\ge0.0\\0&\text{otherwise}\end{cases}

In fact, there are many applications where we are not only interested in the predicted class labels, but where the estimation of the class-membership probability is particularly useful (the output of the sigmoid function prior to applying the threshold function). Logistic regression is used in weather forecasting, for example, not only to predict whether it will rain on a particular day, but also to report the chance of rain. Similarly, logistic regression can be used to predict the chance that a patient has a particular disease given certain symptoms, which is why logistic regression enjoys great popularity in the field of medicine.

Learning the model weights via the logistic loss function

Section titled “Learning the model weights via the logistic loss function”

You have learned how we can use the logistic regression model to predict probabilities and class labels; now, let’s briefly talk about how we fit the parameters of the model, for instance, the weights and bias unit, w and b. In the previous chapter, we defined the mean squared error loss function as follows:

L(w,b∣x)=∑i12(σ(z(i))−y(i))2L(w,b|x)=\sum_i\frac{1}{2}(\sigma(z^{(i)})-y^{(i)})^2

We minimized this function in order to learn the parameters for our Adaline classification model. To explain how we can derive the loss function for logistic regression, let’s first define the likelihood, L\mathcal{L}, that we want to maximize when we build a logistic regression model, assuming that the individual examples in our dataset are independent of one another. The formula is as follows:

ℓ(w,b∣x)=p(y∣x;w,b)=∏i=1n(σ(z(i)))y(i)(1−σ(z(i)))1−y(i)\ell(w,b|x)=p(y|x;w,b)=\prod_{i=1}^{n}(\sigma(z^{(i)}))^{y^{(i)}}(1-\sigma(z^{(i)}))^{1-y^{(i)}}

In practice, it is easier to maximize the (natural) log of this equation, which is called the log-likelihood function:

ℓ(w,b∣x)=log⁡(ℓ(w,b∣x))=∑i[y(i)log⁡σ(z(i))+(1−y(i))log⁡(1−σ(z(i)))]\ell(w,b|x)=\log(\ell(w,b|x))=\sum_i[y^{(i)}\log\sigma(z^{(i)})+(1-y^{(i)})\log(1-\sigma(z^{(i)}))]

Firstly, applying the log function reduces the potential for numerical underflow, which can occur if the likelihoods are very small. Secondly, we can convert the product of factors into a summation of factors, which makes it easier to obtain the derivative of this function via the addition trick, as you may remember from calculus.

Deriving the likelihood function

We can obtain the expression for the likelihood of the model given the data, L(w,b∣x)\mathcal{L}(w,b|x), as follows. Given that we have a binary classification problem with class labels 0 and 1, we can think of the label 1 as a Bernoulli variable—it can take on two values, 0 and 1, with the probability p of being 1: Y∼Bern(p)Y\sim Bern(p). For a single data point, we can write this probability as P(Y=1∣X=x(i))=σ(z(i))P(Y=1|X=x^{(i)})=\sigma(z^{(i)}) and P(Y=0∣X=x(i))=1−σ(z(i))P(Y=0|X=x^{(i)})=1-\sigma(z^{(i)}).

Putting these two expressions together, and using the shorthand P(Y=y(i)∣X=x(i))=p(y(i)∣x(i))P(Y=y^{(i)}|X=x^{(i)})=p(y^{(i)}|x^{(i)}), we get the probability mass function of the Bernoulli variable:

p(y(i)∣x(i))=(σ(z(i)))y(i)(1−σ(z(i)))1−y(i)p(y^{(i)}|x^{(i)})=(\sigma(z^{(i)}))^{y^{(i)}}(1-\sigma(z^{(i)}))^{1-y^{(i)}}

We can write the likelihood of the training labels given the assumption that all training examples are independent, using the multiplication rule to compute the probability that all events occur, as follows:

L(w,b∣x)=∏i=1np(y(i)∣x(i);w,b)\mathcal{L}(w,b|x)=\prod_{i=1}^{n}p(y^{(i)}|x^{(i)};w,b)

Now, substituting the probability mass function of the Bernoulli variable, we arrive at the expression of the likelihood, which we attempt to maximize by changing the model parameters:

ℓ(w,b∣x)=∏i[(σ(z(i)))y(i)(1−σ(z(i)))1−y(i)]\ell(w,b|x)=\prod_i[(\sigma(z^{(i)}))^{y^{(i)}}(1-\sigma(z^{(i)}))^{1-y^{(i)}}]

Now, we could use an optimization algorithm such as gradient ascent to maximize this log-likelihood function. (Gradient ascent works exactly the same way as gradient descent explained in Chapter 2, except that gradient ascent maximizes a function instead of minimizing it.) Alternatively, let’s rewrite the log-likelihood as a loss function, L, that can be minimized using gradient descent as in Chapter 2:

L(w,b)=∑i[−y(i)log⁡σ(z(i))−(1−y(i))log⁡(1−σ(z(i)))]L(w,b)=\sum_i[-y^{(i)}\log\sigma(z^{(i)})-(1-y^{(i)})\log(1-\sigma(z^{(i)}))]

To get a better grasp of this loss function, let’s take a look at the loss that we calculate for one single training example:

L(σ(z),y;w,b)=−ylog⁡(σ(z))−(1−y)log⁡(1−σ(z))L(\sigma(z),y;w,b)=-y\log(\sigma(z))-(1-y)\log(1-\sigma(z))

Looking at the equation, we can see that the first term becomes zero if y = 0, and the second term becomes zero if y = 1:

L(σ(z),y;w,b)={−log⁡(σ(z))if y=1−log⁡(1−σ(z))if y=0L(\sigma(z),y;w,b)=\begin{cases}-\log(\sigma(z))&\text{if }y=1\\-\log(1-\sigma(z))&\text{if }y=0\end{cases}

Let’s write a short code snippet to create a plot that illustrates the loss of classifying a single training example for different values of σ(z)\sigma(z):

>>> def loss_1(z):
... return - np.log(sigmoid(z))
>>> def loss_0(z):
... return - np.log(1 - sigmoid(z))
>>> z = np.arange(-10, 10, 0.1)
>>> sigma_z = sigmoid(z)
>>> c1 = [loss_1(x) for x in z]
>>> plt.plot(sigma_z, c1, label='L(w, b) if y=1')
>>> c0 = [loss_0(x) for x in z]
>>> plt.plot(sigma_z, c0, linestyle='--', label='L(w, b) if y=0')
>>> plt.ylim(0.0, 5.1)
>>> plt.xlim([0, 1])
>>> plt.xlabel('$\sigma(z)$')
>>> plt.ylabel('L(w, b)')
>>> plt.legend(loc='best')
>>> plt.tight_layout()
>>> plt.show()

The resulting plot shows the sigmoid activation on the x axis in the range 0 to 1 (the inputs to the sigmoid function were z values in the range –10 to 10) and the associated logistic loss on the y axis:

Figure 3.4: A plot of the loss function used in logistic regression
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

We can see that the loss approaches 0 (continuous line) if we correctly predict that an example belongs to class 1. Similarly, we can see on the y axis that the loss also approaches 0 if we correctly predict y = 0 (dashed line). However, if the prediction is wrong, the loss goes toward infinity. The main point is that we penalize wrong predictions with an increasingly larger loss.

Converting an Adaline implementation into an algorithm for logistic regression

Section titled “Converting an Adaline implementation into an algorithm for logistic regression”

If we were to implement logistic regression ourselves, we could simply substitute the loss function, L, in our Adaline implementation from Chapter 2, with the new loss function:

L(w,b)=1n∑i[−y(i)log⁡σ(z(i))−(1−y(i))log⁡(1−σ(z(i)))]L(w,b)=\frac{1}{n}\sum_i[-y^{(i)}\log\sigma(z^{(i)})-(1-y^{(i)})\log(1-\sigma(z^{(i)}))]

We use this to compute the loss of classifying all training examples per epoch. Also, we need to swap the linear activation function with the sigmoid. If we make those changes to the Adaline code, we will end up with a working logistic regression implementation. The following is an implementation for full-batch gradient descent (but note that the same changes could be made to the stochastic gradient descent version as well):

class LogisticRegressionGD:
"""Gradient descent-based logistic regression classifier.
Parameters
------------
eta : float
Learning rate (between 0.0 and 1.0)
n_iter : int
Passes over the training dataset.
random_state : int
Random number generator seed for random weight
initialization.
Attributes
-----------
w_ : 1d-array
Weights after training.
b_ : Scalar
Bias unit after fitting.
losses_ : list
Mean squared error loss function values in each epoch.
"""
def __init__(self, eta=0.01, n_iter=50, random_state=1):
self.eta = eta
self.n_iter = n_iter
self.random_state = random_state
def fit(self, X, y):
""" Fit training data.
Parameters
----------
X : {array-like}, shape = [n_examples, n_features]
Training vectors, where n_examples is the
number of examples and n_features is the
number of features.
y : array-like, shape = [n_examples]
Target values.
Returns
-------
self : Instance of LogisticRegressionGD
"""
rgen = np.random.RandomState(self.random_state)
self.w_ = rgen.normal(loc=0.0, scale=0.01, size=X.shape[1])
self.b_ = np.float_(0.)
self.losses_ = []
for i in range(self.n_iter):
net_input = self.net_input(X)
output = self.activation(net_input)
errors = (y - output)
self.w_ += self.eta * 2.0 * X.T.dot(errors) / X.shape[0]
self.b_ += self.eta * 2.0 * errors.mean()
loss = (-y.dot(np.log(output))
- ((1 - y).dot(np.log(1 - output)))
/ X.shape[0])
self.losses_.append(loss)
return self
def net_input(self, X):
"""Calculate net input"""
return np.dot(X, self.w_) + self.b_
def activation(self, z):
"""Compute logistic sigmoid activation"""
return 1. / (1. + np.exp(-np.clip(z, -250, 250)))
def predict(self, X):
"""Return class label after unit step"""
return np.where(self.activation(self.net_input(X)) >= 0.5, 1, 0)

When we fit a logistic regression model, we have to keep in mind that it only works for binary classification tasks.

So, let’s consider only setosa and versicolor flowers (classes 0 and 1) and check that our implementation of logistic regression works:

>>> X_train_01_subset = X_train_std[(y_train == 0) | (y_train == 1)]
>>> y_train_01_subset = y_train[(y_train == 0) | (y_train == 1)]
>>> lrgd = LogisticRegressionGD(eta=0.3,
... n_iter=1000,
... random_state=1)
>>> lrgd.fit(X_train_01_subset,
... y_train_01_subset)
>>> plot_decision_regions(X=X_train_01_subset,
... y=y_train_01_subset,
... classifier=lrgd)
>>> plt.xlabel('Petal length [standardized]')
>>> plt.ylabel('Petal width [standardized]')
>>> plt.legend(loc='upper left')
>>> plt.tight_layout()
>>> plt.show()

The resulting decision region plot looks as follows:

Figure 3.5: The decision region plot for the logistic regression model
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

The gradient descent learning algorithm for logistic regression

If you compared the LogisticRegressionGD in the previous code with the AdalineGD code from Chapter 2, you may have noticed that the weight and bias update rules remained unchanged (except for the scaling factor 2). Using calculus, we can show that the parameter updates via gradient descent are indeed similar for logistic regression and Adaline. However, please note that the following derivation of the gradient descent learning rule is intended for readers who are interested in the mathematical concepts behind the gradient descent learning rule for logistic regression. It is not essential for following the rest of this chapter.

Figure 3.6 summarizes how we can calculate the partial derivative of the log-likelihood function with respect to the jth weight:

Figure 3.6: Calculating the partial derivative of the log-likelihood function
+------------------+ +------------------+
| source elements | -----> | resulting state |
+------------------+ +------------------+

Note that we omitted averaging over the training examples for brevity.

Remember from Chapter 2 that we take steps in the opposite direction of the gradient. Hence, we flip ∂L∂wj=−(y−a)xj\frac{\partial L}{\partial w_j}=-(y-a)x_j and update the jth weight as follows, including the learning rate η\eta:

wj:=wj+η(y−a)xjw_j:=w_j+\eta(y-a)x_j

While the partial derivative of the loss function with respect to the bias unit is not shown, bias derivation follows the same overall concept using the chain rule, resulting in the following update rule:

b:=b+η(y−a)b:=b+\eta(y-a)

Both the weight and bias unit updates are equal to the ones for Adaline in Chapter 2.

Training a logistic regression model with scikit-learn

Section titled “Training a logistic regression model with scikit-learn”

We just went through useful coding and math exercises in the previous subsection, which helped to illustrate the conceptual differences between Adaline and logistic regression. Now, let’s learn how to use scikit-learn’s more optimized implementation of logistic regression, which also supports multiclass settings off the shelf. Note that in recent versions of scikit-learn, the technique used for multiclass classification, multinomial, or OvR, is chosen automatically. In the following code example, we will use the sklearn.linear_model.LogisticRegression class as well as the familiar fit method to train the model on all three classes in the standardized flower training dataset. Also, we set multi_class='ovr' for illustration purposes. As an exercise for the reader, you may want to compare the results with multi_class='multinomial'. Note that the multinomial setting is now the default choice in scikit-learn’s LogisticRegression class and recommended in practice for mutually exclusive classes, such as those found in the Iris dataset. Here, “mutually exclusive” means that each training example can only belong to a single class (in contrast to multilabel classification, where a training example can be a member of multiple classes).

Now, let’s have a look at the code example:

>>> from sklearn.linear_model import LogisticRegression
>>> lr = LogisticRegression(C=100.0, solver='lbfgs',
... multi_class='ovr')
>>> lr.fit(X_train_std, y_train)
>>> plot_decision_regions(X_combined_std,
... y_combined,
... classifier=lr,
... test_idx=range(105, 150))
>>> plt.xlabel('Petal length [standardized]')
>>> plt.ylabel('Petal width [standardized]')
>>> plt.legend(loc='upper left')
>>> plt.tight_layout()
>>> plt.show()

After fitting the model on the training data, we plotted the decision regions, training examples, and test examples, as shown in Figure 3.7:

Figure 3.7: Decision regions for scikit-learn’s multi-class logistic regression model
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

Algorithms for convex optimization

Note that there exist many different algorithms for solving optimization problems. For minimizing convex loss functions, such as the logistic regression loss, it is recommended to use more advanced approaches than regular stochastic gradient descent (SGD). In fact, scikit-learn implements a whole range of such optimization algorithms, which can be specified via the solver parameter, namely, 'newton-cg', 'lbfgs', '``liblinear', 'sag', and 'saga'.

While the logistic regression loss is convex, most optimization algorithms should converge to the global loss minimum with ease. However, there are certain advantages of using one algorithm over the other. For example, in previous versions (for instance, v 0.21), scikit-learn used 'liblinear' as a default, which cannot handle the multinomial loss and is limited to the OvR scheme for multiclass classification. However, in scikit-learn v 0.22, the default solver was changed to 'lbfgs', which stands for the limited-memory Broyden–Fletcher–Goldfarb–Shanno (BFGS) algorithm (https://en.wikipedia.org/wiki/Limited-memory_BFGS) and is more flexible in this regard.

Looking at the preceding code that we used to train the LogisticRegression model, you might now be wondering, “What is this mysterious parameter C?” We will discuss this parameter in the next subsection, where we will introduce the concepts of overfitting and regularization. However, before we move on to those topics, let’s finish our discussion of class membership probabilities.

The probability that training examples belong to a certain class can be computed using the predict_proba method. For example, we can predict the probabilities of the first three examples in the test dataset as follows:

>>> lr.predict_proba(X_test_std[:3, :])

This code snippet returns the following array:

array([[3.81527885e-09, 1.44792866e-01, 8.55207131e-01],
[8.34020679e-01, 1.65979321e-01, 3.25737138e-13],
[8.48831425e-01, 1.51168575e-01, 2.62277619e-14]])

The first row corresponds to the class membership probabilities of the first flower, the second row corresponds to the class membership probabilities of the second flower, and so forth. Notice that the column-wise sum in each row is 1, as expected. (You can confirm this by executing lr.predict_proba(X_test_std[:3, :]).sum(axis=1).)

The highest value in the first row is approximately 0.85, which means that the first example belongs to class 3 (Iris-virginica) with a predicted probability of 85 percent. So, as you may have already noticed, we can get the predicted class labels by identifying the largest column in each row, for example, using NumPy’s argmax function:

>>> lr.predict_proba(X_test_std[:3, :]).argmax(axis=1)

The returned class indices are shown here (they correspond to Iris-virginica, Iris-setosa, and Iris-setosa):

array([2, 0, 0])

In the preceding code example, we computed the conditional probabilities and converted these into class labels manually by using NumPy’s argmax function. In practice, the more convenient way of obtaining class labels when using scikit-learn is to call the predict method directly:

>>> lr.predict(X_test_std[:3, :])
array([2, 0, 0])

Lastly, a word of caution if you want to predict the class label of a single flower example: scikit-learn expects a two-dimensional array as data input; thus, we have to convert a single row slice into such a format first. One way to convert a single row entry into a two-dimensional data array is to use NumPy’s reshape method to add a new dimension, as demonstrated here:

>>> lr.predict(X_test_std[0, :].reshape(1, -1))
array([2])

Overfitting is a common problem in machine learning, where a model performs well on training data but does not generalize well to unseen data (test data). If a model suffers from overfitting, we also say that the model has a high variance, which can be caused by having too many parameters, leading to a model that is too complex given the underlying data. Similarly, our model can also suffer from underfitting (high bias), which means that our model is not complex enough to capture the pattern in the training data well and therefore also suffers from low performance on unseen data.

Although we have only encountered linear models for classification so far, the problems of overfitting and underfitting can be best illustrated by comparing a linear decision boundary to more complex, nonlinear decision boundaries, as shown in Figure 3.8:

Figure 3.8: Examples of underfitted, well-fitted, and overfitted models
+------------------+ +------------------+
| source elements | -----> | resulting state |
+------------------+ +------------------+

The bias-variance tradeoff

Often, researchers use the terms “bias” and “variance” or “bias-variance tradeoff” to describe the performance of a model—that is, you may stumble upon talks, books, or articles where people say that a model has a “high variance” or “high bias.” So, what does that mean? In general, we might say that “high variance” is proportional to overfitting and “high bias” is proportional to underfitting.

In the context of machine learning models, variance measures the consistency (or variability) of the model prediction for classifying a particular example if we retrain the model multiple times, for example, on different subsets of the training dataset. We can say that the model is sensitive to the randomness in the training data. In contrast, bias measures how far off the predictions are from the correct values in general if we rebuild the model multiple times on different training datasets; bias is the measure of the systematic error that is not due to randomness.

If you are interested in the technical specification and derivation of the “bias” and “variance” terms, I’ve written about it in my lecture notes here: https://sebastianraschka.com/pdf/lecture-notes/stat451fs20/08-model-eval-1-intro__notes.pdf.

One way of finding a good bias-variance tradeoff is to tune the complexity of the model via regularization. Regularization is a very useful method for handling collinearity (high correlation among features), filtering out noise from data, and eventually preventing overfitting.

The concept behind regularization is to introduce additional information to penalize extreme parameter (weight) values. The most common form of regularization is so-called L2 regularization (sometimes also called L2 shrinkage or weight decay), which can be written as follows:

λ2n∥w∥2=λ2n∑j=1mwj2\frac{\lambda}{2n}\lVert w\rVert^2=\frac{\lambda}{2n}\sum_{j=1}^{m}w_j^2

Here, λ\lambda is the so-called regularization parameter. Note that the 2 in the denominator is merely a scaling factor, such that it cancels when computing the loss gradient. The sample size n is added to scale the regularization term similar to the loss.

Regularization and feature normalization

Regularization is another reason why feature scaling such as standardization is important. For regularization to work properly, we need to ensure that all our features are on comparable scales.

The loss function for logistic regression can be regularized by adding a simple regularization term, which will shrink the weights during model training:

L(w,b)=1n∑i[−y(i)log⁡a(z(i))−(1−y(i))log⁡(1−a(z(i)))]+λ2n∥w∥2L(w,b)=\frac{1}{n}\sum_i[-y^{(i)}\log a(z^{(i)})-(1-y^{(i)})\log(1-a(z^{(i)}))]+\frac{\lambda}{2n}\lVert w\rVert^2

The partial derivative of the unregularized loss is defined as:

∂L(w,b)∂wj=(1n∑i(σ(wTx(i))−y(i))xj(i))\frac{\partial L(w,b)}{\partial w_j}=\left(\frac{1}{n}\sum_i(\sigma(w^Tx^{(i)})-y^{(i)})x_j^{(i)}\right)

Adding the regularization term to the loss changes the partial derivative to the following form:

∂L(w,b)∂wj=(1n∑i(σ(wTx(i))−y(i))xj(i))+λnwj\frac{\partial L(w,b)}{\partial w_j}=\left(\frac{1}{n}\sum_i(\sigma(w^Tx^{(i)})-y^{(i)})x_j^{(i)}\right)+\frac{\lambda}{n}w_j

Via the regularization parameter, λ\lambda, we can then control how closely we fit the training data, while keeping the weights small. By increasing the value of λ\lambda, we increase the regularization strength. Please note that the bias unit, which is essentially an intercept term or negative threshold, as we learned in Chapter 2, is usually not regularized.

The parameter, C, that is implemented for the LogisticRegression class in scikit-learn comes from a convention in support vector machines, which will be the topic of the next section. The term C is inversely proportional to the regularization parameter, λ\lambda. Consequently, decreasing the value of the inverse regularization parameter, C, means that we are increasing the regularization strength, which we can visualize by plotting the L2 regularization path for the two weight coefficients:

>>> weights, params = [], []
>>> for c in np.arange(-5, 5):
... lr = LogisticRegression(C=10.**c,
... multi_class='ovr')
... lr.fit(X_train_std, y_train)
... weights.append(lr.coef_[1])
... params.append(10.**c)
>>> weights = np.array(weights)
>>> plt.plot(params, weights[:, 0],
... label='Petal length')
>>> plt.plot(params, weights[:, 1], linestyle='--',
... label='Petal width')
>>> plt.ylabel('Weight coefficient')
>>> plt.xlabel('C')
>>> plt.legend(loc='upper left')
>>> plt.xscale('log')
>>> plt.show()

By executing the preceding code, we fitted 10 logistic regression models with different values for the inverse-regularization parameter, C. For illustration purposes, we only collected the weight coefficients of class 1 (here, the second class in the dataset: Iris-versicolor) versus all classifiers—remember that we are using the OvR technique for multiclass classification.

As we can see in the resulting plot, the weight coefficients shrink if we decrease parameter C, that is, if we increase the regularization strength:

Figure 3.9: The impact of the inverse regularization strength parameter C on L2 regularized model results
+------------------+ +------------------+
| source elements | -----> | resulting state |
+------------------+ +------------------+

Increasing the regularization strength can reduce overfitting, so we might ask why we don’t strongly regularize all models by default. The reason is that we have to be careful when adjusting the regularization strength. For instance, if the regularization strength is too high and the weights coefficients approach zero, the model can perform very poorly due to underfitting, as illustrated in Figure 3.8.

An additional resource on logistic regression

Since in-depth coverage of the individual classification algorithms exceeds the scope of this book, Logistic Regression: From Introductory to Advanced Concepts and Applications, Dr. Scott Menard, Sage Publications, 2009, is recommended to readers who want to learn more about logistic regression.

Maximum margin classification with support vector machines

Section titled “Maximum margin classification with support vector machines”

Another powerful and widely used learning algorithm is the support vector machine (SVM), which can be considered an extension of the perceptron. Using the perceptron algorithm, we minimized misclassification errors. However, in SVMs, our optimization objective is to maximize the margin. The margin is defined as the distance between the separating hyperplane (decision boundary) and the training examples that are closest to this hyperplane, which are the so-called support vectors.

This is illustrated in Figure 3.10:

Figure 3.10: SVM maximizes the margin between the decision boundary and training data points
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

The rationale behind having decision boundaries with large margins is that they tend to have a lower generalization error, whereas models with small margins are more prone to overfitting.

Unfortunately, while the main intuition behind SVMs is relatively simple, the mathematics behind them is quite advanced and would require sound knowledge of constrained optimization.

Hence, the details behind maximum margin optimization in SVMs are beyond the scope of this book. However, we recommend the following resources if you are interested in learning more:

  • Chris J.C. Burges’ excellent explanation in A Tutorial on Support Vector Machines for Pattern Recognition (Data Mining and Knowledge Discovery, 2(2): 121-167, 1998)
  • Vladimir Vapnik’s book The Nature of Statistical Learning Theory, Springer Science+Business Media, Vladimir Vapnik, 2000
  • Andrew Ng’s very detailed lecture notes available at https://see.stanford.edu/materials/aimlcs229/cs229-notes3.pdf

Dealing with a nonlinearly separable case using slack variables

Section titled “Dealing with a nonlinearly separable case using slack variables”

Although we don’t want to dive much deeper into the more involved mathematical concepts behind the maximum-margin classification, let’s briefly mention the so-called slack variable, which was introduced by Vladimir Vapnik in 1995 and led to the so-called soft-margin classification. The motivation for introducing the slack variable was that the linear constraints in the SVM optimization objective need to be relaxed for nonlinearly separable data to allow the convergence of the optimization in the presence of misclassifications, under appropriate loss penalization.

The use of the slack variable, in turn, introduces the variable, which is commonly referred to as C in SVM contexts. We can consider C as a hyperparameter for controlling the penalty for misclassification. Large values of C correspond to large error penalties, whereas we are less strict about misclassification errors if we choose smaller values for C. We can then use the C parameter to control the width of the margin and therefore tune the bias-variance tradeoff, as illustrated in Figure 3.11:

Figure 3.11: The impact of large and small values of the inverse regularization strength *C* on classification
+-----+-----+-----+-----+
| img | img | img | img |
+-----+-----+-----+-----+
| img | img | img | img |
+-----+-----+-----+-----+

This concept is related to regularization, which we discussed in the previous section in the context of regularized regression, where decreasing the value of C increases the bias (underfitting) and lowers the variance (overfitting) of the model.

Now that we have learned the basic concepts behind a linear SVM, let’s train an SVM model to classify the different flowers in our Iris dataset:

>>> from sklearn.svm import SVC
>>> svm = SVC(kernel='linear', C=1.0, random_state=1)
>>> svm.fit(X_train_std, y_train)
>>> plot_decision_regions(X_combined_std,
... y_combined,
... classifier=svm,
... test_idx=range(105, 150))
>>> plt.xlabel('Petal length [standardized]')
>>> plt.ylabel('Petal width [standardized]')
>>> plt.legend(loc='upper left')
>>> plt.tight_layout()
>>> plt.show()

The three decision regions of the SVM, visualized after training the classifier on the Iris dataset by executing the preceding code example, are shown in Figure 3.12:

Figure 3.12: SVM’s decision regions
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

Logistic regression versus SVMs

In practical classification tasks, linear logistic regression and linear SVMs often yield very similar results. Logistic regression tries to maximize the conditional likelihoods of the training data, which makes it more prone to outliers than SVMs, which mostly care about the points that are closest to the decision boundary (support vectors). On the other hand, logistic regression has the advantage of being a simpler model and can be implemented more easily, and is mathematically easier to explain. Furthermore, logistic regression models can be easily updated, which is attractive when working with streaming data.

Alternative implementations in scikit-learn

Section titled “Alternative implementations in scikit-learn”

The scikit-learn library’s LogisticRegression class, which we used in the previous sections, can make use of the LIBLINEAR library by setting solver='liblinear'. LIBLINEAR is a highly optimized C/C++ library developed at the National Taiwan University (http://www.csie.ntu.edu.tw/~cjlin/liblinear/).

Similarly, the SVC class that we used to train an SVM makes use of LIBSVM, which is an equivalent C/C++ library specialized for SVMs (http://www.csie.ntu.edu.tw/~cjlin/libsvm/).

The advantage of using LIBLINEAR and LIBSVM over, for example, native Python implementations is that they allow the extremely quick training of large amounts of linear classifiers. However, sometimes our datasets are too large to fit into computer memory. Thus, scikit-learn also offers alternative implementations via the SGDClassifier class, which also supports online learning via the partial_fit method. The concept behind the SGDClassifier class is similar to the stochastic gradient algorithm that we implemented in Chapter 2 for Adaline.

We could initialize the SGD version of the perceptron (loss='perceptron'), logistic regression (loss='log'), and an SVM with default parameters (loss='hinge'), as follows:

>>> from sklearn.linear_model import SGDClassifier
>>> ppn = SGDClassifier(loss='perceptron')
>>> lr = SGDClassifier(loss='log')
>>> svm = SGDClassifier(loss='hinge')

Solving nonlinear problems using a kernel SVM

Section titled “Solving nonlinear problems using a kernel SVM”

Another reason why SVMs enjoy high popularity among machine learning practitioners is that they can be easily kernelized to solve nonlinear classification problems. Before we discuss the main concept behind the so-called kernel SVM, the most common variant of SVMs, let’s first create a synthetic dataset to see what such a nonlinear classification problem may look like.

Kernel methods for linearly inseparable data

Section titled “Kernel methods for linearly inseparable data”

Using the following code, we will create a simple dataset that has the form of an XOR gate using the logical_xor function from NumPy, where 100 examples will be assigned the class label 1, and 100 examples will be assigned the class label -1:

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> np.random.seed(1)
>>> X_xor = np.random.randn(200, 2)
>>> y_xor = np.logical_xor(X_xor[:, 0] > 0,
... X_xor[:, 1] > 0)
>>> y_xor = np.where(y_xor, 1, 0)
>>> plt.scatter(X_xor[y_xor == 1, 0],
... X_xor[y_xor == 1, 1],
... c='royalblue', marker='s',
... label='Class 1')
>>> plt.scatter(X_xor[y_xor == 0, 0],
... X_xor[y_xor == 0, 1],
... c='tomato', marker='o',
... label='Class 0')
>>> plt.xlim([-3, 3])
>>> plt.ylim([-3, 3])
>>> plt.xlabel('Feature 1')
>>> plt.ylabel('Feature 2')
>>> plt.legend(loc='best')
>>> plt.tight_layout()
>>> plt.show()

After executing the code, we will have an XOR dataset with random noise, as shown in Figure 3.13:

Figure 3.13: A plot of the XOR dataset
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

Obviously, we would not be able to separate the examples from the positive and negative class very well using a linear hyperplane as a decision boundary via the linear logistic regression or linear SVM model that we discussed in earlier sections.

The basic idea behind kernel methods for dealing with such linearly inseparable data is to create nonlinear combinations of the original features to project them onto a higher-dimensional space via a mapping function, ϕ\phi, where the data becomes linearly separable. As shown in Figure 3.14, we can transform a two-dimensional dataset into a new three-dimensional feature space, where the classes become separable via the following projection:

ϕ(x1,x2)=(z1,z2,z3)=(x1,x2,x12+x22)\phi(x_1,x_2)=(z_1,z_2,z_3)=(x_1,x_2,x_1^2+x_2^2)

This allows us to separate the two classes shown in the plot via a linear hyperplane that becomes a nonlinear decision boundary if we project it back onto the original feature space, as illustrated with the following concentric circle dataset:

Figure 3.14: The process of classifying nonlinear data using kernel methods
+------------------+ +------------------+
| source elements | -----> | resulting state |
+------------------+ +------------------+

Using the kernel trick to find separating hyperplanes in a high-dimensional space

Section titled “Using the kernel trick to find separating hyperplanes in a high-dimensional space”

To solve a nonlinear problem using an SVM, we would transform the training data into a higher-dimensional feature space via a mapping function, ϕ\phi, and train a linear SVM model to classify the data in this new feature space. Then, we could use the same mapping function, ϕ\phi, to transform new, unseen data to classify it using the linear SVM model.

However, one problem with this mapping approach is that the construction of the new features is computationally very expensive, especially if we are dealing with high-dimensional data. This is where the so-called kernel trick comes into play.

Although we did not go into much detail about how to solve the quadratic programming task to train an SVM, in practice, we just need to replace the dot product x(i)Tx(j) by ϕ(x(i))Tϕ(x(j))\phi(x^{(i)})^T\phi(x^{(j)}). To save the expensive step of calculating this dot product between two points explicitly, we define a so-called kernel function:

κ(x(i),x(j))=ϕ(x(i))Tϕ(x(j))\kappa(x^{(i)},x^{(j)})=\phi(x^{(i)})^T\phi(x^{(j)})

One of the most widely used kernels is the radial basis function (RBF) kernel, which can simply be called the Gaussian kernel:

κ(x(i),x(j))=exp⁡(−∥x(i)−x(j)∥22σ2)\kappa(x^{(i)},x^{(j)})=\exp\left(-\frac{\lVert x^{(i)}-x^{(j)}\rVert^2}{2\sigma^2}\right)

This is often simplified to:

κ(x(i),x(j))=exp⁡(−γ∥x(i)−x(j)∥2)\kappa(x^{(i)},x^{(j)})=\exp(-\gamma\lVert x^{(i)}-x^{(j)}\rVert^2)

Here, γ=12σ2\gamma=\frac{1}{2\sigma^2} is a free parameter to be optimized.

Roughly speaking, the term “kernel” can be interpreted as a similarity function between a pair of examples. The minus sign inverts the distance measure into a similarity score, and, due to the exponential term, the resulting similarity score will fall into a range between 1 (for exactly similar examples) and 0 (for very dissimilar examples).

Now that we have covered the big picture behind the kernel trick, let’s see if we can train a kernel SVM that is able to draw a nonlinear decision boundary that separates the XOR data well. Here, we simply use the SVC class from scikit-learn that we imported earlier and replace the kernel='linear' parameter with kernel='rbf':

>>> svm = SVC(kernel='rbf', random_state=1, gamma=0.10, C=10.0)
>>> svm.fit(X_xor, y_xor)
>>> plot_decision_regions(X_xor, y_xor, classifier=svm)
>>> plt.legend(loc='upper left')
>>> plt.tight_layout()
>>> plt.show()

As we can see in the resulting plot, the kernel SVM separates the XOR data relatively well:

Figure 3.15: The decision boundary on the XOR data using a kernel method
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

The γ\gamma parameter, which we set to gamma=0.1, can be understood as a cut-off parameter for the Gaussian sphere. If we increase the value for γ\gamma, we increase the influence or reach of the training examples, which leads to a tighter and bumpier decision boundary. To get a better understanding of γ\gamma, let’s apply an RBF kernel SVM to our Iris flower dataset:

>>> svm = SVC(kernel='rbf', random_state=1, gamma=0.2, C=1.0)
>>> svm.fit(X_train_std, y_train)
>>> plot_decision_regions(X_combined_std,
... y_combined, classifier=svm,
... test_idx=range(105, 150))
>>> plt.xlabel('Petal length [standardized]')
>>> plt.ylabel('Petal width [standardized]')
>>> plt.legend(loc='upper left')
>>> plt.tight_layout()
>>> plt.show()

Since we chose a relatively small value for γ\gamma, the resulting decision boundary of the RBF kernel SVM model will be relatively soft, as shown in Figure 3.16:

Figure 3.16: The decision boundaries on the Iris dataset using an RBF kernel SVM model with a small $\gamma$ value
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

Now, let’s increase the value of γ\gamma and observe the effect on the decision boundary:

>>> svm = SVC(kernel='rbf', random_state=1, gamma=100.0, C=1.0)
>>> svm.fit(X_train_std, y_train)
>>> plot_decision_regions(X_combined_std,
... y_combined, classifier=svm,
... test_idx=range(105,150))
>>> plt.xlabel('Petal length [standardized]')
>>> plt.ylabel('Petal width [standardized]')
>>> plt.legend(loc='upper left')
>>> plt.tight_layout()
>>> plt.show()

In Figure 3.17, we can now see that the decision boundary around the classes 0 and 1 is much tighter using a relatively large value of γ\gamma:

Figure 3.17: The decision boundaries on the Iris dataset using an RBF kernel SVM model with a large $\gamma$ value
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

Although the model fits the training dataset very well, such a classifier will likely have a high generalization error on unseen data. This illustrates that the γ\gamma parameter also plays an important role in controlling overfitting or variance when the algorithm is too sensitive to fluctuations in the training dataset.

Decision tree classifiers are attractive models if we care about interpretability. As the name “decision tree” suggests, we can think of this model as breaking down our data by making a decision based on asking a series of questions.

Let’s consider the following example in which we use a decision tree to decide upon an activity on a particular day:

Figure 3.18: An example of a decision tree
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

Based on the features in our training dataset, the decision tree model learns a series of questions to infer the class labels of the examples. Although Figure 3.18 illustrates the concept of a decision tree based on categorical variables, the same concept applies if our features are real numbers, like in the Iris dataset. For example, we could simply define a cut-off value along the sepal width feature axis and ask a binary question: “Is the sepal width ≥ 2.8 cm?”

Using the decision algorithm, we start at the tree root and split the data on the feature that results in the largest information gain (IG), which will be explained in more detail in the following section. In an iterative process, we can then repeat this splitting procedure at each child node until the leaves are pure. This means that the training examples at each node all belong to the same class. In practice, this can result in a very deep tree with many nodes, which can easily lead to overfitting. Thus, we typically want to prune the tree by setting a limit for the maximum depth of the tree.

Maximizing IG – getting the most bang for your buck

Section titled “Maximizing IG – getting the most bang for your buck”

To split the nodes at the most informative features, we need to define an objective function to optimize via the tree learning algorithm. Here, our objective function is to maximize the IG at each split, which we define as follows:

IG(Dp,f)=I(Dp)−∑j=1mNjNpI(Dj)IG(D_p,f)=I(D_p)-\sum_{j=1}^{m}\frac{N_j}{N_p}I(D_j)

Here, f is the feature to perform the split; Dp and Dj are the dataset of the parent and jth child node; I is our impurity measure; Np is the total number of training examples at the parent node; and Nj is the number of examples in the jth child node. As we can see, the information gain is simply the difference between the impurity of the parent node and the sum of the child node impurities—the lower the impurities of the child nodes, the larger the information gain. However, for simplicity and to reduce the combinatorial search space, most libraries (including scikit-learn) implement binary decision trees. This means that each parent node is split into two child nodes, Dleft and Dright:

IG(Dp,f)=I(Dp)−NleftNpI(Dleft)−NrightNpI(Dright)IG(D_p,f)=I(D_p)-\frac{N_{left}}{N_p}I(D_{left})-\frac{N_{right}}{N_p}I(D_{right})

The three impurity measures or splitting criteria that are commonly used in binary decision trees are Gini impurity (IG), entropy (IH), and the classification error (IE). Let’s start with the definition of entropy for all non-empty classes (p(i∣t)≠0p(i|t)\ne0):

IH(t)=−∑i=1cp(i∣t)log⁡2p(i∣t)I_H(t)=-\sum_{i=1}^{c}p(i|t)\log_2p(i|t)

Here, p(i|t) is the proportion of the examples that belong to class i for a particular node, t. The entropy is therefore 0 if all examples at a node belong to the same class, and the entropy is maximal if we have a uniform class distribution. For example, in a binary class setting, the entropy is 0 if p(i=1|t) = 1 or p(i=0|t) = 0. If the classes are distributed uniformly with p(i=1|t) = 0.5 and p(i=0|t) = 0.5, the entropy is 1. Therefore, we can say that the entropy criterion attempts to maximize the mutual information in the tree.

To provide a visual intuition, let us visualize the entropy values for different class distributions via the following code:

>>> def entropy(p):
... return - p * np.log2(p) - (1 - p) * np.log2((1 - p))
>>> x = np.arange(0.0, 1.0, 0.01)
>>> ent = [entropy(p) if p != 0 else None for p in x]
>>> plt.ylabel('Entropy')
>>> plt.xlabel('Class-membership probability p(i=1)')
>>> plt.plot(x, ent)
>>> plt.show()

Figure 3.19 below shows the plot produced by the preceding code:

Figure 3.19: Entropy values for different class-membership probabilities
+------------------+ +------------------+
| source elements | -----> | resulting state |
+------------------+ +------------------+

The Gini impurity can be understood as a criterion to minimize the probability of misclassification:

IG(t)=∑i=1cp(i∣t)(1−p(i∣t))=1−∑i=1cp(i∣t)2I_G(t)=\sum_{i=1}^{c}p(i|t)(1-p(i|t))=1-\sum_{i=1}^{c}p(i|t)^2

Similar to entropy, the Gini impurity is maximal if the classes are perfectly mixed, for example, in a binary class setting (c = 2):

IG(t)=1−∑i=1c0.52=0.5I_G(t)=1-\sum_{i=1}^{c}0.5^2=0.5

However, in practice, both the Gini impurity and entropy typically yield very similar results, and it is often not worth spending much time on evaluating trees using different impurity criteria rather than experimenting with different pruning cut-offs. In fact, as you will see later in Figure 3.21, both the Gini impurity and entropy have a similar shape.

Another impurity measure is the classification error:

IE(t)=1−max⁡{p(i∣t)}I_E(t)=1-\max\{p(i|t)\}

This is a useful criterion for pruning, but not recommended for growing a decision tree, since it is less sensitive to changes in the class probabilities of the nodes. We can illustrate this by looking at the two possible splitting scenarios shown in Figure 3.20:

Figure 3.20: Decision tree data splits
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

We start with a dataset, Dp, at the parent node, which consists of 40 examples from class 1 and 40 examples from class 2 that we split into two datasets, Dleft and Dright. The information gain using the classification error as a splitting criterion would be the same (IGE = 0.25) in both scenarios, A and B:

ΔIG=0.5−0.25=0.25,ΔIH=1−0.5=0.5,ΔIE=0.5−0.25=0.25\Delta I_G=0.5-0.25=0.25,\quad \Delta I_H=1-0.5=0.5,\quad \Delta I_E=0.5-0.25=0.25

However, the Gini impurity would favor the split in scenario B (IGG=0.16‾IG_G=0.\overline{16}) over scenario A (IGG = 0.125), which is indeed purer:

IG(Dp)=0.5,IG(Dleft)=0.0,IG(Dright)=0.25,IGG=0.5−35⋅0−25⋅0.25=0.4I_G(D_p)=0.5,\quad I_G(D_{left})=0.0,\quad I_G(D_{right})=0.25,\quad IG_G=0.5-\frac{3}{5}\cdot0-\frac{2}{5}\cdot0.25=0.4

Similarly, the entropy criterion would also favor scenario B (IGH = 0.31) over scenario A (IGH = 0.19):

IG(Dp)=0.5,IG(Dleft)=0.444,IG(Dright)=0.0,IGG=0.5−35⋅0.444−25⋅0=0.23I_G(D_p)=0.5,\quad I_G(D_{left})=0.444,\quad I_G(D_{right})=0.0,\quad IG_G=0.5-\frac{3}{5}\cdot0.444-\frac{2}{5}\cdot0=0.23

For a more visual comparison of the three different impurity criteria that we discussed previously, let’s plot the impurity indices for the probability range [0, 1] for class 1. Note that we will also add a scaled version of the entropy (entropy / 2) to observe that the Gini impurity is an intermediate measure between entropy and the classification error. The code is as follows:

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> def gini(p):
... return p*(1 - p) + (1 - p)*(1 - (1-p))
>>> def entropy(p):
... return - p*np.log2(p) - (1 - p)*np.log2((1 - p))
>>> def error(p):
... return 1 - np.max([p, 1 - p])
>>> x = np.arange(0.0, 1.0, 0.01)
>>> ent = [entropy(p) if p != 0 else None for p in x]
>>> sc_ent = [e*0.5 if e else None for e in ent]
>>> err = [error(i) for i in x]
>>> fig = plt.figure()
>>> ax = plt.subplot(111)
>>> for i, lab, ls, c, in zip([ent, sc_ent, gini(x), err],
... ['Entropy', 'Entropy (scaled)',
... 'Gini impurity',
... 'Misclassification error'],
... ['-', '-', '--', '-.'],
... ['black', 'lightgray',
... 'red', 'green', 'cyan']):
... line = ax.plot(x, i, label=lab,
... linestyle=ls, lw=2, color=c)
>>> ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15),
... ncol=5, fancybox=True, shadow=False)
>>> ax.axhline(y=0.5, linewidth=1, color='k', linestyle='--')
>>> ax.axhline(y=1.0, linewidth=1, color='k', linestyle='--')
>>> plt.ylim([0, 1.1])
>>> plt.xlabel('p(i=1)')
>>> plt.ylabel('impurity index')
>>> plt.show()

The plot produced by the preceding code example is as follows:

Figure 3.21: The different impurity indices for different class-membership probabilities between 0 and 1
+------------------+ +------------------+
| source elements | -----> | resulting state |
+------------------+ +------------------+

Decision trees can build complex decision boundaries by dividing the feature space into rectangles. However, we have to be careful since the deeper the decision tree, the more complex the decision boundary becomes, which can easily result in overfitting. Using scikit-learn, we will now train a decision tree with a maximum depth of 4, using the Gini impurity as a criterion for impurity.

Although feature scaling may be desired for visualization purposes, note that feature scaling is not a requirement for decision tree algorithms. The code is as follows:

>>> from sklearn.tree import DecisionTreeClassifier
>>> tree_model = DecisionTreeClassifier(criterion='gini',
... max_depth=4,
... random_state=1)
>>> tree_model.fit(X_train, y_train)
>>> X_combined = np.vstack((X_train, X_test))
>>> y_combined = np.hstack((y_train, y_test))
>>> plot_decision_regions(X_combined,
... y_combined,
... classifier=tree_model,
... test_idx=range(105, 150))
>>> plt.xlabel('Petal length [cm]')
>>> plt.ylabel('Petal width [cm]')
>>> plt.legend(loc='upper left')
>>> plt.tight_layout()
>>> plt.show()

After executing the code example, we get the typical axis-parallel decision boundaries of the decision tree:

Figure 3.22: The decision boundaries of the Iris data using a decision tree
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

A nice feature in scikit-learn is that it allows us to readily visualize the decision tree model after training via the following code:

>>> from sklearn import tree
>>> feature_names = ['Sepal length', 'Sepal width',
... 'Petal length', 'Petal width']
>>> tree.plot_tree(tree_model,
... feature_names=feature_names,
... filled=True)
>>> plt.show()
Figure 3.23: A decision tree model fit to the Iris dataset
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

Setting filled=True in the plot_tree function we called colors the nodes by the majority class label at that node. There are many additional options available, which you can find in the documentation at https://scikit-learn.org/stable/modules/generated/sklearn.tree.plot_tree.html.

Looking at the decision tree figure, we can now nicely trace back the splits that the decision tree determined from our training dataset. Regarding the feature splitting criterion at each node, note that the branches to the left correspond to “True” and branches to the right correspond to “False.”

Looking at the root node, it starts with 105 examples at the top. The first split uses a sepal width cut-off ≤ 0.75 cm for splitting the root node into two child nodes with 35 examples (left child node) and 70 examples (right child node). After the first split, we can see that the left child node is already pure and only contains examples from the Iris-setosa class (Gini impurity = 0). The further splits on the right are then used to separate the examples from the Iris-versicolor and Iris-virginica class.

Looking at this tree, and the decision region plot of the tree, we can see that the decision tree does a very good job of separating the flower classes. Unfortunately, scikit-learn currently does not implement functionality to manually post-prune a decision tree. However, we could go back to our previous code example, change the max_depth of our decision tree to 3, and compare it to our current model, but we leave this as an exercise for the interested reader.

Alternatively, scikit-learn provides an automatic cost complexity post-pruning procedure for decision trees. Interested readers can find more information about this more advanced topic in the following tutorial: https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html.

Combining multiple decision trees via random forests

Section titled “Combining multiple decision trees via random forests”

Ensemble methods have gained huge popularity in applications of machine learning during the last decade due to their good classification performance and robustness toward overfitting. While we are going to cover different ensemble methods, including bagging and boosting, later in Chapter 7, Combining Different Models for Ensemble Learning, let’s discuss the decision tree-based random forest algorithm, which is known for its good scalability and ease of use. A random forest can be considered as an ensemble of decision trees. The idea behind a random forest is to average multiple (deep) decision trees that individually suffer from high variance to build a more robust model that has a better generalization performance and is less susceptible to overfitting. The random forest algorithm can be summarized in four simple steps:

  1. Draw a random bootstrap sample of size n (randomly choose n examples from the training dataset with replacement).
  2. Grow a decision tree from the bootstrap sample. At each node:
    1. Randomly select d features without replacement. 2. Split the node using the feature that provides the best split according to the objective function, for instance, maximizing the information gain.
  3. Repeat steps 1-2 k times.
  4. Aggregate the prediction by each tree to assign the class label by majority vote. Majority voting will be discussed in more detail in Chapter 7.

We should note one slight modification in step 2 when we are training the individual decision trees: instead of evaluating all features to determine the best split at each node, we only consider a random subset of those.

Sampling with and without replacement

In case you are not familiar with the terms sampling “with” and “without” replacement, let’s walk through a simple thought experiment. Let’s assume that we are playing a lottery game where we randomly draw numbers from an urn. We start with an urn that holds five unique numbers, 0, 1, 2, 3, and 4, and we draw exactly one number on each turn. In the first round, the chance of drawing a particular number from the urn would be 1/5. Now, in sampling without replacement, we do not put the number back into the urn after each turn. Consequently, the probability of drawing a particular number from the set of remaining numbers in the next round depends on the previous round. For example, if we have a remaining set of numbers 0, 1, 2, and 4, the chance of drawing number 0 would become 1/4 in the next turn.

However, in random sampling with replacement, we always return the drawn number to the urn so that the probability of drawing a particular number at each turn does not change; we can draw the same number more than once. In other words, in sampling with replacement, the samples (numbers) are independent and have a covariance of zero. For example, the results from five rounds of drawing random numbers could look like this:

  • Random sampling without replacement: 2, 1, 3, 4, 0
  • Random sampling with replacement: 1, 3, 3, 4, 1

Although random forests don’t offer the same level of interpretability as decision trees, a big advantage of random forests is that we don’t have to worry so much about choosing good hyperparameter values. We typically don’t need to prune the random forest since the ensemble model is quite robust to noise from averaging the predictions among the individual decision trees. The only parameter that we need to care about in practice is the number of trees, k, (step 3) that we choose for the random forest. Typically, the larger the number of trees, the better the performance of the random forest classifier at the expense of an increased computational cost.

Although it is less common in practice, other hyperparameters of the random forest classifier that can be optimized—using techniques that we will discuss in Chapter 6, Learning Best Practices for Model Evaluation and Hyperparameter Tuning—are the size, n, of the bootstrap sample (step 1) and the number of features, d, that are randomly chosen for each split (step 2a), respectively. Via the sample size, n, of the bootstrap sample, we control the bias-variance tradeoff of the random forest.

Decreasing the size of the bootstrap sample increases the diversity among the individual trees since the probability that a particular training example is included in the bootstrap sample is lower. Thus, shrinking the size of the bootstrap samples may increase the randomness of the random forest, and it can help to reduce the effect of overfitting. However, smaller bootstrap samples typically result in a lower overall performance of the random forest and a small gap between training and test performance, but a low test performance overall. Conversely, increasing the size of the bootstrap sample may increase the degree of overfitting. Because the bootstrap samples, and consequently the individual decision trees, become more similar to one another, they learn to fit the original training dataset more closely.

In most implementations, including the RandomForestClassifier implementation in scikit-learn, the size of the bootstrap sample is chosen to be equal to the number of training examples in the original training dataset, which usually provides a good bias-variance tradeoff. For the number of features, d, at each split, we want to choose a value that is smaller than the total number of features in the training dataset. A reasonable default that is used in scikit-learn and other implementations is d=md=\sqrt{m}, where m is the number of features in the training dataset.

Conveniently, we don’t have to construct the random forest classifier from individual decision trees by ourselves because there is already an implementation in scikit-learn that we can use:

>>> from sklearn.ensemble import RandomForestClassifier
>>> forest = RandomForestClassifier(n_estimators=25,
... random_state=1,
... n_jobs=2)
>>> forest.fit(X_train, y_train)
>>> plot_decision_regions(X_combined, y_combined,
... classifier=forest, test_idx=range(105,150))
>>> plt.xlabel('Petal length [cm]')
>>> plt.ylabel('Petal width [cm]')
>>> plt.legend(loc='upper left')
>>> plt.tight_layout()
>>> plt.show()

After executing the preceding code, we should see the decision regions formed by the ensemble of trees in the random forest, as shown in Figure 3.24:

Figure 3.24: Decision boundaries on the Iris dataset using a random forest
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

Using the preceding code, we trained a random forest from 25 decision trees via the n_estimators parameter. By default, it uses the Gini impurity measure as a criterion to split the nodes. Although we are growing a very small random forest from a very small training dataset, we used the n_jobs parameter for demonstration purposes, which allows us to parallelize the model training using multiple cores of our computer (here, two cores). If you encounter errors with this code, your computer may not support multiprocessing. You can omit the n_jobs parameter or set it to n_jobs=None.

K-nearest neighbors – a lazy learning algorithm

Section titled “K-nearest neighbors – a lazy learning algorithm”

The last supervised learning algorithm that we want to discuss in this chapter is the k-nearest neighbor (KNN) classifier, which is particularly interesting because it is fundamentally different from the learning algorithms that we have discussed so far.

KNN is a typical example of a lazy learner. It is called “lazy” not because of its apparent simplicity, but because it doesn’t learn a discriminative function from the training data but memorizes the training dataset instead.

Parametric versus non-parametric models

Machine learning algorithms can be grouped into parametric and non-parametric models. Using parametric models, we estimate parameters from the training dataset to learn a function that can classify new data points without requiring the original training dataset anymore. Typical examples of parametric models are the perceptron, logistic regression, and the linear SVM. In contrast, non-parametric models can’t be characterized by a fixed set of parameters, and the number of parameters changes with the amount of training data. Two examples of non-parametric models that we have seen so far are the decision tree classifier/random forest and the kernel (but not linear) SVM.

KNN belongs to a subcategory of non-parametric models described as instance-based learning. Models based on instance-based learning are characterized by memorizing the training dataset, and lazy learning is a special case of instance-based learning that is associated with no (zero) cost during the learning process.

The KNN algorithm itself is fairly straightforward and can be summarized by the following steps:

  1. Choose the number of k and a distance metric
  2. Find the k-nearest neighbors of the data record that we want to classify
  3. Assign the class label by majority vote

Figure 3.25 illustrates how a new data point (?) is assigned the triangle class label based on majority voting among its five nearest neighbors:

Figure 3.25: How k-nearest neighbors works
+------------------+ +------------------+
| source elements | -----> | resulting state |
+------------------+ +------------------+

Based on the chosen distance metric, the KNN algorithm finds the k examples in the training dataset that are closest (most similar) to the point that we want to classify. The class label of the data point is then determined by a majority vote among its k nearest neighbors.

Advantages and disadvantages of memory-based approaches

The main advantage of such a memory-based approach is that the classifier immediately adapts as we collect new training data. However, the downside is that the computational complexity for classifying new examples grows linearly with the number of examples in the training dataset in the worst-case scenario—unless the dataset has very few dimensions (features) and the algorithm has been implemented using efficient data structures for querying the training data more effectively. Such data structures include k-d tree (https://en.wikipedia.org/wiki/K-d_tree) and ball tree (https://en.wikipedia.org/wiki/Ball_tree), which are both supported in scikit-learn. Furthermore, next to computational costs for querying data, large datasets can also be problematic in terms of limited storage capacities.

However, in many cases when we are working with relatively small to medium-sized datasets, memory-based methods can provide good predictive and computational performance and are thus a good choice for approaching many real-world problems. Recent examples of using nearest neighbor methods include predicting properties of pharmaceutical drug targets (Machine Learning to Identify Flexibility Signatures of Class A GPCR Inhibition, Biomolecules, 2020, Joe Bemister-Buffington, Alex J. Wolf, Sebastian Raschka, and Leslie A. Kuhn, https://www.mdpi.com/2218-273X/10/3/454) and state-of-the-art language models (Efficient Nearest Neighbor Language Models, 2021, Junxian He, Graham Neubig, and Taylor Berg-Kirkpatrick, https://arxiv.org/abs/2109.04212).

By executing the following code, we will now implement a KNN model in scikit-learn using a Euclidean distance metric:

>>> from sklearn.neighbors import KNeighborsClassifier
>>> knn = KNeighborsClassifier(n_neighbors=5, p=2,
... metric='minkowski')
>>> knn.fit(X_train_std, y_train)
>>> plot_decision_regions(X_combined_std, y_combined,
... classifier=knn, test_idx=range(105,150))
>>> plt.xlabel('Petal length [standardized]')
>>> plt.ylabel('Petal width [standardized]')
>>> plt.legend(loc='upper left')
>>> plt.tight_layout()
>>> plt.show()

By specifying five neighbors in the KNN model for this dataset, we obtain a relatively smooth decision boundary, as shown in Figure 3.26:

Figure 3.26: k-nearest neighbors’ decision boundaries on the Iris dataset
y
^ o o class/points
| o x boundary/fit/cluster split
| o ----->
| x x
+-----------------> x

Resolving ties

In the case of a tie, the scikit-learn implementation of the KNN algorithm will prefer the neighbors with a closer distance to the data record to be classified. If the neighbors have similar distances, the algorithm will choose the class label that comes first in the training dataset.

The right choice of k is crucial to finding a good balance between overfitting and underfitting. We also have to make sure that we choose a distance metric that is appropriate for the features in the dataset. Often, a simple Euclidean distance measure is used for real-value examples, for example, the flowers in our Iris dataset, which have features measured in centimeters. However, if we are using a Euclidean distance measure, it is also important to standardize the data so that each feature contributes equally to the distance. The minkowski distance that we used in the previous code is just a generalization of the Euclidean and Manhattan distance, which can be written as follows:

d(x(i),x(j))=∑k∣xk(i)−xk(j)∣ppd(x^{(i)},x^{(j)})=\sqrt[p]{\sum_k|x_k^{(i)}-x_k^{(j)}|^p}

It becomes the Euclidean distance if we set the parameter p=2 or the Manhattan distance at p=1. Many other distance metrics are available in scikit-learn and can be provided to the metric parameter. They are listed at https://scikit-learn.org/stable/modules/generated/sklearn.metrics.DistanceMetric.html.

Lastly, it is important to mention that KNN is very susceptible to overfitting due to the curse of dimensionality. The curse of dimensionality describes the phenomenon where the feature space becomes increasingly sparse for an increasing number of dimensions of a fixed-size training dataset. We can think of even the closest neighbors as being too far away in a high-dimensional space to give a good estimate.

We discussed the concept of regularization in the section about logistic regression as one way to avoid overfitting. However, in models where regularization is not applicable, such as decision trees and KNN, we can use feature selection and dimensionality reduction techniques to help us to avoid the curse of dimensionality. This will be discussed in more detail in the next two chapters.

Alternative machine learning implementations with GPU support

When working with large datasets, running k-nearest neighbors or fitting random forests with many estimators can require substantial computing resources and processing time. If you have a computer equipped with an NVIDIA GPU that is compatible with recent versions of NVIDIA’s CUDA library, we recommend considering the RAPIDS ecosystem (https://docs.rapids.ai/api). For instance, RAPIDS’ cuML (https://docs.rapids.ai/api/cuml/stable/) library implements many of scikit-learn’s machine learning algorithms with GPU support to accelerate the processing speeds. You can find an introduction to cuML at https://docs.rapids.ai/api/cuml/stable/estimator_intro.html. If you are interested in learning more about the RAPIDS ecosystem, please also see the freely accessible journal article that we wrote in collaboration with the RAPIDS team: Machine Learning in Python: Main Developments and Technology Trends in Data Science, Machine Learning, and Artificial Intelligence (https://www.mdpi.com/2078-2489/11/4/193).

In this chapter, you learned about many different machine learning algorithms that are used to tackle linear and nonlinear problems. You have seen that decision trees are particularly attractive if we care about interpretability. Logistic regression is not only a useful model for online learning via SGD, but also allows us to predict the probability of a particular event.

Although SVMs are powerful linear models that can be extended to nonlinear problems via the kernel trick, they have many parameters that have to be tuned in order to make good predictions. In contrast, ensemble methods, such as random forests, don’t require much parameter tuning and don’t overfit as easily as decision trees, which makes them attractive models for many practical problem domains. The KNN classifier offers an alternative approach to classification via lazy learning that allows us to make predictions without any model training, but with a more computationally expensive prediction step.

However, even more important than the choice of an appropriate learning algorithm is the available data in our training dataset. No algorithm will be able to make good predictions without informative and discriminatory features.

In the next chapter, we will discuss important topics regarding the preprocessing of data, feature selection, and dimensionality reduction, which means that we will need to build powerful machine learning models. Later, in Chapter 6, Learning Best Practices for Model Evaluation and Hyperparameter Tuning, we will see how we can evaluate and compare the performance of our models and learn useful tricks to fine-tune the different algorithms.