Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Training Simple Machine Learning Algorithms for Classification

Open in Colab Open in Kaggle

Training Simple Machine Learning Algorithms for Classification

Annotated chapter code — Dr. Brian Jalaian

Package version checks

Add folder to path in order to load from the check_packages.py script:

Check recommended package versions:

[OK] numpy 2.0.2
[OK] matplotlib 3.10.0
[OK] pandas 2.2.2

Chapter 2 - Training Machine Learning Algorithms for Classification

Overview



Artificial neurons - a brief glimpse into the early history of machine learning

<IPython.core.display.Image object>

The formal definition of an artificial neuron

<IPython.core.display.Image object>

The perceptron learning rule

<IPython.core.display.Image object>
<IPython.core.display.Image object>


Implementing a perceptron learning algorithm in Python

An object-oriented perceptron API

This code defines a Python class called Perceptron which implements the perceptron algorithm for binary classification. The class has several methods, including init, fit, net_input, and predict.

The init method is the constructor for the class. It sets the initial values for the learning rate (eta), the number of passes over the training dataset (n_iter), and the random number generator seed for initializing the weights (random_state).

The fit method is used to train the perceptron model. It takes in the training data and target values, and updates the weights and bias unit until convergence or the maximum number of iterations is reached. The number of misclassifications in each iteration is stored in the errors_ list attribute.

The net_input method calculates the dot product of the input data and weights, plus the bias unit.

The predict method takes in input data and returns the predicted class label using the np.where function, which returns 1 if the net input is greater than or equal to 0, and 0 otherwise.

It is worth noting that, this particular implementation is a simple version of the perceptron and it does not account for non-linearly separable datasets, for which more sophisticated linear classifiers like the SVM or Logistic Regression should be used.



Training a perceptron model on the Iris dataset

...

Reading-in the Iris data

From URL: https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data
Loading...

Plotting the Iris data

The code uses the matplotlib and numpy libraries to plot a scatter plot of sepal length and petal length for two classes of iris flower species: Setosa and Versicolor. The data is loaded from a DataFrame df, and the first 100 rows of the data are selected. The y variable is set to be the species column of the data, where ‘Iris-setosa’ is labeled as 0 and ‘Iris-versicolor’ is labeled as 1. The X variable is set to be the sepal length and petal length columns of the data. The code uses the scatter function to plot the data, where Setosa data points are plotted as red circles and Versicolor data points are plotted as blue squares. The x-axis is labeled as ‘Sepal length [cm]’ and the y-axis is labeled as ‘Petal length [cm]’, and a legend is added to the upper left corner of the plot to show the class labels. Finally, the show function is called to display the plot.

<Figure size 640x480 with 1 Axes>


Training the perceptron model

This code creates an instance of the Perceptron class with a learning rate of 0.1 and 10 iterations. The fit method is then called on the instance with the variables X and y as the parameters, where X represents the feature variables and y represents the target variable. The plot method is then used to create a graph with the x-axis representing the number of iterations and the y-axis representing the number of updates (misclassifications) during each iteration. This graph helps to visualize the learning process of the perceptron algorithm and its convergence.

<Figure size 640x480 with 1 Axes>


A function for plotting decision regions

The function plot_decision_regions takes as inputs:

  • X : a 2D array with shape (n_examples, n_features) representing the feature vectors of the input dataset

  • y : a 1D array with shape (n_examples,) representing the target values

  • classifier : the classifier object that has already been fit to the data

  • resolution : a float value that will be used to control the granularity of the grid used to generate the decision regions

The function creates a scatter plot of the input dataset, where each class is represented by a different marker and color, and overlays the decision regions of the classifier on top of it.

The following steps are performed:

  1. Create markers and colors for the different classes

  2. Create a grid of points on the feature space, using the minimum and maximum values of each feature and the specified resolution.

  3. Use the classifier to predict the class of each point on the grid.

  4. Plot the decision regions, using the grid points and their predicted classes.

  5. Plot the input data points, using the markers and colors created in step 1

<Figure size 640x480 with 1 Axes>


Adaptive linear neurons and the convergence of learning

...

Minimizing cost functions with gradient descent

<IPython.core.display.Image object>
<IPython.core.display.Image object>


Implementing an adaptive linear neuron in Python

The AdalineGD class is an implementation of the Adaline algorithm, an adaptive linear neuron. The class has several methods and attributes, including:

  • __init__(self, eta=0.01, n_iter=50, random_state=1): This is the constructor method for the AdalineGD class. It initializes the learning rate (eta), number of iterations (n_iter), and random seed for weight initialization (random_state) with default values of 0.01, 50, and 1 respectively.

  • fit(self, X, y): This method fits the training data (X) and the target values (y) to the model. It initializes the weights (w_) and bias (b_) with random values, and then iterates over the number of iterations specified in the constructor. In each iteration, it calculates the net input, computes the output using the activation function, and computes the error. The weights and bias are then updated based on these errors.

  • net_input(self, X): This method calculates the net input by taking the dot product of the training data (X) and the weights (w_), and adding the bias (b_).

  • activation(self, X): This method computes the linear activation, which is simply the identity function of the net input.

  • predict(self, X): This method returns the class labels after applying the unit step function on the linear activation.

The following code creates two instances of the AdalineGD class, one with a learning rate of 0.1 and the other with a learning rate of 0.0001. Both instances are trained on the feature variables X and the target variable y using the fit method. The first instance is plotted on the left axis of a subplot, with the x-axis representing the number of epochs and the y-axis representing the logarithm of the mean squared error loss function. The second instance is plotted on the right axis of the same subplot, with the x-axis and y-axis representing the same as the first instance but with a linear scale instead of a logarithmic scale. This comparison helps to illustrate the effect of the learning rate on the convergence of the Adaline learning rule.

<Figure size 1000x400 with 2 Axes>


<IPython.core.display.Image object>


Improving gradient descent through feature scaling

<IPython.core.display.Image object>
<Figure size 640x480 with 1 Axes>
<Figure size 640x480 with 1 Axes>


Large scale machine learning and stochastic gradient descent

The AdalineSGD class is an implementation of the Adaptive Linear Neuron (Adaline) algorithm. The Adaline algorithm is an extension of the perceptron algorithm, and is used to train a single-layer neural network to classify linearly separable data.

This implementation of Adaline uses Stochastic Gradient Descent (SGD) to update the weights, instead of batch gradient descent. This means that the weights are updated incrementally for each training example, rather than after evaluating the gradient over the entire training set.

The class has several attributes and methods:

Attributes:

  • eta: the learning rate (between 0.0 and 1.0)

  • n_iter: the number of passes over the training dataset

  • shuffle: whether to shuffle the training data every epoch (to prevent cycles)

  • random_state: the seed for the random number generator used to initialize the weights

  • w_: the weights after fitting

  • b_: the bias unit after fitting

  • losses_: the mean squared error loss function value averaged over all training examples in each epoch

Methods:

  • __init__: Initialize the object with default or user-specified values for the learning rate, number of iterations, and other parameters.

  • fit: Fit the training data to the model.

  • partial_fit: Fit the training data to the model without reinitializing the weights.

  • _shuffle: Shuffle the training data.

  • _initialize_weights: Initialize the weights to small random numbers.

  • _update_weights: Apply the Adaline learning rule to update the weights.

  • net_input: Calculate the net input.

  • activation: Compute linear activation.

  • predict: Return the class label after the unit step.

<Figure size 640x480 with 1 Axes>
<Figure size 640x480 with 1 Axes>
<__main__.AdalineSGD at 0x7a67b26134a0>


Summary

...


Readers may ignore the following cell