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)(input, label) pairs.
  • Task: The estimation of the label (the expected output) from the input.
  • Hypothesis Function: We search for a function hθh_{\theta} such that hθ(x)≈yh_{\theta}(x) \approx 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)((X^T \times X + \lambda \times L)^{-1} \times X^T \times y)

Polynomial Regression and Loss Functions

  • Hypothesis Functions:     * Univariate: hθ(x)=θ0+θ1×x+θ2×x2+…h_{\theta}(x) = \theta_0 + \theta_1 \times x + \theta_2 \times x^2 + \dots     * Multivariate Example: hθ(x)=θ0+θ1×x1+θ2×x2+θ3×x12+θ4×x22+θ5×x1×x2+…h_{\theta}(x) = \theta_0 + \theta_1 \times x_1 + \theta_2 \times x_2 + \theta_3 \times x_1^2 + \theta_4 \times x_2^2 + \theta_5 \times x_1 \times x_2 + \dots
  • Loss Function (Mean Squared Error - MSE):     J(θ)=12m∑j=1m(y^(j)−y(j))2=12m∑i=1m(hθ(x(i))−y(i))2J(\theta) = \frac{1}{2m} \sum_{j=1}^{m} (\hat{y}^{(j)} - y^{(j)})^2 = \frac{1}{2m} \sum_{i=1}^{m} (h_{\theta}(x^{(i)}) - y^{(i)})^2     * Where mm is the number of examples, hθ(x(i))h_{\theta}(x^{(i)}) is the predicted value, and y(i)y^{(i)} is the true value.

Underfitting and Overfitting

  • Underfitting: The model is too simple to explain the variance.     * Example: Regression where Jtrain≈700J_{train} \approx 700 and Jtest≈700J_{test} \approx 700.
  • Appropriate Fitting: "Just right" model performance.     * Example: Regression where Jtrain≈400J_{train} \approx 400 and Jtest≈400J_{test} \approx 400.
  • Overfitting: The model is force-fitting the data; it is too good to be true.     * Example: Regression where Jtrain≈250J_{train} \approx 250 and Jtest≈800J_{test} \approx 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≈800J_{train} \approx 250, J_{test} \approx 800 to Jtrain≈400,Jtest≈400J_{train} \approx 400, J_{test} \approx 400).
  • L2 Regularization:     * Modified Loss Function: J(θ)=12m∑j=1m(hθ(x)(i)−y(i))2+λ2m∑i=1nθi2J(\theta) = \frac{1}{2m} \sum_{j=1}^{m} (h_{\theta}(x)^{(i)} - y^{(i)})^2 + \frac{\lambda}{2m} \sum_{i=1}^{n} \theta_i^2     * Impact of λ\lambda:         * When λ=0\lambda = 0, the model may overfit.         * When λ=0.1\lambda = 0.1, the resulting hypothesis function is smoothed, avoiding extreme values.
  • Early Stopping:     * Incorrect Way: Loop while JtestJ_{test} keeps reducing. This is wrong because it uses the test set for hyperparameter tuning.     * Correct Way: Loop while JvalJ_{val} (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 (θ\theta).     2. Validation set: Used to optimize hyperparameters (Ψ\Psi).     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 (α\alpha).     * Polynomial degree.     * Neural network architecture (layers, number of neurons, etc.).     * Number of iterations for the gradient method (early stopping).

Model Training Procedure

  1. Select a new hyperparameter configuration Ψ\Psi.
  2. Optimize model parameters (θ\theta) on the training set using gradient descent.
  3. Evaluate the trained model on the validation set.
  4. Repeat steps 1-3 to find the best configuration.
  5. Final Results:     * Ψ<em>\Psi^{<em>}: The configuration with the best validation performance.      θ<em>\theta^{<em>}: The trained parameters associated with Ψ</em>\Psi^{</em>}.     * Perform a final evaluation using θ<em>\theta^{<em>} and Ψ</em>\Psi^{</em>} on the test set.

The Artificial Neuron Model

  • Definition: An artificial neuron represents a multivariate logistic regression if the activation function gg is a sigmoid function.
  • Activation Function (gg): 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,x2x_1, x_2), 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)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     * PyTorch: python def __sigmoid(self, z): return 1 / (1 + torch.exp(-z) + self.eps) h = self.__sigmoid(torch.mm(X, self.theta[:, None])) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     * PyTorch with torch.nn: python z = torch.nn.Linear(X.shape[1], 1)(X) h = torch.nn.functional.sigmoid(z) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  • Code Comparison (Loss Calculation):     * PyTorch with torch.nn: python loss = torch.nn.BCELoss()(h, y) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Expressive Power of Neural Networks - Sequential Combination

  • AND Operation Approximation:     * Decision boundary requires h(x)=1h(x) = 1 only when both inputs are 1.     * Example parameters: w1=7,w2=7,b=−9w_1 = 7, w_2 = 7, b = -9.
  • OR Operation Approximation:     * Example parameters: w1=7,w2=7,b=−5w_1 = 7, w_2 = 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=−3w_{111} = -7, w_{121} = 7, b_{11} = -3 and w112=7,w122=−7,b12=−3w_{112} = 7, w_{122} = -7, b_{12} = -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^\hat{y}).     * Dense (Fully Connected) Layers: Each neuron is connected to every neuron in the preceding and succeeding layers.
  • Notation:     * Θ\Theta: The set of all weight matrices (WW) and bias vectors (bb).     * SkS_k: Number of neurons in layer kk.     * W∈RSk×Sk−1W \in \mathbb{R}^{S_k \times S_{k-1}}.     * b∈RSkb \in \mathbb{R}^{S_k}.
  • Hypothesis Function (Two-layer MLP):     y^=g2(W2×g1(W1×x+b1)+b2)\hat{y} = g_2(W_2 \times g_1(W_1 \times x + b_1) + b_2)     * Regression: g2g_2 is often the identity function (h(x)=W2×(W1×x+b1)+b2h(x) = W_2 \times (W_1 \times x + b_1) + b_2); otherwise, expressive power remains linear.     * Nonlinearity: Without activation functions (nonlinearity), a multi-layer network collapses into a single linear regression.

Popular Activation Functions

  • Sigmoid: 11+e−z\frac{1}{1 + e^{-z}}. Output range (0,1)(0, 1).
  • tanh: Hyperbolic tangent. Output range (−1,1)(-1, 1).
  • ReLU (Rectified Linear Unit): f(z)=max⁡(0,z)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 } } &nbsp;&nbsp;&nbsp;&nbsp;
  • 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:     * yy becomes a vector (e.g., estimating both cholesterol and blood sugar levels).     * Loss function averages squared loss over all elements: J(θ)=12m∑i=1m∑j=1k(y^j(i)−yj(i))2J(\theta) = \frac{1}{2m} \sum_{i=1}^{m} \sum_{j=1}^{k} (\hat{y}_j^{(i)} - y_j^{(i)})^2.
  • Multi-class Classification:     * Estimates a probability for each of kk categories.     * Softmax Activation: σ(z)<em>i=ezi∑</em>j=1kezj\sigma(z)<em>i = \frac{e^{z_i}}{\sum</em>{j=1}^{k} e^{z_j}}. Ensures the sum of output probabilities is 1.
  • Cross-Entropy (CE) Loss:     J(θ)=−1m∑i=1m∑j=1kyj(i)ln⁡(y^j(i))J(\theta) = - \frac{1}{m} \sum_{i=1}^{m} \sum_{j=1}^{k} y_j^{(i)} \ln(\hat{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×2828 \times 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() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;