









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










Learning objectives
CONTENTS
11.7 Categorical Cross-Entropy
Categorical Cross-Entropy is used for mutually exclusive multiclass classification, such as classifying an image as a cat, dog or rabbit.
Formula: L = −Σn yn log(nn), where the sum is over all classes. It is commonly combined with a softmax output layer.
11.8 Hinge Loss
Hinge loss is associated with Support Vector Machines and can also be used in some neural-network classification systems.
Formula: L = max(0, 1 − yn), where y is usually −1 or +1 and n is the model score. It penalizes incorrect predictions and predictions that do not satisfy a required classification margin.
11.9 Comparison of Loss Functions
Loss function Main use
Mean Squared Error Regression
Mean Absolute Error Regression
Binary Cross-Entropy Binary classification
Categorical Cross-Entropy Multiclass classification
Hinge Loss Margin-based classification
11.10 Choosing the Correct Loss Function
The loss function should match the task and output representation: MSE or MAE for house-price prediction; binary cross-entropy for spam classification; categorical cross-entropy for cat/dog/rabbit classification; and hinge loss for margin-based classification.
CHAPTER TWELVE: OPTIMIZATION ALGORITHMS IN
NEURAL NETWORKS
12.1 Introduction
Optimization finds suitable values for model parameters to minimize the loss function. Neural networks may contain thousands, millions or billions of trainable parameters. Optimization algorithms determine how these parameters should be adjusted during training.
12.2 Gradient Descent
Gradient Descent updates model parameters in the direction opposite to the gradient of the loss function.
Equation: w(new) = w(old) − η∇L(w)
Here w is a model parameter, η is the learning rate and ∇L(w) is the gradient of the loss.
Basic procedure: initialize parameters; calculate predictions; calculate loss; calculate gradients; update parameters; repeat.
12.3 Types of Gradient Descent
A. Batch Gradient Descent
Uses the entire training dataset to calculate each gradient update. It can produce stable gradient estimates but is computationally expensive for large datasets and requires processing all examples before an update.
B. Stochastic Gradient Descent (SGD)
Uses one training example at a time for an update. It makes frequent updates and can be useful for large datasets, but updates may fluctuate and training can be less stable.
C. Mini-Batch Gradient Descent
Divides the dataset into smaller groups called batches. If N is the number of examples and B is the batch size, iterations per epoch = N/B. For 1,000 examples and a batch size of 100, there are 10 iterations per epoch, assuming equal-sized batches.
12.4 Learning Rate
The learning rate controls the size of parameter updates. If too high, updates may overshoot a minimum and training may become unstable. If too low, training may be very slow and make insufficient progress.
12.5 Momentum Optimization
Momentum uses information from previous gradients to influence current updates. It can accelerate training in consistent directions and reduce oscillations.
Equations: vn = βvnnn + ∇L(wn); wnnn = wn − ηvn.
12.6 AdaGrad
AdaGrad adapts the learning rate for each parameter based on accumulated squared gradients. It can be useful when parameters have different update frequencies, but its effective learning rate may become excessively small over time.
Simplified update: wnnn = wn − [η/(√Gn + ε)]gn.
12.7 RMSProp
RMSProp uses an exponentially weighted moving average of squared gradients to prevent the learning rate from decreasing too aggressively.
Equations: sn = βsnnn + (1 − β)gn²; wnnn = wn − [η/(√sn + ε)]gn.
12.8 Adam Optimizer
Adam stands for Adaptive Moment Estimation. It combines momentum-like tracking of gradients with adaptive scaling based on squared gradients. It is widely used, but does not guarantee the best generalization or outperform simpler optimizers on every task.
First moment: mn = βnmnnn + (1 − βn)gn.
Second moment: vn = βnvnnn + (1 − βn)gn².
Bias correction: mnn = mn/(1 − βnn); vnn = vn/(1 − βnn).
Update: wnnn = wn − ηmnn/(√vnn + ε).
13.6 Regularization in Deep Learning
Regularization reduces overfitting and can improve generalization.
L1 regularization: L(total) = L(original) + λΣn|wn|. It can encourage some weights to become zero, producing sparse models.
L2 regularization: L(total) = L(original) + λΣnwn². It discourages excessively large weights.
Dropout: randomly sets a subset of neuron outputs to zero during training, reducing excessive dependence on particular neurons. It is disabled during ordinary inference.
Early stopping: monitors validation performance and stops training when further training no longer improves the chosen validation metric.
13.7 Batch Normalization
Batch Normalization normalizes intermediate activations using statistics calculated from a training mini-batch, with learned scaling and shifting parameters. It can stabilize and accelerate training in many architectures.
13.8 Transfer Learning
Transfer learning reuses a model trained on one task or dataset as the starting point for a related task. For example, a model trained to recognize general objects can be adapted to classify agricultural diseases. Benefits may include reduced training time and improved performance with smaller datasets, especially when the tasks are related.
CHAPTER FOURTEEN: CONVOLUTIONAL NEURAL
NETWORKS IN DETAIL
14.1 Introduction
Convolutional Neural Networks (CNNs) are specialized deep learning models commonly used for images and other spatially structured data. They automatically identify visual patterns without requiring every feature to be manually defined.
14.2 Understanding Digital Images
A digital image is represented by numerical pixel values. A grayscale image has one intensity value per pixel. A colour image commonly has Red, Green and Blue channels. A 64 × 64 colour image can be represented as a 64 × 64 × 3 array.
14.3 Convolution Operation
Convolution applies a small matrix called a filter or kernel to an input image. The filter moves across the image and calculates weighted sums of local regions. The results form a feature map.
Example input: X = [[1,2,3],[4,5,6],[7,8,9]]. Filter: K = [[1,0],[0,−1]]. The first calculation is (1×1)+(2×0)+(4×0)+(5×−1) = 1−5 = − 4. The filter then moves across the input to produce a feature map.
14.4 Filters and Kernels
A filter is a small matrix of learnable values used to detect patterns. Filters may learn to respond to horizontal, vertical or diagonal edges, textures and more complex visual structures.
14.5 Stride
Stride is the number of pixels by which a filter moves during convolution. Stride 1 moves one pixel at a time; stride 2 moves two pixels at a time. A larger stride generally reduces output spatial dimensions.
14.6 Padding
Valid padding: no additional border values are added. Same padding: padding is selected so that, under suitable stride conditions, output spatial dimensions are preserved.
14.7 Pooling Layers
Pooling reduces the spatial dimensions of feature maps and summarizes local information.
Max pooling: selects the largest value in a region. For [[1,3],[2,4]], the result is 4.
Average pooling: calculates the average. For the same matrix, (1+3+2+4)/4 = 2.5.
14.8 Fully Connected Layers
A fully connected layer connects each neuron to all neurons in the preceding layer. It is often used near the end of traditional CNN architectures to combine extracted features and generate predictions. Some modern CNNs use global average pooling or other structures instead.
14.9 CNN Architecture Example
For classifying images as cat, dog or rabbit, a possible architecture is: input image; convolution; ReLU; pooling; additional convolutional layers; flattening or global average pooling; fully connected layer; softmax output. Example probabilities: cat 0.75, dog 0.20, rabbit 0.05. The model predicts cat.
14.10 Applications
14.11 Advantages and Limitations
Advantages: automatic feature extraction, learning spatial relationships, filter reuse across image locations and strong performance in many image tasks.
Limitations: may require large labelled datasets, can be computationally expensive, may be sensitive to image quality or distribution changes, need careful architecture selection and can be difficult to interpret.
CHAPTER FIFTEEN: RECURRENT NEURAL NETWORKS IN
DETAIL
15.1 Introduction
Recurrent Neural Networks (RNNs) are designed to process sequential information. Unlike traditional feedforward networks, RNNs use recurrent connections to retain information from previous time steps. They are useful when data order matters, such as in sentences, speech and time series.
16.2 Attention Mechanism
Attention allows a neural network to determine which parts of the input are most relevant when producing an output. It helps a model represent relationships among words or other input elements.
16.3 Self-Attention
Self-attention allows each element in a sequence to consider other elements in the same sequence. It uses Query (Q), Key (K) and Value (V) representations.
Attention equation: Attention(Q,K,V) = Softmax(QKn/√dn)V. Here dn is the dimension of the key vectors.
16.4 Multi-Head Attention
Multi-head attention uses multiple attention operations, called heads, to learn different relationships in the input. Their outputs are combined to form a richer representation.
16.5 Positional Encoding
The original Transformer does not use recurrent connections to process tokens in sequence. Positional information is therefore added to represent token order.
16.6 Encoder and Decoder
Encoder: processes the input sequence and creates contextual representations. Decoder: uses encoder representations and previously generated output tokens to produce the next output. Not all modern Transformers use both components; encoder-only and decoder-only architectures are also common.
16.7 Applications of Transformers
16.8 Generative AI and Large Language Models
Generative AI systems create new content based on patterns learned from training data. Content may include text, images, audio, video and code. Large Language Models are neural networks trained on large collections of text and other data to process and generate language. They can answer questions, summarize documents, generate text, translate languages, assist with programming and extract information.
CHAPTER SEVENTEEN: APPLICATIONS OF ARTIFICIAL
NEURAL NETWORKS
17.1 Healthcare
Neural networks support medical research, image analysis and clinical decision support. Applications include identifying abnormalities in images, analysing records, supporting disease screening, predicting health risks, processing medical signals and supporting drug-discovery research. Such systems require clinical evaluation and should not replace qualified professionals.
17.2 Banking and Finance
Applications include fraud detection, credit-risk modelling, financial forecasting, customer-behaviour analysis and transaction classification. A network may learn patterns associated with potentially fraudulent transactions and flag unusual activity for investigation.
17.3 Education
Neural networks can support student-performance prediction, automated assessment support, learning recommendations, retention analysis and intelligent tutoring. A university may analyse historical academic information to identify students who may need additional support.
17.4 Agriculture
Applications include crop-disease identification, yield prediction, soil analysis, weather-related prediction, agricultural image classification and smart irrigation. CNNs can analyse leaf images for patterns associated with crop diseases.
17.5 Cybersecurity
Applications include network intrusion detection, malware classification, spam detection, anomaly detection, suspicious-login identification and phishing-detection support.
17.6 Transportation
Neural networks are used in traffic prediction, vehicle detection, driver assistance, road-sign recognition, pedestrian detection and autonomous-vehicle research.
17.7 Retail and E-Commerce
Applications include product recommendations, customer segmentation, demand forecasting, fraud detection and customer-behaviour analysis.
17.8 Telecommunications
Telecommunication companies use neural networks for network-traffic prediction, fault detection, customer-churn prediction, network optimization and fraud detection.
17.9 Weather Forecasting
Neural networks can analyse historical weather measurements such as temperature, rainfall, wind speed, atmospheric pressure and humidity. They are also used in research involving satellite and radar imagery.
CHAPTER EIGHTEEN: IMPLEMENTING NEURAL
NETWORKS USING PYTHON
18.1 Introduction
Python is widely used in AI and machine learning. Common libraries include NumPy for numerical computation, Pandas for data manipulation, Matplotlib for visualization, Scikit-learn for machine-learning utilities, TensorFlow and Keras for deep learning, and PyTorch for deep-learning research and development.
18.2 Installing Required Libraries
pip install numpy pandas matplotlib scikit-learn tensorflow
18.8 Example of a CNN Using Keras
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential([ layers.Input(shape=(64, 64, 3)), layers.Conv2D(32, kernel_size=3, activation='relu'), layers.MaxPooling2D(pool_size=2), layers.Conv2D(64, kernel_size=3, activation='relu'), layers.MaxPooling2D(pool_size=2), layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(3, activation='softmax') ]) model.summary()
This CNN is designed to classify colour images into three categories. Each input image is 64 × 64 pixels with three colour channels.
CHAPTER NINETEEN: CHALLENGES, LIMITATIONS AND
ETHICAL ISSUES
19.1 Introduction
Although Artificial Neural Networks have many advantages, they also have limitations. Understanding these is important when designing, developing and deploying AI systems.
19.2 Computational Requirements
Deep neural networks can contain millions or billions of parameters. Training may require powerful processors, GPUs, large amounts of memory and substantial electricity, making development expensive.
19.3 Large Data Requirements
Many neural networks require large datasets to learn useful patterns. Collecting and preparing high-quality training data can be expensive and time-consuming.
19.4 Overfitting
A network may memorize training examples instead of learning patterns that generalize to new data. This reduces performance on unseen examples.
19.5 Lack of Interpretability
Some neural networks are difficult to interpret because they contain many layers and parameters. This is often described as the black-box problem: a network may produce a prediction without a simple explanation of how it reached that result.
19.6 Bias in Training Data
If training data contains unfair or unrepresentative patterns, a network may learn and reproduce them. For example, a facial-recognition model trained on an unrepresentative dataset may perform differently across demographic groups.
19.7 Privacy and Data Protection
Training may involve personal information. Developers should consider consent, data minimization, lawful processing, security, confidentiality and appropriate retention. In Kenya, relevant legal considerations include the Data Protection Act, 2019.
19.8 Security Risks
19.9 Ethical Issues
19.10 Environmental Impact
Training and operating large networks can consume considerable energy and computing resources. Researchers are exploring efficient architectures, hardware and training methods to reduce environmental impact.
CHAPTER TWENTY: FUTURE TRENDS, REVISION
QUESTIONS AND REFERENCES
20.1 Future Trends
EXAMINATION REVISION QUESTIONS
Section A: Short-answer questions
ACADEMIC REFERENCES AND FURTHER READING
Author Book or research paper Main subject
Goodfellow, Bengio & Courville (2016)
Deep Learning Deep learning foundations
Bishop (1995) Neural Networks for Pattern Recognition Neural network mathematics
Haykin (1999) Neural Networks: A Comprehensive Foundation Neural network theory
Bishop & Bishop (2024) Deep Learning: Foundations and Concepts Modern deep learning
Nielsen (2015) Neural Networks and Deep Learning Training and backpropagation
Zhang et al. (2023) Dive into Deep Learning Theory and practical deep learning
Rumelhart, Hinton & Williams (1986)
Learning Representations by Back-Propagating Errors Backpropagation
LeCun et al. (1998) Gradient-Based Learning Applied to Document Recognition Convolutional networks
Goodfellow et al. (2014) Generative Adversarial Nets Generative neural networks
Vaswani et al. (2017) Attention Is All You Need Transformer architecture
FREE ONLINE LEARNING RESOURCES
These notes provide a foundation for university study. Supplement them with prescribed textbook chapters, programming exercises and lecturer-specific course requirements.