Deep Network Development Lecture 5 Study Notes
Supervised Learning Review
- Definition: Supervised learning is provided with a training sample consisting of a set of (input,label) pairs.
- Task: The estimation of the label (the expected output) from the input.
- Hypothesis Function: We search for a function hθ such that hθ(x)≈y.
- Two Main Tasks:
* Regression: Continuous labels where the label set is infinite. Examples include the number of cars or the age of a person.
* Classification: Discrete labels where the label set is finite. Examples include categorization tasks, such as determining the profession of a person in an image.
The Normal Equation and Least Squares
- Least Squares Solution: Can be solved in one step using the Normal Equation, which provides an exact solution to the least squares problem.
- The Regularized (L2) Least Squares Solution: Represented by the formula:
((XT×X+λ×L)−1×XT×y)
Polynomial Regression and Loss Functions
- Hypothesis Functions:
* Univariate: hθ(x)=θ0+θ1×x+θ2×x2+…
* Multivariate Example: hθ(x)=θ0+θ1×x1+θ2×x2+θ3×x12+θ4×x22+θ5×x1×x2+…
- Loss Function (Mean Squared Error - MSE):
J(θ)=2m1∑j=1m(y^(j)−y(j))2=2m1∑i=1m(hθ(x(i))−y(i))2
* Where m is the number of examples, hθ(x(i)) is the predicted value, and y(i) is the true value.
Underfitting and Overfitting
- Underfitting: The model is too simple to explain the variance.
* Example: Regression where Jtrain≈700 and Jtest≈700.
- Appropriate Fitting: "Just right" model performance.
* Example: Regression where Jtrain≈400 and Jtest≈400.
- Overfitting: The model is force-fitting the data; it is too good to be true.
* Example: Regression where Jtrain≈250 and Jtest≈800.
- Classification Visualization: Underfitting shows a line failing to separate classes; Appropriate fitting shows a curve separating classes; Overfitting shows an overly complex boundary capturing noise.
Methods to Deal with Overfitting
- Obtaining More Training Data: Increasing data helps generalize the model, reducing the gap between training and test loss (e.g., from Jtrain≈250,Jtest≈800 to Jtrain≈400,Jtest≈400).
- L2 Regularization:
* Modified Loss Function: J(θ)=2m1∑j=1m(hθ(x)(i)−y(i))2+2mλ∑i=1nθi2
* Impact of λ:
* When λ=0, the model may overfit.
* When λ=0.1, the resulting hypothesis function is smoothed, avoiding extreme values.
- Early Stopping:
* Incorrect Way: Loop while Jtest keeps reducing. This is wrong because it uses the test set for hyperparameter tuning.
* Correct Way: Loop while Jval (validation loss) keeps reducing. This preserves the test set for final evaluation.
Data Splitting and Hyperparameters
- Data Splitting: The sample is split into three distinct sets:
1. Training set: Used to optimize model parameters (θ).
2. Validation set: Used to optimize hyperparameters (Ψ).
3. Test set: Used exclusively for the final evaluation of the model.
- Hyperparameters: These include parameters that are not learned via gradient descent on the training set:
* Learning rate (α).
* Polynomial degree.
* Neural network architecture (layers, number of neurons, etc.).
* Number of iterations for the gradient method (early stopping).
Model Training Procedure
- Select a new hyperparameter configuration Ψ.
- Optimize model parameters (θ) on the training set using gradient descent.
- Evaluate the trained model on the validation set.
- Repeat steps 1-3 to find the best configuration.
- Final Results:
* Ψ<em>: The configuration with the best validation performance.
θ<em>: The trained parameters associated with Ψ</em>.
* Perform a final evaluation using θ<em> and Ψ</em> on the test set.
The Artificial Neuron Model
- Definition: An artificial neuron represents a multivariate logistic regression if the activation function g is a sigmoid function.
- Activation Function (g): Can be sigmoid or other functions.
- Expressive Power: A single neuron (with sigmoid) represents a single linear decision surface.
* In 2D (two input variables x1,x2), the decision boundary is a line.
* In higher dimensions, it is a hyperplane.
- IRIS Dataset Limitations: A single neuron (straight line boundary) is not sufficient to separate the "versicolor" category from others because the data is not linearly separable.
Software for Neural Networks
- NumPy: Supports array programming; CPU only.
- PyTorch: Supports array programming; CPU and GPU support; utilize computational graphs and automatic differentiation.
- Code Comparison (Logistic Regression Prediction):
* NumPy:
python
def __sigmoid(self, z):
return 1 / (1 + np.exp(-z) + self.eps)
h = self.__sigmoid(np.dot(X, self.theta))
* PyTorch:
python
def __sigmoid(self, z):
return 1 / (1 + torch.exp(-z) + self.eps)
h = self.__sigmoid(torch.mm(X, self.theta[:, None]))
* PyTorch with torch.nn:
python
z = torch.nn.Linear(X.shape[1], 1)(X)
h = torch.nn.functional.sigmoid(z)
- Code Comparison (Loss Calculation):
* PyTorch with torch.nn:
python
loss = torch.nn.BCELoss()(h, y)
Expressive Power of Neural Networks - Sequential Combination
- AND Operation Approximation:
* Decision boundary requires h(x)=1 only when both inputs are 1.
* Example parameters: w1=7,w2=7,b=−9.
- OR Operation Approximation:
* Example parameters: w1=7,w2=7,b=−5.
- Universal Approximation Theorem: A two-layer neural network with sigmoids can approximate any function to any degree with appropriate weights and enough neurons.
- The XOR Problem: The exclusive OR function is not linearly separable. A single neuron cannot solve XOR, but a multilayer network can.
* XOR weights example (first layer): w111=−7,w121=7,b11=−3 and w112=7,w122=−7,b12=−3.
Multilayer Perceptron (MLP)
- Structure: Building blocks of basic artificial neural networks.
* Input "Layer": No neurons or weights; just the input variables.
* Output "Layer": The final estimation (y^).
* Dense (Fully Connected) Layers: Each neuron is connected to every neuron in the preceding and succeeding layers.
- Notation:
* Θ: The set of all weight matrices (W) and bias vectors (b).
* Sk: Number of neurons in layer k.
* W∈RSk×Sk−1.
* b∈RSk.
- Hypothesis Function (Two-layer MLP):
y^=g2(W2×g1(W1×x+b1)+b2)
* Regression: g2 is often the identity function (h(x)=W2×(W1×x+b1)+b2); otherwise, expressive power remains linear.
* Nonlinearity: Without activation functions (nonlinearity), a multi-layer network collapses into a single linear regression.
Popular Activation Functions
- Sigmoid: 1+e−z1. Output range (0,1).
- tanh: Hyperbolic tangent. Output range (−1,1).
- ReLU (Rectified Linear Unit): f(z)=max(0,z). Easy to compute and highly effective.
Training an MLP
- Gradient Descent Algorithm:
repeat until convergence {
for each theta in Theta {
grad_theta = partial_derivative of J(Theta)
}
for each theta in Theta {
theta = theta - alpha * grad_theta
}
}
- Batch Gradient Descent: Computes the gradient over the entire dataset. This is computationally expensive.
- Stochastic Gradient Descent (SGD): Points are selected randomly in mini-batches to compute steps.
* Mini-batch Variance: Smaller mini-batches increase variance (noisy updates).
* Efficiency: Choose mini-batch sizes that fit in GPU memory.
* Learning Rate: If using small mini-batches, reduce the learning rate to ensure convergence.
- Optimization Variants: SGD with Momentum, AdaGrad, Adam, Adamax, RMSprop.
Multiple Label Variables (Vectorized Labels)
- Regression with Multiple Labels:
* y becomes a vector (e.g., estimating both cholesterol and blood sugar levels).
* Loss function averages squared loss over all elements: J(θ)=2m1∑i=1m∑j=1k(y^j(i)−yj(i))2.
- Multi-class Classification:
* Estimates a probability for each of k categories.
* Softmax Activation: σ(z)<em>i=∑</em>j=1kezjezi. Ensures the sum of output probabilities is 1.
- Cross-Entropy (CE) Loss:
J(θ)=−m1∑i=1m∑j=1kyj(i)ln(y^j(i))
* One-hot Encoding: The true label vector has a 1 at the correct category index and 0 elsewhere.
Application: MNIST Handwritten Digit Classification
- Dataset Details:
* 28×28 pixel images totaling 784 input variables.
* 10 categories (digits 0-9).
* 60,000 training examples and 10,000 test examples.
- PyTorch Implementation:
*
nn.CrossEntropyLoss() in PyTorch includes the Softmax activation automatically and expects categorical labels (performing one-hot conversion internally).
* PyTorch definition for multi-class classification:
python
class MyTwoLayerMLP(nn.Module):
def __init__(self, input_dim, h_dim):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(input_dim, h_dim),
nn.ReLU(),
nn.Linear(h_dim, k)
)
def forward(self, x):
return self.layers(x)
loss_fn = nn.CrossEntropyLoss()