please,didactically solve this Machine Learning exam. solve all steps and proceed with reasoning over all the exercises.
% compile 2 times
\documentclass[a4paper]{article}
\usepackage[solutions%show/hide the solutions
]{verifiche}
\usepackage{listings}
\lstset{basicstyle=\ttfamily,
literate=% Allow for German characters in lstlistings.
{Ö}{{"O}}1
{Ä}{{"A}}1
{Ü}{{"U}}1
{ß}{{\ss}}2
{ü}{{"u}}1
{ä}{{"a}}1
{ö}{{"o}}1
{á}{{'a}}1
{é}{{'e}}1
{à}{{'a}}1
{è}{{'e}}1
}
\usepackage[margin=3cm]{geometry}
\usepackage{lipsum}
%\usepackage{subfigure}
\usepackage{subcaption}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{amsmath}
\captionsetup{font=small, labelfont=bf}
\captionsetup[sub]{labelsep=period, subrefformat=brace}
\begin{document}
%\renewcommand{\institutefont}{\huge}
\renewcommand{\closedquestionitem}{◯}
\renewcommand{\headercandidatenamelabel}{First and last name}
\renewcommand{\headerclasslabel}{Student ID}
\renewcommand{\headerdatelabel}{}
\setlength{\daterulerlength}{0pt}
\setlength{\candidatenamerulerlength}{210pt}
\setlength{\classrulerlength}{65pt}
%\institute{}
\institute{}
\asyear[]{\centerline{\includegraphics[]{images/poliba.png}}}
\testtype{\normalsize{
\centerline{\textbf{FOUNDATIONS OF MACHINE LEARNING}}\
\centerline{\textbf{ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING} (ML TEST)}\
%\centerline{\textbf{MACHINE LEARNING AND ARTIFICIAL INTELLIGENCE} (ML TEST)}\
\centerline{\normalfont{Prof. Tommaso Di Noia}}\
\centerline{\normalfont{Academic Year 2024/2025 – Mid Term Exam}} %1st Middle Exam}}\
\centerline{\normalfont{06/11/2024}}}
}
\instruction{\vspace{-0.8em}}
\duration[Test duration:]{1,5 hours}
\printheading
%\centerline{\includegraphics[]{images/poliba.png}}
\pagestyle{verifiche}
\begin{esercizio}[label=Question]
Explain in detail the \textbf{differences} between supervised and unsupervised learning. Then, provide an example and list some algorithms for both cases.
\end{esercizio}
\begin{esercizio}[label=Question]
% Explain in detail what learning curves are and their link to the concept of bias and variance.
Explain in \textbf{detail} the concepts of bias and variance. Draw the relative learning curves.
% Explain in detail the splitting dataset techniques (Holdout, K-fold cross validation and Random subsampling)
%\openquestion[type=squares, height=9cm, linecolor=black!30]{} &pag 510 slide
\end{esercizio}
\begin{esercizio}[label=Question]%
Explain in \textbf{detail} the dataset splitting techniques and highlight the advantages of \textbf{each} of the possible techniques.
Assistant
% Illustrate the operation of a random forest by explicitly clarifying the role of the \textit{bootstrap} and \textit{bagging} mechanism.%\[1em]
%\openquestion[height=5cm, linecolor=black!30]{}
\end{esercizio}
%\openquestion[type=squares, height=8cm, linecolor=black!30]{}
%\[1em]
%\openquestion[type=squares, height=8cm, linecolor=black!30]{}
% \begin{esercizio}[label=Question]
% Derive the probabilistic interpretation of the linear regression model using the Maximum Likelihood Criterion. Prove that this is \textbf{equivalent} to the MSE loss function.
% \end{esercizio}
\begin{esercizio}[label=Question]
Derive the probabilistic interpretation of the linear regression model using the Maximum Likelihood Criterion. Prove that this is \textbf{equivalent} to the MSE loss function.
\end{esercizio}
% \begin{esercizio}[label=Question]
% \textcolor{red}{cambia con domanda su NN}
% Describe the Support Vector Machines (SVMs) algorithm: focus on the main \textbf{differences} with respect to the Logistic Regression model. Discuss how to select the right \textbf{kernel} for the classification task.
% \end{esercizio}
\begin{esercizio}[label=Question]
You are a professor and you have to explain to your colleagues what is a neural network. Describe it by answering to the following points: \
\begin{enumerate}
\item what is a neural network;
\item why (and when) one should employ a neural network instead of a Logistic Regression model for the classification task;
\item what is the forward propagation (focus on its purpose and how it works);
\item what is the backpropagation (focus on its purpose and how it works).
\end{enumerate}
\end{esercizio}
% In the figures below, each point is a sample in the dataset, while each curve represents a trained model on that samples for a regression task. Describe the situations depicted in each figure in terms of fitting, highlighting the models' characteristics. Then, for each model, draw the corresponding learning curves with respect to the error on the training set and test set and the epochs.
% %\openquestion[type=squares, height=9cm, linecolor=black!30]{} &pag 510 slide
% \begin{figure}[h!]
% \centering
% \begin{subfigure}[b]{0.2\textwidth}
% \centering
% \includegraphics[width=2.8cm]{images/underfitting.png}
% \caption{}
% \label{fig:image1}
% \end{subfigure}
% \quad
% \begin{subfigure}[b]{0.2\textwidth}
% \centering
% \includegraphics[width=2.8cm]{images/ok.png}
% \caption{}
% \label{fig:image2}
% \end{subfigure}
% \quad
% \begin{subfigure}[b]{0.2\textwidth}
% \centering
% \includegraphics[width=2.8cm]{images/overfitting.png}
% \caption{}
% \label{fig:image3}
% \end{subfigure}
% \end{figuzzzre}
\begin{esercizio}[label=Question]%
Briefly explain when computing quartiles is useful when building a machine learning model. Compute the quartiles for the following data: 12, 15, 18, 20, 22, 25, detailing the steps.
\end{esercizio}
\begin{esercizio}[label=Question]
Derive the solution of the Univariate Linear Regression with the Normal Equation.
\end{esercizio}
\begin{esercizio}[label=Question]
Explain the concept of regularization, highlighting the goal. Discuss the regularization approaches reporting the advantages and disadvantages of each of them.
\end{esercizio}
\begin{esercizio}[label=Question]
Consider the table below reporting the True Positive (TP), True Negative (TN), False Positive (FP), and False Negative (FN) values for different threshold values in a classification task. Build the related ROC curve. \
\begin{esercizio}[label=Question]%
Consider the following \textbf{linear regression} model: ( y = \theta_0 + \theta_1 x_1 + \theta_2 x_2 ). Assume that the current weights are ( \theta_0 = 1 ), ( \theta_1 = -0.5 ), ( \theta_2 = 0.8 ). Given the following set of samples ( (\mathbf{X}, \mathbf{y}) ), where each row in ( \mathbf{X} ) represents a data point and each entry in ( \mathbf{y} ) represents the corresponding target value: \
Compute the initial value of the loss function and a \textbf{single step} of Gradient Descent to update the ( \theta_i ) parameters with \textit{Full Batch} and in \textit{Stochastic} solution, using a learning rate ( \alpha = 0.05 ).
\end{esercizio}
\end{document}
Certainly! Below are detailed, step-by-step solutions to each of the exercises from your Machine Learning exam. Each solution aims to provide clear explanations and reasoning to help you understand the underlying concepts thoroughly.
Exercise 1
Explain in detail the differences between supervised and unsupervised learning. Then, provide an example and list some algorithms for both cases.
Solution
Supervised vs. Unsupervised Learning:
Supervised Learning:
Definition: In supervised learning, the model is trained on a labeled dataset. This means that each training example is paired with an output label.
Objective: The goal is to learn a mapping from inputs to outputs, enabling the model to predict the label for new, unseen data.
Use Cases: Classification (e.g., spam detection), regression (e.g., predicting house prices).
Unsupervised Learning:
Definition: Unsupervised learning involves training the model on data without labeled responses. The model tries to find inherent structures or patterns in the data.
Objective: To discover hidden patterns, group similar data points, reduce dimensionality, or identify anomalies.
Supervised: Predict outputs or classify data points.
Unsupervised: Discover patterns or structures within data.
Feedback:
Supervised: Receives feedback based on predictions vs. actual labels.
Unsupervised: No direct feedback on predictions since there are no labels.
Examples and Algorithms:
Supervised Learning Example:
Example: Email Spam Detection
Description: Classifying emails as 'spam' or 'not spam' based on features like the presence of certain keywords.
Algorithms:
Linear Regression: For predicting continuous values.
Logistic Regression: For binary classification tasks.
Support Vector Machines (SVM): For classification by finding the optimal hyperplane.
Decision Trees: For classification and regression by partitioning the data based on feature values.
Random Forests: An ensemble of decision trees for improved accuracy.
Neural Networks: For complex pattern recognition in data.
Unsupervised Learning Example:
Example: Customer Segmentation
Description: Grouping customers into segments based on purchasing behavior without predefined categories.
Algorithms:
K-Means Clustering: Partitions data into K distinct clusters based on distance metrics.
Hierarchical Clustering: Builds a hierarchy of clusters either agglomeratively or divisively.
Principal Component Analysis (PCA): Reduces dimensionality while preserving variance.
Independent Component Analysis (ICA): Separates a multivariate signal into additive independent components.
DBSCAN (Density-Based Spatial Clustering of Applications with Noise): Identifies clusters based on density.
Exercise 2
Explain in detail the concepts of bias and variance. Draw the relative learning curves.
Solution
Bias and Variance:
Understanding bias and variance is crucial in assessing the performance of machine learning models and diagnosing issues related to overfitting or underfitting.
1. Bias:
Definition: Bias refers to the error introduced by approximating a real-world problem, which may be complex, by a simplified model.
High Bias: Occurs when the model is too simple to capture the underlying patterns in the data (underfitting). It leads to poor performance on both training and test datasets.
Low Bias: Indicates that the model can capture the complexity of the data well.
2. Variance:
Definition: Variance measures how much the model's predictions fluctuate for different training datasets.
High Variance: Occurs when the model is too sensitive to the training data, capturing noise as if it were a true signal (overfitting). It leads to excellent performance on training data but poor generalization to unseen data.
Low Variance: The model's predictions are stable across different datasets.
Bias-Variance Trade-off:
There is an inherent trade-off between bias and variance. Increasing model complexity typically decreases bias but increases variance, and vice versa.
The goal is to find a balance where both bias and variance are minimized to achieve good generalization.
Learning Curves:
Learning curves plot model performance (e.g., error rate) against the number of training samples or training iterations (epochs). They help visualize bias and variance.
1. High Bias (Underfitting):
Training Error: High and similar to test error.
Test Error: High.
Curve Behavior: Both training and test errors are high and do not decrease with more data or training.
2. High Variance (Overfitting):
Training Error: Low.
Test Error: High.
Curve Behavior: Training error decreases and test error initially decreases then increases as the model overfits.
3. Low Bias and Low Variance (Good Fit):
Training Error: Low.
Test Error: Low and similar to training error.
Curve Behavior: Both training and test errors decrease and stabilize at a low level.
Illustration of Learning Curves:
(As I cannot draw here, I'll describe the typical plots.)
X-Axis: Training iterations or number of training samples.
Both training and test errors decrease and stabilize at low values.
Conclusion:
High Bias: Simplistic models; consider increasing model complexity.
High Variance: Complex models; consider regularization, more data, or simplifying the model.
Balanced Bias and Variance: Achieved with appropriate model complexity and sufficient data.
Exercise 3
Explain in detail the dataset splitting techniques and highlight the advantages of each of the possible techniques.
Solution
Dataset Splitting Techniques:
Splitting the dataset into training and testing (and sometimes validation) sets is essential for evaluating the performance of machine learning models. The primary techniques include:
Holdout Method
K-Fold Cross-Validation
Random Subsampling (Repeated Train-Test Splits)
1. Holdout Method:
Description:
The dataset is divided into two subsets: a training set and a test set.
Common split ratios include 70/30 or 80/20 (training/test).
Advantages:
Simplicity: Easy to implement.
Speed: Quick since the model is trained and evaluated only once.
Suitable for Large Datasets: When enough data is available, the split can adequately represent the entire dataset.
Disadvantages:
Variance in Performance: The model’s performance can vary significantly based on how the data is split.
Underutilization of Data: A portion of the data isn't used for training, which can be inefficient, especially with limited data.
2. K-Fold Cross-Validation:
Description:
The dataset is divided into 'K' equal-sized folds.
The model is trained 'K' times, each time using K-1 folds for training and the remaining fold for testing.
The final performance metric is averaged over the 'K' iterations.
Advantages:
Efficient Use of Data: Every data point is used for both training and testing, maximizing data utilization.
Reduced Variance: By averaging over 'K' trials, the performance estimate is more stable and reliable.
Flexibility: The value of 'K' can be adjusted based on the dataset size (common values: 5 or 10).
Disadvantages:
Computationally Expensive: Training the model 'K' times can be time-consuming, especially with complex models or large datasets.
Complexity: More involved to implement compared to the holdout method.
3. Random Subsampling (Repeated Train-Test Splits):
Description:
Multiple train-test splits are created by randomly selecting subsets.
The model is trained and evaluated on each split, and results are averaged.
Advantages:
Flexibility: Allows multiple evaluations, providing a broader assessment of model performance.
Reduced Variance: Similar to cross-validation, averaging results over multiple splits leads to more stable estimates.
Disadvantages:
Overlap Between Splits: Different splits may have overlapping data, which can lead to biased estimates.
Computational Cost: Similar to cross-validation, multiple trainings are required, increasing computational load.
Comparison and Selection:
Holdout Method: Best suited for large datasets where a single split can be representative. It's quick but less reliable for smaller datasets.
K-Fold Cross-Validation: Ideal for smaller to medium-sized datasets. It provides a more reliable estimate of model performance but at the cost of increased computation.
Random Subsampling: Offers flexibility and can be useful when model evaluation needs to be robust with multiple estimates. However, it's less consistent than cross-validation due to potential overlaps.
Choosing the Right Technique:
Dataset Size:
Large Datasets: Holdout method may suffice.
Small to Medium Datasets: K-Fold Cross-Validation is preferable to maximize data usage.
Computational Resources:
If computational resources are limited, the holdout method is more feasible.
Model Complexity:
For complex models, cross-validation ensures a more reliable performance estimate despite higher computational costs.
Conclusion:
Selecting the appropriate dataset splitting technique depends on the dataset size, computational resources, and the need for reliable performance estimates. K-Fold Cross-Validation is generally preferred for its balance between bias and variance in performance estimation, especially with limited data.
Exercise 4
Derive the probabilistic interpretation of the linear regression model using the Maximum Likelihood Criterion. Prove that this is equivalent to the MSE loss function.
Solution
Probabilistic Interpretation of Linear Regression:
Linear regression can be framed within a probabilistic framework by assuming that the target variable ( y ) is a linear function of the input features ( X ) plus some Gaussian noise.
Model Assumptions:
[
y = X\theta + \epsilon
]
where:
( y ) is the target variable.
( X ) is the input feature matrix.
( \theta ) are the parameters (weights) of the model.
( \epsilon ) is the noise term, assumed to follow a Gaussian distribution.
Assumption on Noise:
[
\epsilon \sim \mathcal{N}(0, \sigma^2)
]
Thus, the conditional distribution of ( y ) given ( X ) is:
[
p(y | X, \theta) = \mathcal{N}(X\theta, \sigma^2 I)
]
Maximum Likelihood Estimation (MLE):
MLE seeks to find the parameter ( \theta ) that maximizes the likelihood of the observed data. Given ( N ) independent observations, the likelihood is the product of individual probabilities:
From the MLE derivation, minimizing the negative log-likelihood is equivalent to minimizing ( \sum_{i=1}^{N} (y^{(i)} - X^{(i)}\theta)^2 ). Ignoring the constant ( \frac{1}{N} ) (since it does not affect the location of the minimum), the MSE loss function is directly proportional to the term we aim to minimize in MLE.
Conclusion:
Under the assumption of Gaussian noise in the linear regression model, the Maximum Likelihood Estimation leads to minimizing the sum of squared errors, which is equivalent to minimizing the Mean Squared Error (MSE) loss function. Thus, MLE for linear regression with Gaussian noise is equivalent to the standard MSE minimization.
Exercise 5
You are a professor and you have to explain to your colleagues what is a neural network. Describe it by answering the following points:
What is a neural network;
Why (and when) one should employ a neural network instead of a Logistic Regression model for the classification task;
What is the forward propagation (focus on its purpose and how it works);
What is the backpropagation (focus on its purpose and how it works).
Solution
1. What is a Neural Network:
A neural network is a computational model inspired by the structure and functioning of the human brain. It consists of interconnected layers of nodes, or "neurons," which process input data to perform tasks such as classification, regression, pattern recognition, and more.
Key Components:
Input Layer: Receives the initial data.
Hidden Layers: Intermediate layers that perform computations and feature transformations. The complexity and depth (number of layers) can vary.
Output Layer: Produces the final prediction or classification.
Weights and Biases: Each connection between neurons has an associated weight, and each neuron may have a bias term, which are adjusted during training.
Activation Functions: Non-linear functions applied to neuron outputs to introduce non-linearity into the model (e.g., ReLU, sigmoid, tanh).
Neural networks are capable of capturing complex relationships in data through their layered structure and non-linear transformations.
2. Why (and When) to Use a Neural Network Instead of Logistic Regression for Classification:
Logistic Regression:
Nature: A linear model used for binary or multi-class classification.
Limitation: Can only capture linear relationships between features and the target variable.
Neural Networks:
Nature: Can capture non-linear relationships through multiple layers and non-linear activation functions.
Advantages:
Flexibility: Handle complex patterns and interactions between features.
Feature Learning: Automatically learn and extract relevant features from raw data (especially in deep architectures).
Scalability: Effective for large datasets and high-dimensional data (e.g., images, text).
When to Prefer Neural Networks Over Logistic Regression:
Complex Patterns: When the relationship between input features and the target is non-linear.
High Dimensionality: Tasks involving high-dimensional inputs like images, audio, or text.
Large Datasets: Neural networks typically require more data to train effectively.
Performance Needs: When higher predictive performance is required and computational resources are available.
Example Scenario:
Image Classification: Neural networks, especially convolutional neural networks (CNNs), outperform logistic regression due to their ability to capture spatial hierarchies in image data.
3. What is Forward Propagation:
Purpose:
Forward propagation is the process by which input data passes through the neural network to generate an output. It involves computing the activations of each neuron layer by layer, starting from the input layer to the output layer.
How It Works:
Input Layer: Receive input features.
Hidden Layers:
Weighted Sum: For each neuron, compute the weighted sum of inputs plus bias:
[
z^{(l)} = W^{(l)} a^{(l-1)} + b^{(l)}
]
where ( W^{(l)} ) and ( b^{(l)} ) are the weights and biases for layer ( l ), and ( a^{(l-1)} ) are activations from the previous layer.
Activation Function: Apply a non-linear activation function to ( z^{(l)} ) to get the activation ( a^{(l)} ):
[
a^{(l)} = \sigma(z^{(l)})
]
Output Layer: Produce the final output using the same process, typically with an activation function suited to the task (e.g., sigmoid for binary classification).
Purpose:
Backpropagation is the training algorithm used to update the weights and biases of the neural network. It minimizes the loss function by calculating the gradient of the loss with respect to each weight through the chain rule of calculus.
How It Works:
Compute Loss: After forward propagation, compute the loss (e.g., cross-entropy, mean squared error) between the predicted output and the actual target.
Compute Gradients:
Output Layer Gradients: Calculate the derivative of the loss with respect to the activations and then with respect to the weights and biases.
Hidden Layers Gradients: Propagate the gradient back through each layer, computing derivatives with respect to activations, weights, and biases.
Apply the Chain Rule: Use the chain rule to systematically compute gradients layer by layer from the output back to the input.
Update Weights and Biases: Adjust the weights and biases in the opposite direction of the gradients to minimize the loss:
[
W^{(l)} = W^{(l)} - \alpha \frac{\partial \text{Loss}}{\partial W^{(l)}}
]
[
b^{(l)} = b^{(l)} - \alpha \frac{\partial \text{Loss}}{\partial b^{(l)}}
]
where ( \alpha ) is the learning rate.
Example Flow:
Step 1: Forward propagate inputs to compute predictions.
Step 2: Compute the loss between predictions and true labels.
Step 3: Backpropagate the loss to compute gradients for all weights and biases.
Step 4: Update weights and biases using the computed gradients.
Step 5: Repeat the process for multiple iterations (epochs) until convergence.
Key Points:
Efficiency: Backpropagation efficiently computes gradients by reusing intermediate calculations from forward propagation.
Optimization: It is typically combined with optimization algorithms like Gradient Descent, Adam, or RMSprop to update parameters.
Layer-Wise Updates: Gradients are computed separately for each layer, enabling precise updates to the network parameters.
Conclusion:
Forward propagation and backpropagation work hand-in-hand in training neural networks. Forward propagation generates predictions, while backpropagation adjusts the network parameters to minimize the prediction error, enabling the network to learn from data effectively.
Exercise 6
Briefly explain when computing quartiles is useful when building a machine learning model. Compute the quartiles for the following data: 12, 15, 18, 20, 22, 25, detailing the steps.
Solution
Usefulness of Computing Quartiles in Machine Learning:
Quartiles are statistical measures that divide a dataset into four equal parts, providing insights into the data distribution. Computing quartiles is useful in various aspects of building machine learning models:
Data Exploration and Visualization:
Understanding Distribution: Helps in understanding the spread and central tendency of the data.
Identifying Outliers: Quartiles, especially the interquartile range (IQR), are used to detect outliers.
Feature Engineering:
Binning: Splitting continuous variables into categorical features based on quartiles can capture non-linear relationships.
Normalization: Understanding data distribution aids in choosing appropriate normalization or scaling techniques.
Robust Statistical Measures:
Handling Skewness: Quartiles are less affected by skewed data compared to mean and standard deviation.
Model Evaluation:
Performance Metrics: Quartiles can help in assessing the distribution of prediction errors.
Computing Quartiles:
Given the dataset: 12, 15, 18, 20, 22, 25
Steps:
Order the Data:
Confirm the data is in ascending order: 12, 15, 18, 20, 22, 25
Determine Positions of Quartiles:
Number of Data Points (N): 6
First Quartile (Q1): 25th percentile
[
Q1 = \text{Value at } \frac{1}{4}(N + 1) = \text{Value at } \frac{1}{4}(7) = 1.75^{th} \text{ position}
]
Calculation:
The 1st value: 12
The 2nd value: 15
0.75 between the 1st and 2nd value:
[
Q1 = 12 + 0.75 \times (15 - 12) = 12 + 0.75 \times 3 = 12 + 2.25 = 14.25
]
Median (Q2): 50th percentile
[
Q2 = \text{Value at } \frac{2}{4}(N + 1) = \text{Value at } 3.5^{th} \text{ position}
]
Calculation:
The 3rd value: 18
The 4th value: 20
0.5 between the 3rd and 4th value:
[
Q2 = 18 + 0.5 \times (20 - 18) = 18 + 1 = 19
]
Third Quartile (Q3): 75th percentile
[
Q3 = \text{Value at } \frac{3}{4}(N + 1) = \text{Value at } 5.25^{th} \text{ position}
]
Calculation:
The 5th value: 22
The 6th value: 25
0.25 between the 5th and 6th value:
[
Q3 = 22 + 0.25 \times (25 - 22) = 22 + 0.75 = 22.75
]
Summary of Quartiles:
Q1 (25th percentile): 14.25
Q2 (Median or 50th percentile): 19
Q3 (75th percentile): 22.75
Conclusion:
Computing quartiles provides valuable insights into the distribution of data, which is essential for data preprocessing, identifying outliers, and making informed decisions during feature engineering in machine learning models.
Exercise 7
Derive the solution of the Univariate Linear Regression with the Normal Equation.
Solution
Univariate Linear Regression:
In univariate linear regression, we model the relationship between a single feature ( x ) and the target variable ( y ) as:
[
y = \theta_0 + \theta_1 x + \epsilon
]
where:
( \theta_0 ) is the intercept.
( \theta_1 ) is the slope.
( \epsilon ) is the error term.
Objective:
Find the parameters ( \theta = [\theta_0, \theta_1]^T ) that minimize the cost function, typically the Mean Squared Error (MSE):
The Normal Equation provides a closed-form solution to find the optimal ( \theta ) that minimizes the cost function without iterative methods like Gradient Descent.
Steps to Derive the Normal Equation:
Matrix Representation:
For multiple linear regression (including univariate), we can express the model in matrix form:
[
y = X\theta + \epsilon
]
Where:
( y ) is an ( N \times 1 ) vector of target values.
( X ) is an ( N \times 2 ) matrix where the first column consists of ones (for the intercept), and the second column contains the feature values.
( \theta ) is a ( 2 \times 1 ) vector of parameters.
For a ( 2 \times 2 ) matrix:
[
M = \begin{bmatrix}
a & b \
c & d
\end{bmatrix}, \quad M^{-1} = \frac{1}{ad - bc} \begin{bmatrix}
d & -b \
-c & a
\end{bmatrix}
]
Applying to ( X^T X ):
[
(X^T X)^{-1} = \frac{1}{N S_{xx} - (S_x)^2} \begin{bmatrix}
S_{xx} & -S_x \
-S_x & N
\end{bmatrix}
]
( \theta_0 ) (Intercept): Represents the expected value of ( y ) when ( x = 0 ).
( \theta_1 ) (Slope): Represents the change in ( y ) for a one-unit change in ( x ).
Conclusion:
Using the Normal Equation, we derive a closed-form solution for the parameters of a univariate linear regression model. This method efficiently computes the optimal ( \theta ) that minimizes the Mean Squared Error without the need for iterative optimization algorithms.
Exercise 8
Explain the concept of regularization, highlighting the goal. Discuss the regularization approaches reporting the advantages and disadvantages of each of them.
Solution
Concept of Regularization:
Regularization refers to a set of techniques used to prevent overfitting in machine learning models by adding additional information or constraints. The primary goal is to improve the model's generalization ability to unseen data by penalizing complexity.
Goal:
Prevent Overfitting: Ensure that the model captures the underlying data patterns without fitting the noise.
Improve Generalization: Enhance the model's performance on new, unseen data.
Feature Selection/Sparsity: Encourage the model to use fewer features or simpler structures, leading to more interpretable models.
Common Regularization Approaches:
L1 Regularization (Lasso)
L2 Regularization (Ridge)
Elastic Net
Dropout (in Neural Networks)
Early Stopping
1. L1 Regularization (Lasso - Least Absolute Shrinkage and Selection Operator):
Definition:
Adds a penalty equal to the absolute value of the magnitude of coefficients.
[
\text{Cost Function: } J(\theta) = \text{MSE} + \lambda \sum_{j=1}^{p} |\theta_j|
]
Advantages:
Feature Selection: Can shrink some coefficients to exactly zero, effectively performing feature selection.
Sparse Models: Results in simpler, more interpretable models.
Disadvantages:
Bias Introduction: Introduces bias into the model estimates.
Stability Issues: May select different features when data varies slightly.
Not Always Effective with Highly Correlated Features: In scenarios with highly correlated predictors, Lasso may arbitrarily select one and ignore others.
2. L2 Regularization (Ridge):
Definition:
Adds a penalty equal to the square of the magnitude of coefficients.
[
\text{Cost Function: } J(\theta) = \text{MSE} + \lambda \sum_{j=1}^{p} \theta_j^2
]
Advantages:
Handles Multicollinearity: Distributes coefficient weights among correlated features, reducing variance.
Stable Estimates: Provides more stable estimates when predictors are highly correlated.
No Feature Selection: Retains all features, which can be beneficial when all features are relevant.
Disadvantages:
No Sparse Solutions: Does not set coefficients to zero, hence no inherent feature selection.
Interpretability: Less interpretable when dealing with many correlated features since all are retained with smaller coefficients.
Feature Selection and Regularization: Benefits from both Lasso's feature selection and Ridge's coefficient shrinkage.
Handles Correlated Features: Effectively selects groups of correlated features.
Disadvantages:
Complexity: Requires tuning two hyperparameters (( \lambda_1 ) and ( \lambda_2 )).
Computationally Intensive: More complex to implement and compute compared to Lasso or Ridge alone.
4. Dropout (in Neural Networks):
Definition:
Randomly "drops out" (sets to zero) a fraction of neurons during training to prevent co-adaptation.
Advantages:
Prevents Overfitting: Forces the network to learn redundant representations, enhancing generalization.
Simplifies Network: Reduces reliance on specific neurons, leading to more robust feature extraction.
Disadvantages:
Training Time: May require more epochs to converge.
Not Suitable for All Architectures: Less effective for certain types of neural networks or tasks.
5. Early Stopping:
Definition:
Monitors the model's performance on a validation set and stops training when performance stops improving.
Advantages:
Prevents Overfitting: Stops the model before it starts to learn noise from the training data.
Simple to Implement: Does not require modifying the model's architecture or adding penalties.
Disadvantages:
Requires a Validation Set: Necessitates held-out data, which reduces the training data.
Timing Sensitivity: Determining the exact point to stop training can be challenging and may require careful monitoring.
Summary of Regularization Techniques:
Regularization Technique
Type
Advantages
Disadvantages
L1 (Lasso)
Parameterwise
Feature selection, sparse models
No feature selection with correlated features, introduces bias
L2 (Ridge)
Parameterwise
Handles multicollinearity, stable estimates
No sparse solutions, less interpretable with many features
Elastic Net
Parameterwise
Combines L1 and L2 benefits, handles correlated features
More complex, requires tuning multiple hyperparameters
Dropout
Structural
Prevents overfitting in neural networks
Increases training time, not suitable for all architectures
Early Stopping
Training
Simple, prevents overfitting
Requires validation set, sensitive to stopping criteria
Conclusion:
Regularization is essential in machine learning to enhance model generalization and prevent overfitting. The choice of regularization technique depends on the specific problem, data characteristics, and model complexity. Understanding the trade-offs associated with each approach allows for informed decisions to achieve optimal model performance.
Exercise 9
Consider the table below reporting the True Positive (TP), True Negative (TN), False Positive (FP), and False Negative (FN) values for different threshold values in a classification task. Build the related ROC curve.
Threshold
TP
TN
FP
FN
0.1
32
40
8
20
0.2
30
42
6
22
0.3
28
44
4
24
0.4
26
46
2
26
Solution
Building the ROC Curve:
The Receiver Operating Characteristic (ROC) curve is a graphical representation of a classifier's performance across different threshold settings. It plots the True Positive Rate (TPR) against the False Positive Rate (FPR) at various threshold levels.
While an actual plot cannot be drawn here, here's a description of how to connect the points:
Start at (0,0).
Connect to (0.042, 0.500).
Then to (0.083, 0.538).
Then to (0.125, 0.577).
Then to (0.167, 0.615).
Finally to (1,1).
The curve should be a monotonically increasing function from (0,0) to (1,1).
Interpretation:
AUC (Area Under the Curve): Represents the likelihood that the classifier ranks a random positive instance higher than a random negative one.
Closer to (0,1): Indicates better performance.
Diagonal Line (Chance Level): Represents a non-informative classifier (AUC = 0.5).
Conclusion:
The ROC curve constructed from the given data points illustrates the trade-off between TPR and FPR at various threshold levels. An optimal classifier would aim for TPR = 1 and FPR = 0, placing the ROC curve close to the top-left corner.
Exercise 10
Consider the following linear regression model: ( y = \theta_0 + \theta_1 x_1 + \theta_2 x_2 ). Assume that the current weights are ( \theta_0 = 1 ), ( \theta_1 = -0.5 ), ( \theta_2 = 0.8 ). Given the following set of samples ( (\mathbf{X}, \mathbf{y}) ), where each row in ( \mathbf{X} ) represents a data point and each entry in ( \mathbf{y} ) represents the corresponding target value:
Compute the initial value of the loss function and a single step of Gradient Descent to update the ( \theta_i ) parameters with Full Batch and in Stochastic solution, using a learning rate ( \alpha = 0.05 ).
Full Batch GD: Utilizes the entire dataset to compute the gradients, leading to a more averaged update.
Stochastic GD: Updates parameters incrementally with each sample, which can lead to faster convergence but may introduce more variability in the updates.
Conclusion:
Both full batch and stochastic gradient descent methods aim to minimize the loss function by iteratively updating the model parameters. The choice between them depends on factors such as dataset size, computational resources, and desired convergence properties. Full batch GD provides stable updates, while SGD offers speed and the ability to escape local minima due to its stochastic nature.