Lab notebook
A Deep Semi-Supervised Domain Generalization Approach for Epileptic Seizure Prediction using Electroencephalography (EEG)
Deep learning notes were taken during the Coursera Deep Learning course: I took notes, asked my cousin about what I didn’t understand, and self-tested with summary questions.
Courses DeepLearning.AI on Coursera
- I learned deep learning through DeepLearning.AI courses on Coursera; Entries 1–6 are my notes from them
- Completed courses
- Neural Networks and Deep Learning (May 24, 2023)
- Improving Deep Neural Networks: Hyperparameter Tuning, Regularization and Optimization (Jun 13, 2023)
- Convolutional Neural Networks (Jun 14, 2023)
Entry 1 Fri 3/17/23 · Linear classifier
- Started the Coursera deep learning course: took notes, asked my cousin about anything I didn’t understand, and self-tested with summary questions and quizzes
- Why image classification is hard
- Semantic gap: a computer sees an image only as a grid of numbers from 0 to 255
- Viewpoint variation, intraclass variation (white cat vs black cat), fine-grained categories (pomeranian vs maltese), background clutter, illumination changes, deformation (cat sitting vs jumping) and occlusion (cat under a blanket)
- Linear classifier
- Data-driven approach: collect images and labels → train → evaluate (datasets: MNIST, CIFAR-10, ImageNet)
- Flatten the image’s pixels into a column x, then score = f(x, W) = Wx + b, with one row of weights per class
- Loss functions: how good is the classifier? (low loss = good)
- Multiclass SVM loss: worked example for three images gave losses 2.9, 0 and 12.9, so the dataset loss L = (2.9 + 0 + 12.9) / 3 = 5.27
- Softmax: exponentiate the scores (so they’re positive without changing their order), then divide by their sum so they add to 1
- Cross-entropy loss: Li = −log P(Y = yi | X = xi); it grows to infinity as the probability of the true class nears 0
- Coding: loaded an image in Colab with OpenCV and changed blocks of pixels to see how an image is just an array
Entry 2 Mon 3/20/23 · Optimization
- Optimization: finding the weights and bias that make the loss as small as possible
- Analogy: a blind person trying to reach the lowest point of a valley by following the slope
- Gradient descent
- 1) Initialize the parameters, 2) compute the loss, 3) compute its gradient, 4) update: wt+1 = wt − learning rate × dw, 5) repeat
- Hyperparameters chosen by the user: weight initialization, number of steps, learning rate (usually 1/1000 or 1/10000)
- Problem: zero gradient
- At a local minimum or saddle point the gradient is 0, so w = w − 0 never changes and training gets stuck
- Fix: momentum
- Idea of inertia (Newton’s first law): keep a running “velocity” v = ρ·v + dw and update w = w − v
- ρ adds “friction”, typically 0.9 or 0.99, so the update keeps moving even when the gradient is 0
- Coding: Python classes (a TV-remote example with power, volume and Netflix attributes)
Entry 3 Mon 3/27/23 · Neural networks
- From a linear classifier to a 2-layer neural network
- f = W2 · max(0, W1x + b1) + b2: one more weight and bias, with a hidden layer h in between
- Also called a fully-connected network or multi-layer perceptron
- ReLU: Rectified Linear Unit, ReLU(z) = max(0, z)
- An activation function: passes positive inputs and outputs 0 for negative ones
- Without activations, the whole network is just a linear function and can only learn linear patterns; ReLU adds non-linearity so it can learn complex patterns, and helps keep gradients from vanishing
- Practice: counting learnable parameters
- 4×4 RGB images (48 features), hidden size 20, 4 classes
- Layer 1: 20 × 48 + 20 = 980; layer 2: 4 × 20 + 4 = 84; total = 1,064 parameters
Entry 4 Mon 4/3/23 · NumPy
- Coding: building NumPy arrays (zeros, ones, full, identity, random) and doing element-wise operations, sums, logs and matrix multiplication (@)
- Wrote my own linear_classifier(weight, bias, x) and softmax(score) functions with NumPy
- Self-quiz
- 2×2 RGB images, hidden size 10, 10 classes: layer 1 = 10 × 12 + 10 = 130, layer 2 = 10 × 10 + 10 = 110, total = 240; W1 is 10×12 and W2 is 10×10
- Reviewed ReLU, optimization, gradient descent, the zero-gradient problem and softmax
Entry 5 Fri 4/7/23 · Training a network from scratch
- Built and trained a 2-layer network on MNIST (handwritten digits) using only NumPy
- Flattened each 28×28 image to 784 values and scaled pixels from 0–255 to 0–1; one-hot encoded the labels
- Initialized small random weights; forward pass with ReLU and softmax
- Cross-entropy loss and accuracy functions; wrote the gradients by hand (backpropagation) and updated W1, b1, W2, b2 in mini-batches
- Debugging
- Loss went down steadily, but the accuracy plot stayed flat at 0
- Cause:
avg_acc+accinstead ofavg_acc += acc, so accuracy was never added up - A later run’s log shows accuracy climbing past 97%
Entry 6 Fri 4/28/23 · Convolutional neural networks
- Problem → solution
- Fully-connected classifiers ignore the spatial structure of images → convolutional layers that operate on the image directly
- Convolution
- A small filter (e.g., 3×5×5 for a 3×32×32 RGB image; its depth must match) slides over the image; at each spot, multiply element-wise and sum to get one value
- Each filter produces an activation (feature) map; 6 filters → 6 maps of 28×28 = one convolutional layer
- To get scores, flatten the last activation map and add a linear layer
- Feature maps shrink with each layer → padding
- Output size = (W − K + 2P) / S + 1 (input W, filter K, padding P, stride S)
- Quiz: 224×224×3 input, 32 filters of 3×3, padding 1 → 32 × 224 × 224
- Downsampling
- Max pooling keeps the largest value (the most important feature); average pooling reduces the effect of noise and outliers
- Example: 224×224×64 → 112×112×64
- Linear classifier vs neural network vs CNN
- Linear classifier: 1 layer, linear patterns only
- Neural network: multiple layers with ReLU between weight matrices, global information (W @ x)
- CNN: multiple layers of filters and pooling, local information; built for images
Research notes Brainstorming the method
- Previous methods
- 1D EEG recording → CNN feature extractor → feature map → linear layer → probability of seizure
- Problem 1: trained networks are biased to the specific datasets (and devices) they learned from, so they can’t be used in practice
- Problem 2: very sensitive to noise, which is why earlier work needed a wavelet transform
- My idea
- The features a CNN extracts from EEG are entangled: frequency, amplitude, noise, seizure-related and device-related information all mixed together
- Previous methods learn from all of it at once; I want to pull out only the seizure-related features (assuming such a latent code exists)
- Step 1: representation learning
- Goal: disentangle the seizure-related features
- Autoencoder: the encoder compresses the 1D signal into a latent code; the decoder reconstructs the signal to check that the features were extracted well
- L1 loss compares the original and reconstructed signal point by point
- Step 2: transfer learning
- Goal: an accurate seizure classifier
- 1D signal → pre-trained encoder from step 1 → seizure-related features → neural network → probability of seizure vs normal
- Trained with cross-entropy loss
Stage 1 Background
- Why seizure prediction
- 1 in 26 people in the US has epilepsy, 50 million worldwide, and the death rate with epilepsy as the underlying cause has doubled over the past decade
- 1 in 3 patients have drug-resistant epilepsy, where medication can’t control seizures, so prediction is the best solution
- Motivation: meeting epilepsy patients while volunteering at a hospital, who couldn’t lead a normal life in constant fear of seizures
- EEG
- Electrodes on the scalp record the brain’s electrical activity; during a seizure, the EEG shows rapid spiking waves
- Engineering goal
- A seizure prediction model, using semi-supervised deep learning, that is (1) not biased to particular datasets or devices and (2) robust to noise such as blinking, coughing and movement
Stage 2 Datasets
NICU dataset
- Neonatal EEG recordings with seizure annotations
- 46,640 samples from 79 individuals
- 17,940 seizure (positive), 28,700 normal (negative)
Epileptic Seizure Recognition dataset (UC Irvine)
- 11,500 samples from 500 individuals
- 2,300 seizure (positive), 9,200 normal (negative)
- Two different sources, so a model trained on one and tested on the other shows whether it is biased to a dataset or device
Stage 3 Representation learning: the feature swapping mechanism
- The encoder splits each EEG signal’s features into four parts: zs (seizure), zd (device), zn (noise) and zc (common)
- Input: two EEG signals from the same seizure category but different devices, so their seizure-related features should be identical
- Swap only the seizure features: Z1swap = {z2s, z1d, z1n, z1c} and Z2swap = {z1s, z2d, z2n, z2c}
- The decoder rebuilds each signal from the swapped features; if zs really holds only seizure information, the rebuilt signal should match the original
- Loss: Lseizure = Σt |Et − Êt|, the element-wise difference between the input and reconstructed signal over T samples
Stage 4 Transfer learning: the seizure classifier
- The pre-trained encoder from Stage 3 extracts zs, the seizure-related features (ENC: E → Z)
- The Seizure Classifier (SCL), a neural network, turns zs into Pseizure, the probability that a seizure will occur
- Softmax turns the scores into probabilities; cross-entropy loss LCE = −Σ yi log ŷi is large when the prediction is far from the truth
Stage 5 Experiment 1: t-SNE feature map visualization
- Goal: check that the encoder really extracts the right features
- Each person’s EEG data is plotted in its own color
- Original NICU data: the colors are tangled together; after disentanglement by the autoencoder, same-colored points form clear groups
- Shows the feature swapping mechanism works and that seizure-related features can be extracted
Stage 6 Experiment 2: within-dataset evaluation (≈5% improvement)
- Data split into 5 folds: train on 4, test on 1
- Compared against VGG19, MobileNetV2, DenseNet121 and HRNet32 on accuracy, recall, precision and F1-score
- The proposed model reached 92.70% accuracy, about 5% better than previous methods
Stage 7 Experiment 3: cross-dataset evaluation (≈20% improvement)
- Train on 4 folds of one dataset, test on 1 fold of the other dataset, to test for bias to datasets and devices (overfitting)
- Previous models dropped sharply when tested on a new dataset; the proposed model held up much better
- Outperformed previous methods by 19.35% in the cross-dataset evaluation
Stage 8 Application: wearable prototype
- Goal: a device patients can wear in daily life that warns them before a seizure
- Prototype: a baseball cap with the OpenBCI “EEG Electrode Cap Bundle”
- Design
- Affordable (~$71): uses only the center electrodes (C3, C2, C4)
- Lightweight and portable: still light with a wig or cap added
- Fast: the model works on 1D seizure features rather than the full 2D EEG, so it can predict quickly



















