Chapter 3 - Traditional Machine Learning (Sample)
Copyright and License
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, without written permission of the copyright owner.
MIT License.
FTC and Amazon Disclaimer
This post/page/article includes Amazon Affiliate links to products. This site receives income if you purchase through these links.
This income helps support content such as this one.
Traditional Machine Learning
In this chapter, I will address some of the traditional machine learning topics. I will use python, numpy, and the Sklearn library to provide example code on how to use the different models and other tools. I will quickly move through KNN to arrive at other algorithms. Much of what we learn from using the SKlearn tool kit can be integrated with PyTorch to make your deep learning code more powerful and modular. That way, you will be able to re-use your code for many different tasks. I will not focus on the theory of traditional machine learning algorithms here. There are many books on the theory of machine learning algorithms so instead I will concentrate on the practical aspects of using them in Python. Machine Learning (ML) is essential to enable automated systems to make decisions and to infer new knowledge about the world. This section describes some of the most important traditional methodologies currently in use in the field of machine learning. Machine learning approaches can be divided into supervised learning (such as Support Vector Machines) and unsupervised learning (such as K-means clustering). Within supervised approaches, the learning methodologies can be divided, based on whether they predict a class or a magnitude, into classification and regression approaches, respectively. An additional categorization for ML methods depends on whether they use sequential or non-sequential data. Classifiers are machine learning approaches that produce as an output a specific class given some input features. Important classifiers include Support Vector Machines (Burges 1998) commonly implemented using LibSVM (Chang and Lin, 2001), Naïve Bayes, artificial neural networks, deep learning based neural networks, decision trees, random forests, and the k-nearest neighbor classifier. Regression models are those that produce a real valued number (magnitude) instead of a class such as the price or square footage of a house, or temperature, etc. Deep learning methods have made a big impact in the field of machine learning in recent years. In their simplest form, deep learning based methods are simply neural networks with more layers between inputs and outputs. In particular, they are very important because, given enough computational power, they can automatically learn the optimal features to be used in a ML model from the raw data. In the past, learning what features to use required using humans to engineer the features. This issue has now been alleviated considerably by deep learning. Additionally, artificial neural networks are models that can handle non-linearly separable data. In theory, this capability allows them to model data that may be more difficult to infer. DL methods have many more capabilities and some of them will be discussed in future chapters.
Code Issues
Before we begin, I want to address some issues about the code. First, I have tried to be consistent with other programmers of machine learning in Python. We will be using many libraries to implement the models. In particular, I selected to use the SKLearn library since it is very powerful and widely use. Especially for pre-processing steps. I only introduce enough SKlearn code for us to know how to integrate it with PyTorch in our deep learning endeavors. For a more in-depth discussion of SKlearn, I highly recommend the book “Python Machine Learning” by Sebastian Raschka. I have tried to be consistent with the conventions used in that book so that both books can be used together. So, now, getting back to the code, here is an example of some of the most important libraries that we can use for our machine learning modeling.- accuracy_score
- recall_score
- f1_score
- precision_score
- confusion_matrix
- coefficient of determination ($ R^2 $)
- RMSE
Object Oriented Programming
Object Oriented Programming (OOP) will be used extensively in this book to implement our ML and deep learning (DL) algorithms. As is necessary with progress, the DL algorithms are more complicated, with deeper and more resource intensive networks. This is best exemplified by one of the newest deep learning algorithms: The Transformer. The NN algorithms are just much more complicated. A little bit too much in fact and some proprietary programming libraries, as a result, are starting to abstract too much of the code. I have found that a simple solution to continue to write from scratch code is to write everything in an object oriented fashion. This way, you are still defining the classes from scratch but you can also build far more complicated algorithms thanks to traditional object oriented programming techniques. The following code segment includes a simple example of an OOP class format we will use extensively throughout this book for defining DL models.Performance Evaluation
As previously stated, performance evaluation depends on whether we are doing classification or regression.Regression Performance Evaluation
The main metrics used to evaluate regression models are:- Coefficient of determination ($ R^2 $)
- RMSE
Classification Performance Evaluation
The main metrics to evaluate classification models are:- accuracy score
- recall score
- f1 score
- precision score
- confusion matrix
Plotting Performance
In the following code segment we can see the function plot_metric_per_epoch() which can be used to plot a metric value every N epochs. For this to work, you store the metric values in a list such as precision_scores_list and then proceed to plot these values using the "matplotlib" library.
Information Theory
Information Theory provides a mathematical framework for quantifying information and uncertainty. Claude Shannon proposed metrics on how to measure the amount of information available (or not available) in a medium or that can be transmitted over a channel. These metrics include: Entropy, the Kullback–Leibler divergence, mutual information, among many others.Entropy
Entropy is an idea in the context of information theory to describe uncertainty. For example, given a very biased coin with both sides having a tail, the probability of getting a head is 0 %. The chance of getting a tail is 100 %. So, we are 100 % sure of the outcome. Entropy, in this case, is 0 given that the uncertainty is 0. On the other hand, if we have a fair coin where both head and tail are equally likely; then, the uncertainty in this outcome is the highest. The formula for Entropy is as follows: \[ entropy = \sum -p \cdot ln(p ) \] You add or sum over all possible outcomes and "p" is the probability of each outcome. In the next graph, we plot the Entropy of a head for a fair coin given the probability of head.
Kullback-Leibler (KL) divergence
The Kullback-Leibler (KL) divergence metric from information theory is designed to measure the difference between 2 distributions (P and Q). The formula for the Kullback-Leibler (KL) divergence is as follows: $ D_{KL} ( p(x) || q(x) ) = \sum p(x) \cdot ln \frac{p(x)}{q(x)} $ A simple example of how to use the KL divergence can be seen in the next code listing.Mutual Information
Mutual Information (MI) is a metric that can be used to measure the relationship between one variable and another variable. In ML this can be used to measure the importance of features when predicting labels. For instance, we can use it to measure how much information we can get about one variable (labels) from another variable (features). We can see this with examples. In the next section I will contrast 2 cases (examples). I will create a data set that is 7x3 for "X", and 7x1 for "y". We will use MI to look at the importance of features when predicting the labels. In each of the 2 cases (example 1 and example 2), we will look at the MI between each feature and the labels. The higher the MI, the more related the features are to the labels.Information Gain
Information Gain can be a useful metric in cyber security. It can help us to compare the entropy in 2 probability distributions. Let us consider a simple example. Assume you have 4 threats with associated probabilities. We are considering purchasing a new AI based security appliance. We have estimated the probabilities of the threat before and after purchasing the security appliance. We use Information Gain to begin to evaluate our outcomes. The example is presented in the following code listing:Conditional Entropy
Conditional Entropy (CE), like mutual information (MI), can be used to compare the relationship between variables (c and f). In fact, you can consider that MI(f, c) is related to entropy(c) minus CE(c|f). Conditional Entropy tells you how much surprise is left in "c" given that you know "f". This is best understood with 3 examples.Optimization
Before we begin to discuss some of the machine learning algorithms, I should also say something about optimization. Optimization is a key process in machine learning. Basically, any supervised learning algorithm needs to learn a prediction equation given a set of annotated data. This prediction function usually has a set of parameters that must be learned. However, the question is “how do you learn these parameters?” The answer is that you do so through: Optimization. In its simplest form, optimization consists of trying many sets of parameters with your model and seeing what result they give you. If the result is not good, the optimization algorithm needs to decide if you should decrease the values of the parameters or increase the values of the parameters. In general, you do this in a loop (increasing and decreasing the parameter values) until you find an optimal set of parameters. But one of the questions to answer here as you are looping is: \textbf{do the values go up or down in this iteration?} Well, as it turns out, there are methodologies based on calculus that help you to make this decision. Let us try to picture this with a graph (below).
Anomaly Detection Algorithms
Perhaps the first set of machine learning algorithms to discuss in a "Cyber Security and Machine Learning" book is the set of algorithms related to Anomaly Detection. There are no machine learning algorithms exclusively for cyber security. Instead, there are many machine learning algorithms that can be applied to cyber security. Anomaly detection algorithms, as the name implies, seem to correlate well with cyber security problems. So what is special about an anomaly detection algorithm? Essentially, I would say that the key characteristic is that you do not need labels for the data samples. Usually in machine learning you have "X" and "y". Where "X" is the data of samples with features, and "y" includes the labels. Anomaly detection algorithms do not have associated labels. They are unsupervised. In this case, the machine learning model must learn what the data looks like. Once trained, the model can be used to compare new test samples to the learned distribution and determine if the test sample is similar or anomalous. There are several algorithms that can fit in this category. Some of them include: Hopfield networks (\cite{hopfield1982Ref}), Boltzman Machines (\cite{hinton1985Ref}), clustering, auto-encoders, etc. Clustering will be covered in the next sections in the context of KNN. Auto-encoders will be covered after deep learning is introduced in the next chapters. Throughout this book I will provide examples of how to use these for cyber security problems.Hopfield Networks
Hopfield Networks (\cite{hopfield1982Ref}) are sometimes called associative memory networks. John Hopfield won the 2024 nobel prize in physics for this work. They can be related to Information Theory because they can be used to store and re-construct (retrieve) information. The number of neurons can determine the amount of information that can be stored in the model. Hopfield Networks use the "outer product" multiplication to calculate the weights matrix. The "outer product" is an operation in linear algebra which, given 2 vectors, can return a matrix. The "outer product" operation can be seen in the next example: \[ \begin{bmatrix} u_1 \\ u_2 \\ u_3 \\ \end{bmatrix} \begin{bmatrix} v_1 & v_2 & v_3 & v_4 \\ \end{bmatrix} = \begin{bmatrix} u_1 v_1 & u_1 v_2 & u_1 v_3 & u_1 v_4 \\ u_2 v_1 & u_2 v_2 & u_2 v_3 & u_2 v_4 \\ u_3 v_1 & u_3 v_2 & u_3 v_3 & u_3 v_4 \\ \end{bmatrix} \] The weights are calculated via an "outer product" of the input vector and the transpose of the same vector. The identity matrix is subtracted from the resulting matrix as can be seen in the following formulation. \[ W = v \times v^T - I \] The weights are calculated using the "outer product" of the input vector and the transpose of the same vector. The outer product itself is simply $$ W' = vv^T $$ or, for each element, $$ w'_{ij} = v_i v_j. $$ In a Hopfield network, neurons are not connected to themselves. Therefore, the diagonal elements of the final weight matrix must be set to zero. For bipolar input vectors, where $$ v_i \in \{-1,1\} $$ the diagonal elements produced by the outer product are all equal to one since $$ v_i^2=1 $$ These self-connections can therefore be removed by subtracting the identity matrix: $$ W = vv^T - I $$ Equivalently, each individual Hopfield weight can be written as $$ w_{ij} = v_i v_j - \delta_{ij} $$ where \(\delta_{ij}\) is the Kronecker delta, defined as $$ \delta_{ij} = \begin{cases} 1, & i=j \\ 0, & i\neq j. \end{cases} $$ For example, consider the bipolar input vector $$ v = \begin{bmatrix} 1\\ -1\\ 1 \end{bmatrix}. $$ First, the outer product is calculated: $$ vv^T = \begin{bmatrix} 1\\ -1\\ 1 \end{bmatrix} \begin{bmatrix} 1 & -1 & 1 \end{bmatrix} = \begin{bmatrix} 1 & -1 & 1\\ -1 & 1 & -1\\ 1 & -1 & 1 \end{bmatrix}. $$ The Hopfield algorithm then removes the self-connections by subtracting the identity matrix: $$ W = vv^T-I = \begin{bmatrix} 1 & -1 & 1\\ -1 & 1 & -1\\ 1 & -1 & 1 \end{bmatrix} - \begin{bmatrix} 1 & 0 & 0\\ 0 & 1 & 0\\ 0 & 0 & 1 \end{bmatrix} = \begin{bmatrix} 0 & -1 & 1\\ -1 & 0 & -1\\ 1 & -1 & 0 \end{bmatrix}. $$ Notice that the outer product creates the initial matrix of pairwise relationships, while subtracting the identity matrix is a Hopfield-specific step used to eliminate the self-connections. Here are some important points to note about Hopfield networks and the code:- np.outer produces one product between each possible element pairing from two vectors
- np.outer is used to calculate the "outer product"
- The outer product captures pairwise relationships between the features of a sample
- During training, these pairwise relationships are accumulated across the normal samples and stored in the weights matrix
- The Hopfield network can therefore be thought of as an associative memory of the normal patterns
- A new sample can be reconstructed using this stored memory and compared with its reconstructed version
- A large Hamming distance between the original and reconstructed samples may indicate an anomaly
- The Hebbian learning rule can be used for training
- Neurons: 6 Storage Capacity: 1.67
- Neurons: 100 Storage Capacity: 10.86
- Neurons: 1000 Storage Capacity: 72.38
- Neurons: 10000 Storage Capacity: 542.87
Boltzman Machines
Boltzman Machines (\cite{hinton1985Ref}) build on the idea of Hopfield networks and can be used to discover properties in data or anomalies. Geoffrey Hinton won the 2024 nobel prize in physics for this work. I will cover Restricted Boltzman Machines (RBMs) in this book, but not in this chapter. The reason for this is that RBMs are based on neural networks. Therefore, I will cover them in the network security chapter after I have introduced many concepts related to neural networks.Popular Supervised Learning Algorithms
In this section, I will discuss some traditional and popular supervised learning algorithms. These are the ones that learn to correlate data to labels.KNN
The k-nearest neighbor (KNN) classifier is a popular algorithm that I always like to use. It requires very little parameter tuning and can be easily implemented. Here, the KNN code is implemented in pure Numpy because of its simplicity. In this case, the \textbf{k} closest samples are selected. In the next code listings, you can see all the code needed to run KNN. Wow! Pretty short right? This code splits our data into \textbf{train} and \textbf{test} sets. Then grabs every sample in the test set and compares it to every sample in the train set. For each test sample, we get all distances between the test sample and all train samples. We then rank the distances and select the closest \textbf{K} distances. Finally, we assign the majority class associated with the closest 5 distances. That is it! Let us get started. First the libraries.
Logistic Regression
Logistic regression is a simple algorithm that is often used by practitioners of machine learning because it can obtain good results. Logistic regression is a linear function much like linear regression which predicts the probability of a sample belonging to a given class. Logistic regression uses another optimization function instead of the standard least squares cost function used in linear regression.Neural Networks
Neural networks can be very complex models that take a long time to train. Therefore, the use of them in SKlearn may not be recommended except for the smallest of data sets. The code is shown here for contrast purposes with later implementations of neural networks in PyTorch. In the next chapters, we will focus on how to do this in PyTorch and how to create networks of multiple layers from scratch. In the code below we can see that everything is very similar to the previous logistic regression implementation. The new changes appear in the definition of the \textbf{clf} multilayer object. Here, the parameter \textbf{hidden\_layer\_sizes}=(100,100) means that the architecture of the network consists of 2 hidden layers with 100 neurons each. A parameter such as (200, ) would mean that the network has 1 hidden layer with 200 neurons.Regression, Trees, and XGBoost
There are several ML approaches to fit models to regression data. Three important ones are linear regression, regression trees, and neural networks. The next sections discuss regression and regression trees leading up to XGBoost. A more detailed discussion of regression will be covered later in the book.Regression Trees
Regression trees (Torgo 2017) can fit nonlinear regression data. Regression trees are a type of decision tree in which the predicted values are not discrete classes but instead are real valued numbers. The key concept here is to use the features from the samples to build a tree. The nodes in the tree are decision points leading to leaves. The leaves contain values that are used to determine the final predicted regression value.XGBoost
The "XGBoost" technique represents an improvement over other regression techniques like gradient boosting. XGBoost has new algorithms and approaches for generating the regression tree. It also has several optimizations that improve the speed and performance by which it can learn and process data. As of 2023, XGBoost can outperform many ML techniques including neural networks for small tabular data. XGBoost is also very easy to use and I would recommend always trying it with your tabular cyber security data. A usage example of XGBoost can be seen in the next code listing.Summary
This chapter provided an overview of some of the main traditional topics in machine learning. In particular, the following machine learning algorithms were presented: anomaly detection, logistic regression, KNN, and neural networks. Code examples of their implementation using the sklearn toolkit or Numpy were presented and discussed. Additionally, issues related to classifier performance and information theory were also addressed. The next chapter will focus on issues related to data and data pre-processing that apply to "cyber security and machine learning".Code Examples
Notes
Hopfield Networks
- Code Example: https://github.com/rcalix1/CyberSecurityAndMachineLearning/blob/main/FirstEdition/Ch3_TraditionalML/HopfieldNetworks.ipynb
Hopfield Networks
- We discussed the perceptron. Now it is time to connect multiple neurons together
- we now make the output of one neuron into the input to another neuron
- and this allows us to create neural networks
- Neural Nets can be of 2 types:
- a) Feedforward Nets (all in one direction - directed acyclic graph)
- b) Feedback nets (if not feedforward, then a network is a feed back net)
- This classification depends on their connectivity
- they have been used to study associative memory. Memory can be used for anomaly detection, for instance
Hebbian Training
- Hopfield Networks are sometimes called associative memory networks.
- John Hopfield won the 2024 nobel prize in physics for this work.
- They can be related to Information Theory because they can be used to store and re-construct (retrieve) information.
- The number of neurons can determine the amount of information that can be stored in the model.
- Hopfield Networks use the "outer product" multiplication to calculate the weights matrix.
- The "outer product" is an operation in linear algebra which, given 2 vectors, can return a matrix.
- The "outer product" operation can be seen in the next example:
- The weights are calculated via an "outer product" of the input vector and the transpose of the same vector.
- The identity matrix is subtracted from the resulting matrix as can be seen in the following formulation.
- np.outer produces one product between each possible element pairing from 2 tensors
- np.outer is used for the "outer product"
- The intuition is like a pairwise distance matrix
- This can help us to find the distance between each pair of point values
