Training a neural network is a process to adjust its parameters based on a training set to ensure it correctly classifies the data.
y^=h(x;θ)
where:
θ is the set of parameters of the neural network
θ={W[1],b[1],…,W[L],b[L]}
Analogy: Think of training a neural network like teaching a student. The training examples are like practice problems, and the training algorithm adjusts the "knowledge" (parameters) to help the network make better predictions, eventually finding the optimal decision boundary.
Visual representation:
Training examples → Training Algorithm → Θ∗ → Decision boundary
10.2 Training Set
To train a neural network, เราก็ต้องมี Training set ถูกป่าว
A training set is composed of pairs of an input vector and a target output. D={(x1,y1),(x2,y2),(x3,y3),…,(xN,yN)}
where:
Each (xi,yi) is a labeled example, when i∈[1,…,N]
Each xi=[xi1xi2…xiM]⊤ is an input vector
Each yi is a target output
N is the number of training examples
M is the number of features
Analogy: A training set is like a textbook with answers. Each example (xi,yi) is a question-answer pair where xi is the question and yi is the correct answer.
Example 10.1
Write the training set visualized by the following plot.
Note: use 0 for ● and 1 for ×.
Write the training set visualized by the following plot.
Note: use 0 for ● and 1 for ×.
{(000,1),(100,1),(011,0),(112,1)}
N=4,M=3
10.3 Gradient Descent
Key Points:
Gradient descent is a common method to train a neural network
It is an iterative optimization algorithm for finding the values of parameters of a function that minimizes a differentiable objective function (คล้าย ๆ กับ Chapter 5 - Local Search)
ต่างกันตรงที่ว่า Function ที่จะ Work กับ Gradient Descent ก็คือต้องเป็น Differentiable Function
It works similarly to the hill-climbing algorithm but operates in a continuous space
แต่ Gradient Descent เป็น continuous space ไปทางไหนก็ได้ 360 องศาเลยล่ะ
It operates by updating the parameters in the direction of the negative gradient of the objective function, gradually moving towards a minimum
Update Rule
Given an objective function J(θ), the gradient descent algorithm updates the parameters θ iteratively as follows: θ←θ−η∇θJ(θ)
where:
η is the step size or learning rate (a hyperparameter that controls the step size)
∇θJ(θ) is the gradient of the objective function with respect to the parameters
Gradient = Direction นั่นแหละ
θ=[θ1,…,θk]
∇θJ(θ)=∂θ1∂J∂θ2∂J⋮∂θk∂J
Analogy: Imagine you're hiking down a mountain in fog. You can only see your immediate surroundings. Gradient descent is like taking small steps in the direction that slopes downward the most steeply. The learning rate η controls how big each step is.
Visual Example
For example, given an objective function f(x)=x2: (We want to find x that makes f(x) be the minimum)
Includes the weights and the bias of the neural network as its parameters
The gradient descent algorithm can then be used to iteratively update the weights and bias of the neural network to minimize the objective function. Thus, the neural network learns to make accurate predictions on the training set.
A loss function is a mathematical function that quantifies the difference between the predicted output of a model (yi^) and the actual target output (yi). It measures how well the model is performing on a given dataset.
The choice of loss function depends on the specific task and the type of output the model is producing.
Common Loss Functions
1. Squared Error Loss Function
Quantifies the difference between target and predicted outputs. Commonly used for ==regression tasks.==
Regression task → yi∈R
Lse(xi,yi;w,b)=∥y^i−yi∥2 Properties:
When y^i is close to yi, Lse is small
When y^i is far from yi, Lse is large
We need to square because we want the error (loss) to be positive, ถ้ามีบวกบ้าง มีลบบ้าง สรุปคือเราเอามา Sum กันได้ 0 งงเลยล่ะ Loss เป็นศูนย์แต่จริง ๆ แล้วพังเยอะ
Analogy: Squared error is like measuring how far your dart is from the bullseye. The further away, the bigger the penalty, and it squares the distance to punish larger errors more heavily.
2. Cross-Entropy Loss Function
Commonly used for ==classification tasks==, especially with sigmoid units.
Analogy: Cross-entropy loss is like a confidence penalty. If the model is very confident (prediction close to 1) but wrong (actual is 0), the penalty shoots up dramatically. It rewards confident correct predictions and heavily punishes confident wrong predictions.
Example 10.3
When yi=1 and y^i=0.82, calculate the squared error loss and the cross-entropy loss.
Batch gradient descent is a variant that uses the entire training set to compute gradients in each iteration.
Algorithm
Input: A training set D={(xi,yi)}i=1N
Initialize model parameters θ (e.g., weights and biases) randomly or with small values
fore=1 to E (epochs/training iterations):
for(xi,yi)∈D:
Compute predicted output: y^i=h(xi;θ)
Compute gradient ∇θL(xi,yi;θ)
Compute average gradient: ∇θL(θ)=N1∑i=1N∇θL(xi,yi;θ)
Update model parameters: θ←θ−η∇θL(θ)
Analogy: Batch gradient descent is like a teacher grading all homework assignments before deciding what to teach next. You look at everyone's mistakes, find the average problem areas, and adjust your teaching accordingly.
Stochastic gradient descent (SGD) is a variant of the gradient descent algorithm that updates the model parameters using the gradient computed from a small, randomly selected subset of the training data (minibatch) at each iteration.
Algorithm
Input: A training set D={(xi,yi)}i=1N, minibatch size B
Initialize model parameters θ (e.g., weights and biases) randomly or with small values
fore=1 to E (epochs):
Split D into minibatches of size B: {B1,B2,…,BT} where T=⌈BN⌉
Update model parameters: θ←θ−η∇θLB(θ)
Number of updates = T×E
Comparison between Batch GD and SGD
แค่ต่างกันตรง Data ที่เอาไว้ Calculate Gradient นั่นแหละ
(Batch) GD:
Uses the entire dataset to compute gradients
==More stable convergence== but can be slow for large datasets
SGD:
Uses a single sample (or minibatch) to compute gradients
Faster updates and can escape local minima, but more noisy
Escape local minima ได้ด้วยเพราะมัน Zig-zag 55555
เดี๋ยวนี้ใช้อันนี้กันหมด เพราะว่ามันดีกว่า in terms of memory management or something
Analogy: If Batch GD is like surveying everyone in a city before making a decision, SGD is like asking a random sample of people and making quicker (but noisier) decisions. SGD's path is more zigzagged but often reaches the goal faster.
Example 10.4
Given the MLP for the XOR function below, use the SGD algorithm to update the weights and biases using a minibatch size of 2: B1={([0,0]T,0),([1,0]T,1)}, learning rate η=0.1, and the cross entropy loss function.
Using the cross-entropy loss function: Lce(xi,yi;θ)=−[yilog(y^i)+(1−yi)log(1−y^i)]
Given an MLP with W[1]∈R4×5, b[1]∈R4, W[2]∈R3×4, b[2]∈R3, W[3]∈R1×3, and b[3]∈R, write the product of partial derivatives using the chain rule to compute:
∂w1,1[3]∂Lce,i
∂b2[2]∂Lce,i
∂w5,2[1]∂Lce,i
Note: all neurons use the sigmoid activation function, and the loss function is cross-entropy loss.
Adam is an optimization algorithm that combines the benefits of two other popular optimizers: AdaGrad and RMSProp. It computes adaptive learning rates for each parameter by maintaining running averages of both the gradients and their squared values.
Update Rules
Given parameters w, gradient gt, and learning rate η, instead of updating parameters using the raw gradient: wt=wt−1−ηgt
The Adam update rules are: mt=β1mt−1+(1−β1)gt (First moment estimate) vt=β2vt−1+(1−β2)gt2 (Second moment estimate) m^t=1−β1tmt (Bias-corrected first moment) v^t=1−β2tvt (Bias-corrected second moment) wt=wt−1−ηv^t+ϵm^t (Parameter update)
where:
mt is the first moment estimate (mean of gradients)
vt is the second moment estimate (uncentered variance of gradients)
m^t and v^t are bias-corrected estimates of mt and vt, respectively
Aims to correct the initialization bias towards zero, especially during initial time steps
β1 and β2 are hyperparameters that control the decay rates of these moving averages
Commonly set to β1=0.9 and β2=0.999
ϵ is a small constant (e.g., 10−8) to prevent division by zero
Analogy: Adam is like an adaptive cruise control for optimization. It remembers both where you've been (momentum via mt) and how bumpy the road has been (variance via vt), then adjusts your speed (learning rate) accordingly for each parameter individually.
10.9 Scheduling Learning Rate
Scheduling the learning rate (step size) is a technique used to adjust the learning rate during training to improve convergence and performance.
Common Strategies
1. Step Decay
Reduce the learning rate by a factor (e.g., 0.1) every few epochs (e.g., every 10 epochs).
ηt+1=γηtevery k epochs
Analogy: Step decay is like driving at high speed initially, then periodically reducing speed as you get closer to your destination.
2. Exponential Decay
Decrease the learning rate exponentially over time, typically using a decay rate.
ηt=η0⋅γt
Analogy: Exponential decay is like gradually and smoothly slowing down your car as you approach your destination, with the rate of slowing itself decreasing over time.
3. Cosine Annealing
Gradually decrease the learning rate following a cosine function.
ηt=ηmin+21(ηmax−ηmin)(1+cos(Ttπ))
where:
ηmin and ηmax=η0 are the minimum and maximum learning rates
T is the total number of iterations
Analogy: Cosine annealing is like a smooth, wave-like deceleration. It starts fast, slows down smoothly in a curved pattern, and gently approaches the minimum, like a pendulum gradually coming to rest.
10.10 Summary
Gradient Descent (GD) is an optimization algorithm used to minimize the loss function by iteratively updating model parameters in the direction of the negative gradient
Stochastic Gradient Descent (SGD) is a variant of GD that updates model parameters using a single sample or a small batch of samples, making it more efficient for large datasets
Adam is an advanced optimization algorithm that combines the benefits of AdaGrad and RMSProp, using adaptive learning rates for each parameter based on first and second moment estimates of the gradients
Scheduling the learning rate during training can help improve convergence and performance, with common strategies including: