Overview:

This document provides a comprehensive guide to implementing Machine Learning and Deep Learning workflows using Python libraries like Scikit-learn and PyTorch. It contrasts traditional programming with machine learning, detailing how algorithms autonomously discover patterns from structured data represented by features and targets. Furthermore, it breaks down the core paradigms of supervised learning and unsupervised learning, covering classification, regression, clustering, and Principal Component Analysis for dimensionality reduction. The text also outlines the standard machine learning pipeline, moving logically from raw data ingestion and preparation to model building, evaluation, and real-world deployment. Finally, it demonstrates a practical application by building, training, and evaluating a neural network to classify flower species using the classic Iris dataset.

What Is Machine Learning?

Machine Learning (ML) is a branch of Artificial Intelligence (AI) focused on developing computational systems that learn patterns and relationships from data and improve performance through experience.

Unlike traditional programming, where developers explicitly define the rules to solve a problem, machine learning gives algorithms mechanisms to discover those rules from data. The fundamental distinction is between programming a computer to perform a specific task and programming a computer to learn how to perform that task.

Traditional Programming vs Machine Learning

In traditional programming, a computational system takes rules and input data to produce an output. In machine learning, a learning algorithm uses input data and, in supervised learning, known outputs to construct a model that captures the underlying relationships.

Aspect Traditional Programming Machine Learning
Rules Explicitly programmed Learned from data
Logic Developer-defined Model-derived
Adaptability Requires code changes Can improve through retraining
Output Rule-based computation Model-based prediction
Knowledge Encoded in instructions Encoded in model parameters

Representation of Data

Machine learning requires a structured representation of the information a system learns from.

A tabular dataset typically consists of rows and columns.

  • Instances (Samples): Individual observations represented by rows.
  • Features: Attributes or characteristics represented by columns.
  • Input Features: Variables supplied to the learning algorithm.
  • Target: The dependent variable that the model attempts to predict.

For example, load the Iris dataset:

from sklearn.datasets import load_iris
irisData = load_iris()
print(irisData.DESCR)
.. _iris_dataset:

Iris plants dataset
--------------------

**Data Set Characteristics:**

:Number of Instances: 150 (50 in each of three classes)
:Number of Attributes: 4 numeric, predictive attributes and the class
:Attribute Information:
    - sepal length in cm
    - sepal width in cm
    - petal length in cm
    - petal width in cm
    - class:
            - Iris-Setosa
            - Iris-Versicolour
            - Iris-Virginica

:Summary Statistics:

============== ==== ==== ======= ===== ====================
                Min  Max   Mean    SD   Class Correlation
============== ==== ==== ======= ===== ====================
sepal length:   4.3  7.9   5.84   0.83    0.7826
sepal width:    2.0  4.4   3.05   0.43   -0.4194
petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)
============== ==== ==== ======= ===== ====================

:Missing Attribute Values: None
:Class Distribution: 33.3% for each of 3 classes.
:Creator: R.A. Fisher
:Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
:Date: July, 1988

The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken
from Fisher's paper. Note that it's the same as in R, but not as in the UCI
Machine Learning Repository, which has two wrong data points.

This is perhaps the best known database to be found in the
pattern recognition literature.  Fisher's paper is a classic in the field and
is referenced frequently to this day.  (See Duda & Hart, for example.)  The
data set contains 3 classes of 50 instances each, where each class refers to a
type of iris plant.  One class is linearly separable from the other 2; the
latter are NOT linearly separable from each other.

.. dropdown:: References

  - Fisher, R.A. "The use of multiple measurements in taxonomic problems"
    Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to
    Mathematical Statistics" (John Wiley, NY, 1950).
  - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.
    (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.
  - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
    Structure and Classification Rule for Recognition in Partially Exposed
    Environments".  IEEE Transactions on Pattern Analysis and Machine
    Intelligence, Vol. PAMI-2, No. 1, 67-71.
  - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactions
    on Information Theory, May 1972, 431-433.
  - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS II
    conceptual clustering system finds 3 classes in the data.
  - Many, many more ...

Structure of a Machine Learning Dataset

A dataset is typically represented as a two-dimensional matrix, where each row represents an observation and each column represents a feature.

The feature matrix is conventionally denoted by $X$:

\[X \in \mathbb{R}^{n \times d}\]

where:

  • $n$ is the number of observations.
  • $d$ is the number of features.

In supervised learning, the target variable is represented by $y$:

\[y = (y_1, y_2, \ldots, y_n)\]

The objective of supervised learning is to approximate a function that maps input features to corresponding target values:

\[f: X \rightarrow y\]
irisData.keys()
dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename', 'data_module'])

sepal and Petal

There are 150 iris flowers in the dataset, with the colour indicating their respective type (Setosa, Versicolour, and Virginica).

irisData['feature_names']
['sepal length (cm)',
 'sepal width (cm)',
 'petal length (cm)',
 'petal width (cm)']

Here the example corresponding valudes for the above features1

irisData['data'][0]
array([5.1, 3.5, 1.4, 0.2])
import pandas as pd
iris_df = pd.DataFrame(irisData.data,
                       columns = irisData.feature_names)
iris_df['target'] = irisData.target
iris_df.head()
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target
0 5.1 3.5 1.4 0.2 0
1 4.9 3.0 1.4 0.2 0
2 4.7 3.2 1.3 0.2 0
3 4.6 3.1 1.5 0.2 0
4 5.0 3.6 1.4 0.2 0

Features and Target Variables

Features are independent variables that describe the characteristics of observations. The target is the dependent variable that the machine learning model attempts to predict.

iris_df.target.value_counts()
target
0    50
1    50
2    50
Name: count, dtype: int64

Dataset Representation in Scikit-learn

Scikit-learn commonly represents built-in datasets using a dictionary-like object called Bunch.

Typical attributes include:

Attribute Description
data Feature matrix
target Target values
feature_names Names of input features
target_names Names of target classes, when available
DESCR Dataset description

The feature matrix and target vector are separated before training a supervised learning model.

Exploratory Data Analysis (EDA)

Exploratory Data Analysis is the process of understanding the structure, characteristics and statistical properties of a dataset before constructing a machine learning model.

Important activities include:

  • Examining dataset dimensions and data types.
  • Identifying missing values and duplicate observations.
  • Understanding feature distributions.
  • Calculating descriptive statistics.
  • Identifying correlations between features.
  • Examining the distribution of target classes.
  • Detecting outliers and potential data quality issues.

Data Visualisation

Visualisation helps identify patterns and relationships that may not be immediately apparent from numerical representations.

Visualisation Purpose
Histogram Examine feature distributions
Scatter plot Identify relationships between two features
Box plot Detect outliers and statistical dispersion
Pair plot Explore pairwise feature relationships
Heatmap Visualise feature correlations
Count plot Examine class distributions

In classification problems, visualisation can also help determine whether different classes are separable in the feature space.

sns.pairplot(iris_df, hue='target', height=1.2)
<seaborn.axisgrid.PairGrid at 0x752331d0b920>

png

Feature Space

Each observation can be represented as a point in a multidimensional feature space:

\[\mathbf{x}_i = (x_{i1}, x_{i2}, \ldots, x_{id})\]

Machine learning algorithms identify patterns, similarities, and decision boundaries within this space.

When classes are well separated, classification may be relatively straightforward. Overlapping classes may require more sophisticated algorithms, feature engineering or nonlinear decision boundaries.

Preparing Data for Machine Learning

Before model training, the dataset may require several preprocessing operations:

  1. Data cleaning.
  2. Missing value imputation.
  3. Categorical variable encoding.
  4. Feature scaling and normalisation.
  5. Feature selection or dimensionality reduction.
  6. Training and testing dataset separation.

Preprocessing transformations that learn from data must be fitted only on the training dataset to prevent data leakage.

A supervised learning dataset can be represented mathematically as:

\[D = \{(\mathbf{x}_i, y_i)\}_{i=1}^{n}\]

where:

  • $D$ is the dataset.
  • $n$ is the number of observations.
  • $\mathbf{x}_i$ is the input feature vector.
  • $y_i$ is the corresponding target value.

Each feature vector contains $d$ input features:

\[\mathbf{x}_i = (x_{i1}, x_{i2}, \ldots, x_{id})\]

The complete input dataset can be represented as a feature matrix:

\[X = \begin{bmatrix} x_{11} & x_{12} & \cdots & x_{1d} \\ x_{21} & x_{22} & \cdots & x_{2d} \\ \vdots & \vdots & \ddots & \vdots \\ x_{n1} & x_{n2} & \cdots & x_{nd} \end{bmatrix}\]

The corresponding target vector is:

\[\mathbf{y} = (y_1, y_2, \ldots, y_n)^T\]

Fundamental Components of Machine Learning

A machine learning system consists of three fundamental components.

  1. Model Representation Model representation defines the mathematical structure of the learning system, including its parameters and the relationships it is capable of expressing. The choice of representation determines the hypothesis space within which the learning algorithm searches for a solution.

  2. Prediction Mechanism The prediction mechanism defines how input features interact with model parameters to generate an output.

\[\hat{y} = f_{\theta}(\mathbf{x})\]

Different model representations employ different mathematical operations to transform inputs into predictions.

  1. Learning Algorithm The learning algorithm determines how model parameters are estimated or adjusted using the available training data. In many machine learning systems, this involves minimising an objective function that measures the difference between predicted and actual outputs.
\[\theta^* = \arg\min_{\theta} \frac{1}{n} \sum_{i=1}^{n} L(y_i, f_{\theta}(\mathbf{x}_i))\]

where:

  • $L$ is the loss function.
  • $\theta^*$ represents the optimal parameters under the objective.
  • $y_i$ is the actual target.
  • $f_{\theta}(\mathbf{x}_i)$ is the predicted target.

The learning process searches for parameter values that minimise prediction errors according to the selected objective function.

Types of Machine Learning

The nature of machine learning approaches can be distinguished by their training data and expected outputs.

  1. Supervised Learning: Supervised learning uses datasets containing both input features and corresponding target values.

    The objective is to learn a function that predicts the target from the input features. Supervised learning is primarily divided into two categories: classification and regression.

    Classification: Classification predicts discrete categorical outputs.

    \[f_{\theta}: \mathcal{X} \rightarrow \{c_1,c_2,\ldots,c_k\}\]

    where $k$ represents the number of possible classes.

    Classification problems can be further categorised into:

    • Binary classification
    • Multiclass classification
    • Multilabel classification

    The objective is to assign appropriate class labels to previously. unseen observations.

    Regression: Regression is concerned with predicting numerical quantities, typically continuous values.

    \[f_{\theta}: \mathcal{X} \rightarrow \mathbb{R}\]

    The objective is to estimate the quantitative relationship between input features and a numerical target.

  2. Unsupervised Learning: Unsupervised learning operates on datasets without explicitly defined target values.

    \[D = \{\mathbf{x}_i\}_{i=1}^{n}\]

    Rather than learning a relationship between inputs and known outputs, unsupervised learning discovers intrinsic patterns, relationships and structures within the input data.

    Clustering: Clustering is an unsupervised learning technique that partitions or groups observations according to their similarities or underlying characteristics.

    The objective is to discover meaningful structures within the dataset without relying on predefined target labels.

Comparison of Learning Approaches

Characteristic Classification Regression Clustering
Learning paradigm Supervised Supervised Unsupervised
Target required Yes Yes No
Output Discrete categories Numerical values Groups
Primary objective Predict classes Predict quantities Discover structures
Training data Labelled Labelled Unlabelled

Conceptual Architecture:

flowchart TD
    A[Machine Learning] --> B[Supervised Learning]
    A --> C[Unsupervised Learning]

    B --> D[Classification]
    B --> E[Regression]
    C --> F[Clustering]

    D --> G[Discrete]
    E --> H[Numerical]
    F --> I[Groups]

For example, you can analyse the Iris dataset with Pandas:

Machine Learning with Scikit-learn

Scikit-learn is a Python machine learning library that provides a consistent framework for developing, training, evaluating, and deploying machine learning models. It integrates with NumPy, Pandas, SciPy, and Matplotlib to support the machine learning workflow.

import sklearn
sklearn.__version__
'1.9.0'

The above version is in use.

Scikit-learn Machine Learning Map

The diagram2 is an interactive3 flowchart that helps users select the right machine learning estimator (algorithm) based on their dataset and problem type.

How to Use the Flowchart

  • Navigation: You can click any estimator in the chart to view its documentation, zoom using the scroll wheel, pan by clicking and dragging, or download the chart directly3.
  • “Try Next” Arrows: Orange arrows indicate fallback options—if the initial recommended estimator doesn’t yield the desired results, follow the arrow to the next suggested algorithm.

Algorithm Paths by Problem Type

The flowchart starts by checking if you have more than 50 samples (if not, it advises getting more data) and then branches into four main categories:

  • Classification (Predicting a category with labeled data)
    • Less than 100K samples: Starts with Linear SVC. If that fails and you have text data, try Naive Bayes; otherwise, try KNeighbors Classifier, followed by SVC or Ensemble Classifiers.
    • 100K samples or more: Starts with SGD Classifier, falling back to Kernel Approximation.
  • Clustering (Predicting a category without labeled data)
    • Number of categories is known: Uses KMeans (for less than 10K samples, with Spectral Clustering or GMM as backups) or MiniBatch KMeans (for 10K samples or more).
    • Number of categories is unknown: Uses MeanShift or VBGMM (for less than 10K samples).
  • Regression (Predicting a quantity)
    • Less than 100K samples: If only a few features should be important, use Lasso or ElasticNet. Otherwise, start with RidgeRegression or SVR (kernel=”linear”), and fall back to SVR (kernel=”rbf”) or Ensemble Regressors.
    • 100K samples or more: Uses SGD Regressor.
  • Dimensionality Reduction (Just looking / simplifying data structure)
    • Starts with Randomized PCA. If more is needed, it branches by sample size: Isomap or Spectral Embedding (with LLE as a backup) for less than 10K samples, or Kernel Approximation for 10K samples or more.

Classification

Classification is a supervised learning technique used to predict discrete categorical outcomes. A classification model learns the relationship between input features and predefined class labels from labelled training data.

Common classification algorithms include:

  • Logistic Regression
  • Decision Trees
  • Random Forests
  • Support Vector Machines (SVM)
  • K-Nearest Neighbours (KNN)
  • Naive Bayes

Classification models are commonly evaluated using accuracy, precision, recall, F1-score, and confusion matrices.

Regression

Regression is a supervised learning technique used to predict continuous numerical values. The objective is to learn a mathematical relationship between independent input variables and a dependent target variable.

Common regression algorithms include:

  • Linear Regression
  • Polynomial Regression
  • Ridge Regression
  • Lasso Regression
  • Random Forest Regression

Regression models are commonly evaluated using Mean Absolute Error (MAE), Mean Squared Error (MSE), Root Mean Squared Error (RMSE), and the coefficient of determination (R²).

Clustering

Clustering is an unsupervised learning technique that identifies groups of similar observations within an unlabelled dataset. Unlike supervised learning, clustering does not require predefined target variables.

Common clustering algorithms include:

  • K-Means Clustering
  • Hierarchical Clustering
  • DBSCAN
  • Gaussian Mixture Models

Clustering helps discover hidden structures, relationships, and patterns within data.

Principal Component Analysis (PCA)

Principal Component Analysis (PCA) is an unsupervised machine learning technique used for dimensionality reduction while preserving as much variance in the original data as possible.

PCA transforms a set of potentially correlated features into a smaller set of linearly uncorrelated variables called principal components.

The principal components are ordered according to the amount of variance they capture:

  • The first principal component (PC1) captures the maximum possible variance in the dataset.
  • The second principal component (PC2) captures the maximum remaining variance and is orthogonal to PC1.
  • Subsequent components follow the same principle.

Mathematical Foundation

Given a centred data matrix $X \in \mathbb{R}^{n \times d}$, PCA projects the original data into a lower-dimensional space:

\[Z = XW\]

where:

  • $X$ is the centred input data matrix.
  • $W$ is the matrix of selected principal component directions.
  • $Z$ is the transformed, lower-dimensional representation.
  • $n$ is the number of observations.
  • $d$ is the number of original features.

PCA can be computed using eigendecomposition (a mathematical technique that decomposes a square matrix into its eigenvalues and eigenvectors) of the covariance matrix or Singular Value Decomposition(SVD).

Applications of PCA

  • Dimensionality reduction
  • Feature extraction
  • Data visualisation
  • Reducing multicollinearity
  • Noise reduction
  • Improving computational efficiency
  • Preprocessing for other machine learning algorithms

Limitations:

PCA captures linear relationships and is sensitive to feature scales. Standardisation is often necessary when features have different units or magnitudes. Furthermore, principal components may be difficult to interpret because they represent linear combinations of the original features. High variance does not necessarily imply high predictive importance.

Supporting Python Libraries

Scikit-learn operates within a broader Python scientific computing ecosystem:

Library Responsibility
NumPy Numerical computation and multidimensional arrays
Pandas Data manipulation and preparation
SciPy Scientific computing and optimisation
Matplotlib Data visualisation
Seaborn Statistical visualisation
Scikit-learn Machine learning and model evaluation

A Unified Machine Learning Interface

Scikit-learn provides a consistent application programming interface across different machine learning algorithms.

  • fit() — learns model parameters from training data.
  • predict() — generates predictions using a trained model.
  • transform() — transforms data into another representation.
  • fit_transform() — learns transformation parameters and transforms the data.
  • score() — evaluates model performance using the estimator’s default evaluation metric.

This consistent interface simplifies experimentation, algorithm selection, preprocessing, and the development of reproducible machine learning pipelines.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

Machine Learning Pipeline

A machine learning pipeline is a structured sequence of operations that transforms raw data into a trained model capable of making predictions in real-world applications.

The pipeline consists of six fundamental stages.

Machine Learning Pipeline 1. Data Ingestion 2. Data Preparation 3. Model Building 4. Training 5. Evaluation 6. Deployment Collect raw data Clean and transform Define architecture Learn from data Test and debug Real-world inference
  1. Data Ingestion: Data ingestion involves collecting raw data from its sources and organising it into a format that can be processed efficiently by the machine learning framework. Real-world data frequently contains quality issues, including:

    • Inconsistent data formats.
    • Missing values.
    • Invalid measurements.
    • Unrealistic values.

    Identifying these problems is an important part of understanding the input data before model development begins.

  2. Data Preparation: Data preparation transforms raw information into a representation suitable for machine learning. The main operations include:
    • Data cleaning: correcting errors and removing invalid records.
    • Deduplication: eliminating duplicate observations.
    • Missing value handling: addressing incomplete records.
    • Data transformation: converting data into consistent, usable formats.
    • Feature engineering: deriving meaningful input variables from existing information.

    Data preparation often consumes a substantial proportion of the development time in machine learning projects.

    The quality of the training data directly influences the quality of the resulting model. Even a well-designed neural network may perform poorly when trained on unreliable data.

  3. Model Building: Model building involves selecting and defining a neural network architecture appropriate for the problem being solved.

    The architecture determines:

    • The number of neurons.
    • How neurons are connected.
    • The types of layers used in the network.

    A model may consist of a single neuron that learns a relationship between an input and an output, or a more complex architecture containing multiple interconnected layers.

    PyTorch provides a consistent approach to defining both simple and complex neural network architectures.

  4. Model Training: Training is the process through which a model learns patterns from historical data.

    During training, the model receives input data together with its expected outputs. It makes predictions, measures prediction errors, and progressively adjusts its learnable parameters to improve its performance.

    The training process requires three fundamental components:

    Component Purpose
    Loss function Measures prediction errors.
    Optimizer Guides the adjustment of model parameters.
    Learning rate Controls the magnitude of parameter updates.

    These components operate within a training loop.

    Model Training Loop Input Data Neural Network Prediction Loss Function Optimizer Expected Output Ground Truth Update parameters Repeat to improve predictions

    The training loop repeatedly performs the following operations:

    1. Supply input data to the model.
    2. Generate predictions.
    3. Compare predictions with expected outputs.
    4. Calculate prediction errors using a loss function.
    5. Update model parameters using an optimiser.
    6. Repeat the process.

    The objective is to progressively reduce prediction errors and improve the model’s ability to learn meaningful relationships from data.

  5. Model Evaluation and Debugging: Successful training does not necessarily mean that a model can make reliable predictions on new data.

    Model evaluation measures performance using a test dataset that was excluded from the training process.

    The evaluation process determines:

    • How accurately the model predicts unseen observations.
    • How frequently prediction errors occur.
    • The magnitude of prediction errors.
    • Whether the model is sufficiently reliable for its intended application.

    Debugging involves identifying and investigating problems when model predictions do not meet expectations.

    The fundamental objective of evaluation is to determine whether the model can generalise beyond its training data.

  6. Model Deployment: Deployment is the final stage of the machine learning pipeline.

    It involves making the trained and evaluated model available for practical use, allowing it to receive new inputs and generate predictions in real-world applications.

    Deployment follows successful model training and evaluation.

Deep Learning with Python

Deep learning is a subset of machine learning that uses neural networks to learn patterns and relationships from data. Instead of explicitly programming rules, a neural network learns from examples and develops the ability to make predictions on unseen data.

Python provides frameworks such as PyTorch for building, training, and evaluating neural networks. Whether developing a simple single-neuron model or a complex neural network, the underlying machine learning workflow follows a common structure known as the Machine Learning Pipeline.

The Building Blocks of Neural Networks

A neural network consists of interconnected computational units called neurons. Although inspired by biological neurons, artificial neurons are mathematical units with adjustable parameters that learn patterns from data.

Understanding the behaviour of a single neuron provides the foundation for understanding more complex neural network architectures.

Single Neuron

In its simplest form, a neuron represents a linear equation with two adjustable parameters: a weight and a bias.

\[\hat{y} = wx + b\]

Where:

  • $x$: Input feature.
  • $w$: Weight associated with the input.
  • $b$: Bias.
  • $\hat{y}$: Predicted output.

The weight determines the slope of the line, while the bias determines its vertical intercept.

x Weight (w) wx + b Bias (b) ŷ Input Neuron Prediction

Figure: Computational structure of a single linear neuron.

The objective of learning is to determine the values of $w$ and $b$ that produce the best-fitting line for the observed data.

In PyTorch, these adjustable values are referred to as model parameters.

How a Neuron Learns

A neuron learns by progressively reducing the difference between its predictions and the actual observations.

The learning process consists of the following steps:

  1. Initialisation: Start with initial values for the weight and bias.
  2. Prediction: Calculate the predicted output using the current parameters.
  3. Error measurement: Compare the predicted output with the actual value.
  4. Calculate adjustment: Use calculus to determine how changes to the parameters affect the error.
  5. Update parameters: Adjust the weight and bias slightly in the direction that reduces the error.
  6. Repeat: Continue the process until the parameters approach an optimal solution.

For an individual observation, the prediction error can be expressed as:

\[e = y - \hat{y}\]

Substituting the prediction equation:

\[e = y - (wx + b)\]

Where $y$ represents the actual observed value.

The model considers the errors across its observations when determining how to adjust its parameters.

Initialise weight and bias Generate prediction Measure prediction error Calculate adjustment Update weight and bias Repeat

Figure: Iterative learning through parameter adjustment and error reduction.

This process may be repeated hundreds or thousands of times to obtain parameters that closely represent the underlying relationship in the data.

Neuron with Multiple Inputs

A neuron is not restricted to a single input. It can process multiple input features by assigning a separate weight to each feature while maintaining a single bias.

For three input features:

\[\hat{y} = w_1x_1 + w_2x_2 + w_3x_3 + b\]

For $n$ input features, the generalised equation is:

\[\hat{y} = \sum_{i=1}^{n} w_i x_i + b\]

Alternatively, using vector notation:

\[\hat{y} = \mathbf{w}^{T}\mathbf{x} + b\]

Each weight determines the contribution of its corresponding input feature to the prediction.

x₁ x₂ x₃ w₁ w₂ w₃ Σ + b b ŷ Inputs Weighted sum + bias Output

Figure: A neuron combining multiple weighted input features and a bias.

Regardless of the number of inputs, the underlying weighted-sum computation remains the same.

From Neurons to Neural Networks

A neural network is constructed by connecting multiple neurons together and organising them into layers.

A layer is a collection of neurons that receive the same set of inputs. The outputs of one layer become the inputs of the subsequent layer.

A typical neural network consists of three types of layers:

Layer Description
Input layer Receives the raw input features.
Hidden layers Perform intermediate computations using learned weights and biases.
Output layer Produces the final prediction.
Input Hidden 1 Hidden 2 Output x₁ x₂ x₃ Σ Σ Σ Σ Σ Σ Σ ŷ Features Intermediate representations Prediction

Figure: Neural network with an input layer, two hidden layers and an output layer.

Hidden layers are intermediate computational layers whose values are not directly supplied as inputs or observed as final predictions.

Even when a network contains thousands or millions of neurons, each neuron performs the same fundamental weighted-sum operation.

Key Concepts

Concept Description
Neuron Fundamental computational unit of a neural network.
Weight Learnable parameter controlling the contribution of an input.
Bias Learnable parameter that shifts the weighted sum.
Parameters Adjustable weights and biases of a model.
Prediction Output calculated using the current parameters.
Error Difference between the predicted and actual values.
Learning Iterative adjustment of parameters to reduce prediction error.
Layer Group of neurons processing a common set of inputs.
Neural network Interconnected layers of neurons.

A neural network is fundamentally constructed from simple mathematical operations. Its learning capability comes from adjusting weights and biases to minimise prediction error. PyTorch simplifies the implementation of these computations, parameter adjustments and connections between layers.

X = irisData.data
y = irisData.target
X[0:5]
array([[5.1, 3.5, 1.4, 0.2],
       [4.9, 3. , 1.4, 0.2],
       [4.7, 3.2, 1.3, 0.2],
       [4.6, 3.1, 1.5, 0.2],
       [5. , 3.6, 1.4, 0.2]])
import pandas as pd

df_X = pd.DataFrame(X)
tg_y = pd.Series(y)
df_X.head()
0 1 2 3
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2

Scale the data:

from sklearn.preprocessing import StandardScaler
scaled_X = StandardScaler().fit_transform(X)
scaled_X[0:5]
array([[-0.90068117,  1.01900435, -1.34022653, -1.3154443 ],
       [-1.14301691, -0.13197948, -1.34022653, -1.3154443 ],
       [-1.38535265,  0.32841405, -1.39706395, -1.3154443 ],
       [-1.50652052,  0.09821729, -1.2833891 , -1.3154443 ],
       [-1.02184904,  1.24920112, -1.34022653, -1.3154443 ]])
df_scaled_X = pd.DataFrame(scaled_X)
df_scaled_X.head()
0 1 2 3
0 -0.900681 1.019004 -1.340227 -1.315444
1 -1.143017 -0.131979 -1.340227 -1.315444
2 -1.385353 0.328414 -1.397064 -1.315444
3 -1.506521 0.098217 -1.283389 -1.315444
4 -1.021849 1.249201 -1.340227 -1.315444

Split the input and output to the training and testing:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2, random_state = 42)
print(f'{X_train.shape = } is 80% for training',
     f'{X_test.shape = } is 20% for testing',
     sep='\n')
X_train.shape = (120, 4) is 80% for training
X_test.shape = (30, 4) is 20% for testing
Convert the above NumPy arrays to Pytorch:

PyTorch represents data as tensors, which are containers optimised for the mathematical operations that neural networks require.

X_tensor_train = torch.tensor(X_train, dtype=torch.float32)
X_tensor_test = torch.tensor(X_test, dtype=torch.float32)
y_tensor_train = torch.tensor(y_train, dtype=torch.long)
y_tensor_test = torch.tensor(y_test, dtype=torch.long)

Neural Network

The simplest neural network consists of a single neuron that performs a linear transformation.

model = nn.Sequential(
    nn.Linear(1, 1)
)

The nn.Sequential container passes data through its layers in sequential order.

The nn.Linear(1, 1) layer specifies:

  • One input feature.
  • One output value.
  • A trainable weight.
  • A trainable bias.

The mathematical representation of the neuron is:

\[\hat{y} = wx + b\]

Where:

  • $x$ is the input feature.
  • $w$ is the weight.
  • $b$ is the bias.
  • $\hat{y}$ is the predicted output.
x Input Weight (w) wx + b Linear neuron b Bias ŷ Prediction

During training, the neuron learns the weight and bias that produce the best-fitting line through the training data.

Here the Neural network for the Iris dataset:

import torch.nn as nn

class IrisModel(nn.Module):
    def __init__(self):
        super(IrisModel, self).__init__()
        # Linear model
        self.fc = nn.Linear(4,3) # 4 input features can generate 3 targets
    
    
    def forward(self, x):
        return self.fc(x)

model = IrisModel()

Loss Function

The loss function measures the difference between predicted and actual values.

The Mean Squared Error (MSE) is the simplest to explain:

loss_function = nn.MSELoss()

The mathematical representation of MSE is:

\[\mathcal{L} = \frac{1}{N} \sum_{i=1}^{N}(y_i-\hat{y}_i)^2\]

Where:

  • $N$ is the number of samples.
  • $y_i$ is the actual value.
  • $\hat{y}_i$ is the predicted value.
  • $\mathcal{L}$ is the calculated loss.

Larger prediction errors receive a greater penalty because the differences are squared.

The objective of training is to minimise this loss.

Cross-Entropy Loss (nn.CrossEntropyLoss)

Here we use nn.CrossEntropyLoss measures the difference between the predicted class probabilities and the actual class labels. It is commonly used in multi-class classification problems:

loss_criterion =nn.CrossEntropyLoss() # best for the classification problems

Optimisation

An optimiser updates the trainable parameters of a neural network to reduce prediction errors. The model.parameters() method provides access to the trainable weight and bias.

The learning rate (lr) controls the magnitude of parameter updates.

  • A small learning rate produces smaller adjustments.
  • A large learning rate produces larger adjustments.
  • Extremely small or large learning rates can create training difficulties.

Create optimiser:

import torch.optim as optim
optimiser = optim.Adam(model.parameters(), lr =0.01)

Training is an iterative process in which the model makes predictions, calculates errors and adjusts its parameters.

Each complete pass through the training dataset is called an epoch.

Training Loop Operations

Operation Description
optimiser.zero_grad() Clears gradients from the previous iteration
model(inputs) Performs a forward pass to generate predictions
loss_function(outputs, times) Calculates the prediction error
loss.backward() Calculates gradients through backpropagation
optimiser.step() Updates the trainable parameters
Clear Gradients optimizer.zero_grad() Forward Pass outputs = model(inputs) Calculate Loss loss_function(outputs, times) Backpropagation loss.backward() Update Weight and Bias optimizer.step() Next Epoch Repeat for 1000 epochs
epochs = 1000
losses = []

for epoch in range(epochs):
    optimiser.zero_grad()
    outputs = model(X_tensor_train)
    loss = loss_criterion(outputs, y_tensor_train)
    loss.backward()
    optimiser.step()
    losses.append(loss.item())
    if epoch % 100 == 0:
        print(f"Epoch {epoch} Loss = {loss.item()}")
Epoch 0 Loss = 2.113104820251465
Epoch 100 Loss = 0.5278659462928772
Epoch 200 Loss = 0.3992648422718048
Epoch 300 Loss = 0.3256811797618866
Epoch 400 Loss = 0.2734515964984894
Epoch 500 Loss = 0.23453274369239807
Epoch 600 Loss = 0.20486031472682953
Epoch 700 Loss = 0.18179373443126678
Epoch 800 Loss = 0.16352887451648712
Epoch 900 Loss = 0.14881643652915955

PyTorch accumulates gradients by default. Therefore, clearing previous gradients is necessary in this training loop.

Backpropagation

Backpropagation loss.backward() calculates how the loss changes with respect to the trainable parameters. It computes the gradients of the weight and bias. The optimiser subsequently uses these gradients to update the parameters.

here the model has trained int he above training process:

Line Explanation
plt.plot(losses) Plots the loss values as a line. With no x-values supplied, Matplotlib uses the indices 0, 1, 2, …. Each point represents an epoch if losses contains one value per epoch.
plt.title("Training Loss Curve") Sets the visible title above the plot.
fig = plt.gcf() Gets the current Matplotlib figure and stores it in fig. The figure is the container that holds the plot.
fig.set_label("Training-loss-curve") Sets a label on the figure object. You can retrieve it with fig.get_label(). The visible title is still Training Loss Curve.
plt.plot(losses)
plt.title("Training Loss Curve")

loss_curve_fig = plt.gcf()
loss_curve_fig.set_label("Training_loss_curve")

png

Inference

After training, the neural network can generate predictions for previously unseen inputs. The torch.no_grad() context manager disables gradient tracking.

Unlike training, inference does not require gradient calculation or parameter updates. Consequently, disabling gradient tracking makes prediction more computationally efficient.

from sklearn.metrics import classification_report

with torch.no_grad():
    preds = model(X_tensor_test)
    predictions = torch.argmax(preds, dim=1)
    print(classification_report(y_tensor_test, predictions, target_names = irisData.target_names))
              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        10
  versicolor       1.00      1.00      1.00         9
   virginica       1.00      1.00      1.00        11

    accuracy                           1.00        30
   macro avg       1.00      1.00      1.00        30
weighted avg       1.00      1.00      1.00        30

The model correctly classified all 30 examples in this evaluation: 10 setosa, 9 versicolor, and 11 virginica.

Column What it measures What your report shows
Precision Of the examples predicted to be a given species, how many actually belonged to that species? Every prediction for each species was correct.
Recall Of the examples that actually belonged to a given species, how many did the model identify? The model found every example of each species.
F1-score The harmonic mean of precision and recall. It is high when both are high. Both precision and recall were perfect for every species, so every F1-score is (1.00).
Support The number of examples of each species in the true labels. There were 10 setosa, 9 versicolor, and 11 virginica.

The bottom rows summarise the evaluation:

  • Accuracy is the fraction of all predictions that were correct, here (30/30 = 1.00).
  • Macro average gives each species equal weight when averaging precision, recall, and F1-score.
  • Weighted average weights each species by its support, so virginica contributes slightly more than versicolor. Both averages are (1.00) because every species has perfect scores.

The report describes performance on these 30 examples. How well the model generalises depends on whether they were held out from training and how representative they are of future data.