This commit is contained in:
Morten Hjorth-Jensen
2025-09-01 08:26:37 +02:00
parent 2015cf2c36
commit 7bcccbbf71
39 changed files with 1492 additions and 2 deletions
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,360 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "7d56b2d5",
"metadata": {
"editable": true
},
"source": [
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
"doconce format html exercisesweek37.do.txt -->\n",
"<!-- dom:TITLE: Exercises week 36 -->"
]
},
{
"cell_type": "markdown",
"id": "c7a8e9c7",
"metadata": {
"editable": true
},
"source": [
"# Exercises week 36\n",
"**Implementing gradient descent for Ridge and ordinary Least Squares Regression**\n",
"\n",
"Date: **September 8-12, 2025**"
]
},
{
"cell_type": "markdown",
"id": "cf8f0ecb",
"metadata": {
"editable": true
},
"source": [
"## Learning goals\n",
"\n",
"After having completed these exercises you will have:\n",
"1. Your own code for the implementation of the simplest gradient descent approach applied to ordinary least squares (OLS) and Ridge regression\n",
"\n",
"2. Be able to compare the analytical expressions for OLS and Rudge regression with the gradient descent approach\n",
"\n",
"3. Explore the role of the learning rate in the gradient descent approach and the hyperparameter $\\lambda$ in Ridge regression\n",
"\n",
"4. Scale the data properly"
]
},
{
"cell_type": "markdown",
"id": "a67ae548",
"metadata": {
"editable": true
},
"source": [
"## Ridge regression and a new Synthetic Dataset\n",
"\n",
"We create a synthetic linear regression dataset with a sparse\n",
"underlying relationship. This means we have many features but only a\n",
"few of them actually contribute to the target. In our example, well\n",
"use 10 features with only 3 non-zero weights in the true model. This\n",
"way, the target is generated as a linear combination of a few features\n",
"(with known coefficients) plus some random noise. The steps we include are:\n",
"\n",
"Decide on the number of samples and features (e.g. 100 samples, 10 features).\n",
"Define the **true** coefficient vector with mostly zeros (for sparsity). For example, we set $\\hat{\\boldsymbol{\\theta}} = [5.0, -3.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0]$, meaning only features 0, 1, and 6 have a real effect on y.\n",
"\n",
"Then we sample feature values for $\\boldsymbol{X}$ randomly (e.g. from a normal distribution). We use a normal distribution so features are roughly centered around 0.\n",
"Then we compute the target values $y$ using the linear combination $\\boldsymbol{X}\\hat{\\boldsymbol{\\theta}}$ and add some noise (to simulate measurement error or unexplained variance).\n",
"\n",
"Below is the code to generate the dataset:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "f2d4a55d",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"# Set random seed for reproducibility\n",
"np.random.seed(0)\n",
"\n",
"# Define dataset size\n",
"n_samples = 100\n",
"n_features = 10\n",
"\n",
"# Define true coefficients (sparse linear relationship)\n",
"theta_true = np.array([5.0, -3.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0])\n",
"\n",
"# Generate feature matrix X (n_samples x n_features) with random values\n",
"X = np.random.randn(n_samples, n_features) # standard normal distribution\n",
"\n",
"# Generate target values y with a linear combination of X and theta_true, plus noise\n",
"noise = 0.5 * np.random.randn(n_samples) # Gaussian noise\n",
"y = X.dot @ theta_true + noise"
]
},
{
"cell_type": "markdown",
"id": "a445583b",
"metadata": {
"editable": true
},
"source": [
"This code produces a dataset where only features 0, 1, and 6\n",
"significantly influence $\\boldsymbol{y}$. The rest of the features have zero true\n",
"coefficient, so they only contribute noise. For example, feature 0 has\n",
"a true weight of 5.0, feature 1 has -3.0, and feature 6 has 2.0, so\n",
"the expected relationship is:"
]
},
{
"cell_type": "markdown",
"id": "4a81ddf9",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"y \\approx 5 \\times X_0 \\;-\\; 3 \\times X_1 \\;+\\; 2 \\times X_6 \\;+\\; \\text{noise}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "ae590275",
"metadata": {
"editable": true
},
"source": [
"## Exercise 1, scale your data\n",
"\n",
"Before fitting a regression model, it is good practice to normalize or\n",
"standardize the features. This ensures all features are on a\n",
"comparable scale, which is especially important when using\n",
"regularization. Here we will perform standardization, scaling each\n",
"feature to have mean 0 and standard deviation 1:\n",
"\n",
"Compute the mean and standard deviation of each column (feature) in $bm{X}$.\n",
"Subtract the mean and divide by the standard deviation for each feature.\n",
"\n",
"We will also center the target $\\boldsymbol{y}$ to mean $0$. Centering $\\boldsymbol{y}$\n",
"(and each feature) means the model wont require a separate intercept\n",
"term the data is shifted such that the intercept is effectively 0\n",
". (In practice, one could include an intercept in the model and not\n",
"penalize it, but here we simplify by centering.)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "8b40c47a",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Standardize features (zero mean, unit variance for each feature)\n",
"X_mean = X.mean(axis=0)\n",
"X_std = X.std(axis=0)\n",
"X_std[X_std == 0] = 1 # safeguard to avoid division by zero for constant features\n",
"X_norm = (X - X_mean) / X_std\n",
"\n",
"# Center the target to zero mean (optional, to simplify intercept handling)\n",
"y_mean = ?\n",
"y_centered = ?"
]
},
{
"cell_type": "markdown",
"id": "ff9c0c81",
"metadata": {
"editable": true
},
"source": [
"### 1a)\n",
"\n",
"Fill in the necessary details.\n",
"\n",
"After this preprocessing, each column of $\\boldsymbol{X}_norm$ has mean zero and standard deviation $1$\n",
"and $\\boldsymbol{y}_centered$ has mean 0. This makes the optimization landscape\n",
"nicer and ensures the regularization penalty $\\lambda \\sum_j\n",
"\\beta_j^2$ treats each coefficient fairly (since features are on the\n",
"same scale)."
]
},
{
"cell_type": "markdown",
"id": "d27c70e4",
"metadata": {
"editable": true
},
"source": [
"## Exercise 2, use the analytical formulae for OLS and Ridge regression to find the optimal paramters $\\boldsymbol{theta}$"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "9f1e5184",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Set regularization parameter, either a single value or a vector of values\n",
"lambda = ?\n",
"\n",
"# Analytical form for OLS and Ridge solution: theta_Ridge = (X^T X + lambda * I)^{-1} X^T y and theta_OLS = (X^T X)^{-1} X^T y\n",
"I = np.eye(n_features)\n",
"theta_closed_formRidge = ?\n",
"theta_closed_formOLS = ?\n",
"\n",
"print(\"Closed-form Ridge coefficients:\", theta_closed_form)\n",
"print(\"Closed-form OLS coefficients:\", theta_closed_form)"
]
},
{
"cell_type": "markdown",
"id": "2ec556b9",
"metadata": {
"editable": true
},
"source": [
"This computes the ridge and OLS regression coefficients directly. The identity\n",
"matrix $I$ has the same size as $X^T X$ (which is n_features x\n",
"n_features), and lam * I adds $\\lambda$ to the diagonal of $X^T X. We\n",
"then invert this matrix and multiply by $X^T y. The result\n",
"for $\\boldsymbol{\\theta}$ is a NumPy array of shape (n_features,) containing the\n",
"fitted weights."
]
},
{
"cell_type": "markdown",
"id": "a821f0c5",
"metadata": {
"editable": true
},
"source": [
"### 2a)\n",
"\n",
"Finalize the OLS and Ridge regression determination of the optimal parameters $bm{\\theta}$."
]
},
{
"cell_type": "markdown",
"id": "d637130e",
"metadata": {
"editable": true
},
"source": [
"### 2b)\n",
"\n",
"Explore the results as function of different values of the hyperparameter $\\lambda$. See for example exercise 4 from week 36."
]
},
{
"cell_type": "markdown",
"id": "b455ce7e",
"metadata": {
"editable": true
},
"source": [
"## Implementing the simplest form for gradient descent\n",
"\n",
"Alternatively, we can fit the ridge regression model using gradient\n",
"descent. This is useful to visualize the iterative convergence and is\n",
"necessary if $n$ and $p$ are so large that the closed-form might be\n",
"too slow or memory-intensive. We derive the gradients from the cost\n",
"functions defined above. Use the gradients of the Ridge and OLS cost functions with respect to\n",
"the parameters $\\boldsymbol{\\theta}$ and set up (using the template below) your own gradient descent code for OLS and Ridge regression.\n",
"\n",
"Below is a template code for gradient descent implementation of ridge:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "cfa1eb29",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Gradient descent parameters, learning rate eta first\n",
"eta = 0.1\n",
"# Then number of iterations\n",
"num_iters = 1000\n",
"\n",
"# Initialize weights for gradient descent\n",
"theta = np.zeros(n_features)\n",
"\n",
"# Arrays to store history for plotting\n",
"cost_history = np.zeros(num_iters)\n",
"\n",
"# Gradient descent loop\n",
"m = n_samples # number of examples\n",
"for t in range(num_iters):\n",
" # Compute prediction error\n",
" error = X_norm.dot(theta) - y_centered \n",
" # Compute cost for OLS and Ridge (MSE + regularization for Ridge) for monitoring\n",
" cost_OLS = ?\n",
" cost_Ridge = ?\n",
" cost_history[t] = ?\n",
" # Compute gradients for OSL and Ridge\n",
" grad_OLS = ?\n",
" grad_Ridge = ?\n",
" # Update parameters theta\n",
" theta_gdOLS = ?\n",
" theta_gdRidge = ? \n",
"\n",
"# After the loop, theta contains the fitted coefficients\n",
"theta_gdOLS = ?\n",
"theta_gdRidge = ?\n",
"print(\"Gradient Descent OLS coefficients:\", theta_gdOLS)\n",
"print(\"Gradient Descent Ridge coefficients:\", theta_gdRidge)"
]
},
{
"cell_type": "markdown",
"id": "dc78d58d",
"metadata": {
"editable": true
},
"source": [
"### 3a)\n",
"\n",
"Discuss the results as function of the learning rate paramaters and the number of iterations."
]
},
{
"cell_type": "markdown",
"id": "15060acb",
"metadata": {
"editable": true
},
"source": [
"### 3b)\n",
"\n",
"Add a stopping parameter as function of the number iterations. \n",
"\n",
"If everything worked correctly, the learned coefficients should be\n",
"close to the true values [5.0, -3.0, 0.0, …, 2.0, …] that we used to\n",
"generate the data. Keep in mind that due to regularization and noise,\n",
"the learned values will not exactly equal the true ones, but they\n",
"should be in the same ballpark."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -227,6 +227,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1 current active"><a class="current reference internal" href="#">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -0,0 +1,730 @@
<!DOCTYPE html>
<html lang="en" data-content_root="./" >
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Exercises week 36 &#8212; Applied Data Analysis and Machine Learning</title>
<script data-cfasync="false">
document.documentElement.dataset.mode = localStorage.getItem("mode") || "";
document.documentElement.dataset.theme = localStorage.getItem("theme") || "";
</script>
<!-- Loaded before other Sphinx assets -->
<link href="_static/styles/theme.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="_static/styles/bootstrap.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="_static/styles/pydata-sphinx-theme.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="_static/vendor/fontawesome/6.5.2/css/all.min.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.5.2/webfonts/fa-solid-900.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.5.2/webfonts/fa-brands-400.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.5.2/webfonts/fa-regular-400.woff2" />
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=fa44fd50" />
<link rel="stylesheet" type="text/css" href="_static/styles/sphinx-book-theme.css?v=eba8b062" />
<link rel="stylesheet" type="text/css" href="_static/togglebutton.css?v=13237357" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.8ecb98da25f57f5357bf6f572d296f466b2cfe2517ffebfabe82451661e28f02.css?v=6644e6bb" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css?v=4fa983c6" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-design.min.css?v=95c83b7e" />
<!-- Pre-loaded scripts that we'll load fully later -->
<link rel="preload" as="script" href="_static/scripts/bootstrap.js?digest=dfe6caa3a7d634c4db9b" />
<link rel="preload" as="script" href="_static/scripts/pydata-sphinx-theme.js?digest=dfe6caa3a7d634c4db9b" />
<script src="_static/vendor/fontawesome/6.5.2/js/all.min.js?digest=dfe6caa3a7d634c4db9b"></script>
<script src="_static/documentation_options.js?v=9eb32ce0"></script>
<script src="_static/doctools.js?v=9a2dae69"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/clipboard.min.js?v=a7894cd8"></script>
<script src="_static/copybutton.js?v=f281be69"></script>
<script src="_static/scripts/sphinx-book-theme.js?v=887ef09a"></script>
<script>let toggleHintShow = 'Click to show';</script>
<script>let toggleHintHide = 'Click to hide';</script>
<script>let toggleOpenOnPrint = 'true';</script>
<script src="_static/togglebutton.js?v=4a39c7ea"></script>
<script>var togglebuttonSelector = '.toggle, .admonition.dropdown';</script>
<script src="_static/design-tabs.js?v=f930bc37"></script>
<script>const THEBE_JS_URL = "https://unpkg.com/thebe@0.8.2/lib/index.js"; const thebe_selector = ".thebe,.cell"; const thebe_selector_input = "pre"; const thebe_selector_output = ".output, .cell_output"</script>
<script async="async" src="_static/sphinx-thebe.js?v=c100c467"></script>
<script>var togglebuttonSelector = '.toggle, .admonition.dropdown';</script>
<script>const THEBE_JS_URL = "https://unpkg.com/thebe@0.8.2/lib/index.js"; const thebe_selector = ".thebe,.cell"; const thebe_selector_input = "pre"; const thebe_selector_output = ".output, .cell_output"</script>
<script>window.MathJax = {"options": {"processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script>
<script defer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>DOCUMENTATION_OPTIONS.pagename = 'exercisesweek37';</script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="prev" title="Week 36: Linear Regression and Gradient descent" href="week36.html" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="docsearch:language" content="en"/>
</head>
<body data-bs-spy="scroll" data-bs-target=".bd-toc-nav" data-offset="180" data-bs-root-margin="0px 0px -60%" data-default-mode="">
<div id="pst-skip-link" class="skip-link d-print-none"><a href="#main-content">Skip to main content</a></div>
<div id="pst-scroll-pixel-helper"></div>
<button type="button" class="btn rounded-pill" id="pst-back-to-top">
<i class="fa-solid fa-arrow-up"></i>Back to top</button>
<input type="checkbox"
class="sidebar-toggle"
id="pst-primary-sidebar-checkbox"/>
<label class="overlay overlay-primary" for="pst-primary-sidebar-checkbox"></label>
<input type="checkbox"
class="sidebar-toggle"
id="pst-secondary-sidebar-checkbox"/>
<label class="overlay overlay-secondary" for="pst-secondary-sidebar-checkbox"></label>
<div class="search-button__wrapper">
<div class="search-button__overlay"></div>
<div class="search-button__search-container">
<form class="bd-search d-flex align-items-center"
action="search.html"
method="get">
<i class="fa-solid fa-magnifying-glass"></i>
<input type="search"
class="form-control"
name="q"
id="search-input"
placeholder="Search this book..."
aria-label="Search this book..."
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"/>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd>K</kbd></span>
</form></div>
</div>
<div class="pst-async-banner-revealer d-none">
<aside id="bd-header-version-warning" class="d-none d-print-none" aria-label="Version warning"></aside>
</div>
<header class="bd-header navbar navbar-expand-lg bd-navbar d-print-none">
</header>
<div class="bd-container">
<div class="bd-container__inner bd-page-width">
<div class="bd-sidebar-primary bd-sidebar">
<div class="sidebar-header-items sidebar-primary__section">
</div>
<div class="sidebar-primary-items__start sidebar-primary__section">
<div class="sidebar-primary-item">
<a class="navbar-brand logo" href="intro.html">
<img src="_static/logo.png" class="logo__image only-light" alt="Applied Data Analysis and Machine Learning - Home"/>
<script>document.write(`<img src="_static/logo.png" class="logo__image only-dark" alt="Applied Data Analysis and Machine Learning - Home"/>`);</script>
</a></div>
<div class="sidebar-primary-item">
<script>
document.write(`
<button class="btn search-button-field search-button__button" title="Search" aria-label="Search" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="fa-solid fa-magnifying-glass"></i>
<span class="search-button__default-text">Search</span>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd class="kbd-shortcut__modifier">K</kbd></span>
</button>
`);
</script></div>
<div class="sidebar-primary-item"><nav class="bd-links bd-docs-nav" aria-label="Main">
<div class="bd-toc-item navbar-nav active">
<ul class="nav bd-sidenav bd-sidenav__home-link">
<li class="toctree-l1">
<a class="reference internal" href="intro.html">
Applied Data Analysis and Machine Learning
</a>
</li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">About the course</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="schedule.html">Course setting</a></li>
<li class="toctree-l1"><a class="reference internal" href="teachers.html">Teachers and Grading</a></li>
<li class="toctree-l1"><a class="reference internal" href="textbooks.html">Textbooks</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Review of Statistics with Resampling Techniques and Linear Algebra</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="statistics.html">1. Elements of Probability Theory and Statistical Data Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="linalg.html">2. Linear Algebra, Handling of Arrays and more Python Features</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">From Regression to Support Vector Machines</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter1.html">3. Linear Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter2.html">4. Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter3.html">5. Resampling Methods</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter4.html">6. Logistic Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapteroptimization.html">7. Optimization, the central part of any Machine Learning algortithm</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter5.html">8. Support Vector Machines, overarching aims</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Decision Trees, Ensemble Methods and Boosting</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter6.html">9. Decision trees, overarching aims</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter7.html">10. Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Dimensionality Reduction</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter8.html">11. Basic ideas of the Principal Component Analysis (PCA)</a></li>
<li class="toctree-l1"><a class="reference internal" href="clustering.html">12. Clustering and Unsupervised Learning</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Deep Learning Methods</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="chapter9.html">13. Neural networks</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter10.html">14. Building a Feed Forward Neural Network</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter11.html">15. Solving Differential Equations with Deep Learning</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter12.html">16. Convolutional Neural Networks</a></li>
<li class="toctree-l1"><a class="reference internal" href="chapter13.html">17. Recurrent neural networks: Overarching view</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Weekly material, notes and exercises</span></p>
<ul class="current nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="exercisesweek34.html">Exercises week 34</a></li>
<li class="toctree-l1"><a class="reference internal" href="week34.html">Week 34: Introduction to the course, Logistics and Practicalities</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek35.html">Exercises week 35</a></li>
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1 current active"><a class="current reference internal" href="#">Exercises week 36</a></li>
</ul>
</div>
</nav></div>
</div>
<div class="sidebar-primary-items__end sidebar-primary__section">
</div>
<div id="rtd-footer-container"></div>
</div>
<main id="main-content" class="bd-main" role="main">
<div class="sbt-scroll-pixel-helper"></div>
<div class="bd-content">
<div class="bd-article-container">
<div class="bd-header-article d-print-none">
<div class="header-article-items header-article__inner">
<div class="header-article-items__start">
<div class="header-article-item"><button class="sidebar-toggle primary-toggle btn btn-sm" title="Toggle primary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-bars"></span>
</button></div>
</div>
<div class="header-article-items__end">
<div class="header-article-item">
<div class="article-header-buttons">
<div class="dropdown dropdown-download-buttons">
<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Download this page">
<i class="fas fa-download"></i>
</button>
<ul class="dropdown-menu">
<li><a href="_sources/exercisesweek37.ipynb" target="_blank"
class="btn btn-sm btn-download-source-button dropdown-item"
title="Download source file"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-file"></i>
</span>
<span class="btn__text-container">.ipynb</span>
</a>
</li>
<li>
<button onclick="window.print()"
class="btn btn-sm btn-download-pdf-button dropdown-item"
title="Print to PDF"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-file-pdf"></i>
</span>
<span class="btn__text-container">.pdf</span>
</button>
</li>
</ul>
</div>
<button onclick="toggleFullScreen()"
class="btn btn-sm btn-fullscreen-button"
title="Fullscreen mode"
data-bs-placement="bottom" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-expand"></i>
</span>
</button>
<script>
document.write(`
<button class="btn btn-sm nav-link pst-navbar-icon theme-switch-button" title="light/dark" aria-label="light/dark" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="theme-switch fa-solid fa-sun fa-lg" data-mode="light"></i>
<i class="theme-switch fa-solid fa-moon fa-lg" data-mode="dark"></i>
<i class="theme-switch fa-solid fa-circle-half-stroke fa-lg" data-mode="auto"></i>
</button>
`);
</script>
<script>
document.write(`
<button class="btn btn-sm pst-navbar-icon search-button search-button__button" title="Search" aria-label="Search" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="fa-solid fa-magnifying-glass fa-lg"></i>
</button>
`);
</script>
<button class="sidebar-toggle secondary-toggle btn btn-sm" title="Toggle secondary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-list"></span>
</button>
</div></div>
</div>
</div>
</div>
<div id="jb-print-docs-body" class="onlyprint">
<h1>Exercises week 36</h1>
<!-- Table of contents -->
<div id="print-main-content">
<div id="jb-print-toc">
<div>
<h2> Contents </h2>
</div>
<nav aria-label="Page">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#learning-goals">Learning goals</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#ridge-regression-and-a-new-synthetic-dataset">Ridge regression and a new Synthetic Dataset</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#exercise-1-scale-your-data">Exercise 1, scale your data</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#a">1a)</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#exercise-2-use-the-analytical-formulae-for-ols-and-ridge-regression-to-find-the-optimal-paramters-boldsymbol-theta">Exercise 2, use the analytical formulae for OLS and Ridge regression to find the optimal paramters <span class="math notranslate nohighlight">\(\boldsymbol{theta}\)</span></a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#id1">2a)</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#b">2b)</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#implementing-the-simplest-form-for-gradient-descent">Implementing the simplest form for gradient descent</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#id2">3a)</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#id3">3b)</a></li>
</ul>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div id="searchbox"></div>
<article class="bd-article">
<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)
doconce format html exercisesweek37.do.txt -->
<!-- dom:TITLE: Exercises week 36 --><section class="tex2jax_ignore mathjax_ignore" id="exercises-week-36">
<h1>Exercises week 36<a class="headerlink" href="#exercises-week-36" title="Link to this heading">#</a></h1>
<p><strong>Implementing gradient descent for Ridge and ordinary Least Squares Regression</strong></p>
<p>Date: <strong>September 8-12, 2025</strong></p>
<section id="learning-goals">
<h2>Learning goals<a class="headerlink" href="#learning-goals" title="Link to this heading">#</a></h2>
<p>After having completed these exercises you will have:</p>
<ol class="arabic simple">
<li><p>Your own code for the implementation of the simplest gradient descent approach applied to ordinary least squares (OLS) and Ridge regression</p></li>
<li><p>Be able to compare the analytical expressions for OLS and Rudge regression with the gradient descent approach</p></li>
<li><p>Explore the role of the learning rate in the gradient descent approach and the hyperparameter <span class="math notranslate nohighlight">\(\lambda\)</span> in Ridge regression</p></li>
<li><p>Scale the data properly</p></li>
</ol>
</section>
<section id="ridge-regression-and-a-new-synthetic-dataset">
<h2>Ridge regression and a new Synthetic Dataset<a class="headerlink" href="#ridge-regression-and-a-new-synthetic-dataset" title="Link to this heading">#</a></h2>
<p>We create a synthetic linear regression dataset with a sparse
underlying relationship. This means we have many features but only a
few of them actually contribute to the target. In our example, well
use 10 features with only 3 non-zero weights in the true model. This
way, the target is generated as a linear combination of a few features
(with known coefficients) plus some random noise. The steps we include are:</p>
<p>Decide on the number of samples and features (e.g. 100 samples, 10 features).
Define the <strong>true</strong> coefficient vector with mostly zeros (for sparsity). For example, we set <span class="math notranslate nohighlight">\(\hat{\boldsymbol{\theta}} = [5.0, -3.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0]\)</span>, meaning only features 0, 1, and 6 have a real effect on y.</p>
<p>Then we sample feature values for <span class="math notranslate nohighlight">\(\boldsymbol{X}\)</span> randomly (e.g. from a normal distribution). We use a normal distribution so features are roughly centered around 0.
Then we compute the target values <span class="math notranslate nohighlight">\(y\)</span> using the linear combination <span class="math notranslate nohighlight">\(\boldsymbol{X}\hat{\boldsymbol{\theta}}\)</span> and add some noise (to simulate measurement error or unexplained variance).</p>
<p>Below is the code to generate the dataset:</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>import numpy as np
# Set random seed for reproducibility
np.random.seed(0)
# Define dataset size
n_samples = 100
n_features = 10
# Define true coefficients (sparse linear relationship)
theta_true = np.array([5.0, -3.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0])
# Generate feature matrix X (n_samples x n_features) with random values
X = np.random.randn(n_samples, n_features) # standard normal distribution
# Generate target values y with a linear combination of X and theta_true, plus noise
noise = 0.5 * np.random.randn(n_samples) # Gaussian noise
y = X.dot @ theta_true + noise
</pre></div>
</div>
</div>
</div>
<p>This code produces a dataset where only features 0, 1, and 6
significantly influence <span class="math notranslate nohighlight">\(\boldsymbol{y}\)</span>. The rest of the features have zero true
coefficient, so they only contribute noise. For example, feature 0 has
a true weight of 5.0, feature 1 has -3.0, and feature 6 has 2.0, so
the expected relationship is:</p>
<div class="math notranslate nohighlight">
\[
y \approx 5 \times X_0 \;-\; 3 \times X_1 \;+\; 2 \times X_6 \;+\; \text{noise}.
\]</div>
</section>
<section id="exercise-1-scale-your-data">
<h2>Exercise 1, scale your data<a class="headerlink" href="#exercise-1-scale-your-data" title="Link to this heading">#</a></h2>
<p>Before fitting a regression model, it is good practice to normalize or
standardize the features. This ensures all features are on a
comparable scale, which is especially important when using
regularization. Here we will perform standardization, scaling each
feature to have mean 0 and standard deviation 1:</p>
<p>Compute the mean and standard deviation of each column (feature) in <span class="math notranslate nohighlight">\(bm{X}\)</span>.
Subtract the mean and divide by the standard deviation for each feature.</p>
<p>We will also center the target <span class="math notranslate nohighlight">\(\boldsymbol{y}\)</span> to mean <span class="math notranslate nohighlight">\(0\)</span>. Centering <span class="math notranslate nohighlight">\(\boldsymbol{y}\)</span>
(and each feature) means the model wont require a separate intercept
term the data is shifted such that the intercept is effectively 0
. (In practice, one could include an intercept in the model and not
penalize it, but here we simplify by centering.)</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># Standardize features (zero mean, unit variance for each feature)
X_mean = X.mean(axis=0)
X_std = X.std(axis=0)
X_std[X_std == 0] = 1 # safeguard to avoid division by zero for constant features
X_norm = (X - X_mean) / X_std
# Center the target to zero mean (optional, to simplify intercept handling)
y_mean = ?
y_centered = ?
</pre></div>
</div>
</div>
</div>
<section id="a">
<h3>1a)<a class="headerlink" href="#a" title="Link to this heading">#</a></h3>
<p>Fill in the necessary details.</p>
<p>After this preprocessing, each column of <span class="math notranslate nohighlight">\(\boldsymbol{X}_norm\)</span> has mean zero and standard deviation <span class="math notranslate nohighlight">\(1\)</span>
and <span class="math notranslate nohighlight">\(\boldsymbol{y}_centered\)</span> has mean 0. This makes the optimization landscape
nicer and ensures the regularization penalty <span class="math notranslate nohighlight">\(\lambda \sum_j
\beta_j^2\)</span> treats each coefficient fairly (since features are on the
same scale).</p>
</section>
</section>
<section id="exercise-2-use-the-analytical-formulae-for-ols-and-ridge-regression-to-find-the-optimal-paramters-boldsymbol-theta">
<h2>Exercise 2, use the analytical formulae for OLS and Ridge regression to find the optimal paramters <span class="math notranslate nohighlight">\(\boldsymbol{theta}\)</span><a class="headerlink" href="#exercise-2-use-the-analytical-formulae-for-ols-and-ridge-regression-to-find-the-optimal-paramters-boldsymbol-theta" title="Link to this heading">#</a></h2>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># Set regularization parameter, either a single value or a vector of values
lambda = ?
# Analytical form for OLS and Ridge solution: theta_Ridge = (X^T X + lambda * I)^{-1} X^T y and theta_OLS = (X^T X)^{-1} X^T y
I = np.eye(n_features)
theta_closed_formRidge = ?
theta_closed_formOLS = ?
print(&quot;Closed-form Ridge coefficients:&quot;, theta_closed_form)
print(&quot;Closed-form OLS coefficients:&quot;, theta_closed_form)
</pre></div>
</div>
</div>
</div>
<p>This computes the ridge and OLS regression coefficients directly. The identity
matrix <span class="math notranslate nohighlight">\(I\)</span> has the same size as <span class="math notranslate nohighlight">\(X^T X\)</span> (which is n_features x
n_features), and lam * I adds <span class="math notranslate nohighlight">\(\lambda\)</span> to the diagonal of <span class="math notranslate nohighlight">\(X^T X. We
then invert this matrix and multiply by \)</span>X^T y. The result
for <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span> is a NumPy array of shape (n_features,) containing the
fitted weights.</p>
<section id="id1">
<h3>2a)<a class="headerlink" href="#id1" title="Link to this heading">#</a></h3>
<p>Finalize the OLS and Ridge regression determination of the optimal parameters <span class="math notranslate nohighlight">\(bm{\theta}\)</span>.</p>
</section>
<section id="b">
<h3>2b)<a class="headerlink" href="#b" title="Link to this heading">#</a></h3>
<p>Explore the results as function of different values of the hyperparameter <span class="math notranslate nohighlight">\(\lambda\)</span>. See for example exercise 4 from week 36.</p>
</section>
</section>
<section id="implementing-the-simplest-form-for-gradient-descent">
<h2>Implementing the simplest form for gradient descent<a class="headerlink" href="#implementing-the-simplest-form-for-gradient-descent" title="Link to this heading">#</a></h2>
<p>Alternatively, we can fit the ridge regression model using gradient
descent. This is useful to visualize the iterative convergence and is
necessary if <span class="math notranslate nohighlight">\(n\)</span> and <span class="math notranslate nohighlight">\(p\)</span> are so large that the closed-form might be
too slow or memory-intensive. We derive the gradients from the cost
functions defined above. Use the gradients of the Ridge and OLS cost functions with respect to
the parameters <span class="math notranslate nohighlight">\(\boldsymbol{\theta}\)</span> and set up (using the template below) your own gradient descent code for OLS and Ridge regression.</p>
<p>Below is a template code for gradient descent implementation of ridge:</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># Gradient descent parameters, learning rate eta first
eta = 0.1
# Then number of iterations
num_iters = 1000
# Initialize weights for gradient descent
theta = np.zeros(n_features)
# Arrays to store history for plotting
cost_history = np.zeros(num_iters)
# Gradient descent loop
m = n_samples # number of examples
for t in range(num_iters):
# Compute prediction error
error = X_norm.dot(theta) - y_centered
# Compute cost for OLS and Ridge (MSE + regularization for Ridge) for monitoring
cost_OLS = ?
cost_Ridge = ?
cost_history[t] = ?
# Compute gradients for OSL and Ridge
grad_OLS = ?
grad_Ridge = ?
# Update parameters theta
theta_gdOLS = ?
theta_gdRidge = ?
# After the loop, theta contains the fitted coefficients
theta_gdOLS = ?
theta_gdRidge = ?
print(&quot;Gradient Descent OLS coefficients:&quot;, theta_gdOLS)
print(&quot;Gradient Descent Ridge coefficients:&quot;, theta_gdRidge)
</pre></div>
</div>
</div>
</div>
<section id="id2">
<h3>3a)<a class="headerlink" href="#id2" title="Link to this heading">#</a></h3>
<p>Discuss the results as function of the learning rate paramaters and the number of iterations.</p>
</section>
<section id="id3">
<h3>3b)<a class="headerlink" href="#id3" title="Link to this heading">#</a></h3>
<p>Add a stopping parameter as function of the number iterations.</p>
<p>If everything worked correctly, the learned coefficients should be
close to the true values [5.0, -3.0, 0.0, …, 2.0, …] that we used to
generate the data. Keep in mind that due to regularization and noise,
the learned values will not exactly equal the true ones, but they
should be in the same ballpark.</p>
</section>
</section>
</section>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
name: "python3",
path: "./."
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</article>
<footer class="prev-next-footer d-print-none">
<div class="prev-next-area">
<a class="left-prev"
href="week36.html"
title="previous page">
<i class="fa-solid fa-angle-left"></i>
<div class="prev-next-info">
<p class="prev-next-subtitle">previous</p>
<p class="prev-next-title">Week 36: Linear Regression and Gradient descent</p>
</div>
</a>
</div>
</footer>
</div>
<div class="bd-sidebar-secondary bd-toc"><div class="sidebar-secondary-items sidebar-secondary__inner">
<div class="sidebar-secondary-item">
<div class="page-toc tocsection onthispage">
<i class="fa-solid fa-list"></i> Contents
</div>
<nav class="bd-toc-nav page-toc">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#learning-goals">Learning goals</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#ridge-regression-and-a-new-synthetic-dataset">Ridge regression and a new Synthetic Dataset</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#exercise-1-scale-your-data">Exercise 1, scale your data</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#a">1a)</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#exercise-2-use-the-analytical-formulae-for-ols-and-ridge-regression-to-find-the-optimal-paramters-boldsymbol-theta">Exercise 2, use the analytical formulae for OLS and Ridge regression to find the optimal paramters <span class="math notranslate nohighlight">\(\boldsymbol{theta}\)</span></a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#id1">2a)</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#b">2b)</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#implementing-the-simplest-form-for-gradient-descent">Implementing the simplest form for gradient descent</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#id2">3a)</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#id3">3b)</a></li>
</ul>
</li>
</ul>
</nav></div>
</div></div>
</div>
<footer class="bd-footer-content">
<div class="bd-footer-content__inner container">
<div class="footer-item">
<p class="component-author">
By Morten Hjorth-Jensen
</p>
</div>
<div class="footer-item">
<p class="copyright">
© Copyright 2023.
<br/>
</p>
</div>
<div class="footer-item">
</div>
<div class="footer-item">
</div>
</div>
</footer>
</main>
</div>
</div>
<!-- Scripts loaded after <body> so the DOM is not blocked -->
<script src="_static/scripts/bootstrap.js?digest=dfe6caa3a7d634c4db9b"></script>
<script src="_static/scripts/pydata-sphinx-theme.js?digest=dfe6caa3a7d634c4db9b"></script>
<footer class="bd-footer">
</footer>
</body>
</html>
@@ -226,6 +226,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
+1
View File
@@ -230,6 +230,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
+1
View File
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
Binary file not shown.
@@ -227,6 +227,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
+1
View File
@@ -228,6 +228,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
File diff suppressed because one or more lines are too long
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -227,6 +227,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -227,6 +227,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
+1
View File
@@ -229,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
+1
View File
@@ -229,6 +229,7 @@
<li class="toctree-l1 current active"><a class="current reference internal" href="#">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1"><a class="reference internal" href="week36.html">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
+11
View File
@@ -62,6 +62,7 @@
<script>DOCUMENTATION_OPTIONS.pagename = 'week36';</script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="Exercises week 36" href="exercisesweek37.html" />
<link rel="prev" title="Exercises week 36" href="exercisesweek36.html" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="docsearch:language" content="en"/>
@@ -228,6 +229,7 @@
<li class="toctree-l1"><a class="reference internal" href="week35.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek36.html">Exercises week 36</a></li>
<li class="toctree-l1 current active"><a class="current reference internal" href="#">Week 36: Linear Regression and Gradient descent</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercisesweek37.html">Exercises week 36</a></li>
</ul>
</div>
@@ -2403,6 +2405,15 @@ plt.show()
<p class="prev-next-title">Exercises week 36</p>
</div>
</a>
<a class="right-next"
href="exercisesweek37.html"
title="next page">
<div class="prev-next-info">
<p class="prev-next-subtitle">next</p>
<p class="prev-next-title">Exercises week 36</p>
</div>
<i class="fa-solid fa-angle-right"></i>
</a>
</div>
</footer>
@@ -0,0 +1,360 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "7d56b2d5",
"metadata": {
"editable": true
},
"source": [
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
"doconce format html exercisesweek37.do.txt -->\n",
"<!-- dom:TITLE: Exercises week 36 -->"
]
},
{
"cell_type": "markdown",
"id": "c7a8e9c7",
"metadata": {
"editable": true
},
"source": [
"# Exercises week 36\n",
"**Implementing gradient descent for Ridge and ordinary Least Squares Regression**\n",
"\n",
"Date: **September 8-12, 2025**"
]
},
{
"cell_type": "markdown",
"id": "cf8f0ecb",
"metadata": {
"editable": true
},
"source": [
"## Learning goals\n",
"\n",
"After having completed these exercises you will have:\n",
"1. Your own code for the implementation of the simplest gradient descent approach applied to ordinary least squares (OLS) and Ridge regression\n",
"\n",
"2. Be able to compare the analytical expressions for OLS and Rudge regression with the gradient descent approach\n",
"\n",
"3. Explore the role of the learning rate in the gradient descent approach and the hyperparameter $\\lambda$ in Ridge regression\n",
"\n",
"4. Scale the data properly"
]
},
{
"cell_type": "markdown",
"id": "a67ae548",
"metadata": {
"editable": true
},
"source": [
"## Ridge regression and a new Synthetic Dataset\n",
"\n",
"We create a synthetic linear regression dataset with a sparse\n",
"underlying relationship. This means we have many features but only a\n",
"few of them actually contribute to the target. In our example, well\n",
"use 10 features with only 3 non-zero weights in the true model. This\n",
"way, the target is generated as a linear combination of a few features\n",
"(with known coefficients) plus some random noise. The steps we include are:\n",
"\n",
"Decide on the number of samples and features (e.g. 100 samples, 10 features).\n",
"Define the **true** coefficient vector with mostly zeros (for sparsity). For example, we set $\\hat{\\boldsymbol{\\theta}} = [5.0, -3.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0]$, meaning only features 0, 1, and 6 have a real effect on y.\n",
"\n",
"Then we sample feature values for $\\boldsymbol{X}$ randomly (e.g. from a normal distribution). We use a normal distribution so features are roughly centered around 0.\n",
"Then we compute the target values $y$ using the linear combination $\\boldsymbol{X}\\hat{\\boldsymbol{\\theta}}$ and add some noise (to simulate measurement error or unexplained variance).\n",
"\n",
"Below is the code to generate the dataset:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "f2d4a55d",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"# Set random seed for reproducibility\n",
"np.random.seed(0)\n",
"\n",
"# Define dataset size\n",
"n_samples = 100\n",
"n_features = 10\n",
"\n",
"# Define true coefficients (sparse linear relationship)\n",
"theta_true = np.array([5.0, -3.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0])\n",
"\n",
"# Generate feature matrix X (n_samples x n_features) with random values\n",
"X = np.random.randn(n_samples, n_features) # standard normal distribution\n",
"\n",
"# Generate target values y with a linear combination of X and theta_true, plus noise\n",
"noise = 0.5 * np.random.randn(n_samples) # Gaussian noise\n",
"y = X.dot @ theta_true + noise"
]
},
{
"cell_type": "markdown",
"id": "a445583b",
"metadata": {
"editable": true
},
"source": [
"This code produces a dataset where only features 0, 1, and 6\n",
"significantly influence $\\boldsymbol{y}$. The rest of the features have zero true\n",
"coefficient, so they only contribute noise. For example, feature 0 has\n",
"a true weight of 5.0, feature 1 has -3.0, and feature 6 has 2.0, so\n",
"the expected relationship is:"
]
},
{
"cell_type": "markdown",
"id": "4a81ddf9",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"y \\approx 5 \\times X_0 \\;-\\; 3 \\times X_1 \\;+\\; 2 \\times X_6 \\;+\\; \\text{noise}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "ae590275",
"metadata": {
"editable": true
},
"source": [
"## Exercise 1, scale your data\n",
"\n",
"Before fitting a regression model, it is good practice to normalize or\n",
"standardize the features. This ensures all features are on a\n",
"comparable scale, which is especially important when using\n",
"regularization. Here we will perform standardization, scaling each\n",
"feature to have mean 0 and standard deviation 1:\n",
"\n",
"Compute the mean and standard deviation of each column (feature) in $bm{X}$.\n",
"Subtract the mean and divide by the standard deviation for each feature.\n",
"\n",
"We will also center the target $\\boldsymbol{y}$ to mean $0$. Centering $\\boldsymbol{y}$\n",
"(and each feature) means the model wont require a separate intercept\n",
"term the data is shifted such that the intercept is effectively 0\n",
". (In practice, one could include an intercept in the model and not\n",
"penalize it, but here we simplify by centering.)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "8b40c47a",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Standardize features (zero mean, unit variance for each feature)\n",
"X_mean = X.mean(axis=0)\n",
"X_std = X.std(axis=0)\n",
"X_std[X_std == 0] = 1 # safeguard to avoid division by zero for constant features\n",
"X_norm = (X - X_mean) / X_std\n",
"\n",
"# Center the target to zero mean (optional, to simplify intercept handling)\n",
"y_mean = ?\n",
"y_centered = ?"
]
},
{
"cell_type": "markdown",
"id": "ff9c0c81",
"metadata": {
"editable": true
},
"source": [
"### 1a)\n",
"\n",
"Fill in the necessary details.\n",
"\n",
"After this preprocessing, each column of $\\boldsymbol{X}_norm$ has mean zero and standard deviation $1$\n",
"and $\\boldsymbol{y}_centered$ has mean 0. This makes the optimization landscape\n",
"nicer and ensures the regularization penalty $\\lambda \\sum_j\n",
"\\beta_j^2$ treats each coefficient fairly (since features are on the\n",
"same scale)."
]
},
{
"cell_type": "markdown",
"id": "d27c70e4",
"metadata": {
"editable": true
},
"source": [
"## Exercise 2, use the analytical formulae for OLS and Ridge regression to find the optimal paramters $\\boldsymbol{theta}$"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "9f1e5184",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Set regularization parameter, either a single value or a vector of values\n",
"lambda = ?\n",
"\n",
"# Analytical form for OLS and Ridge solution: theta_Ridge = (X^T X + lambda * I)^{-1} X^T y and theta_OLS = (X^T X)^{-1} X^T y\n",
"I = np.eye(n_features)\n",
"theta_closed_formRidge = ?\n",
"theta_closed_formOLS = ?\n",
"\n",
"print(\"Closed-form Ridge coefficients:\", theta_closed_form)\n",
"print(\"Closed-form OLS coefficients:\", theta_closed_form)"
]
},
{
"cell_type": "markdown",
"id": "2ec556b9",
"metadata": {
"editable": true
},
"source": [
"This computes the ridge and OLS regression coefficients directly. The identity\n",
"matrix $I$ has the same size as $X^T X$ (which is n_features x\n",
"n_features), and lam * I adds $\\lambda$ to the diagonal of $X^T X. We\n",
"then invert this matrix and multiply by $X^T y. The result\n",
"for $\\boldsymbol{\\theta}$ is a NumPy array of shape (n_features,) containing the\n",
"fitted weights."
]
},
{
"cell_type": "markdown",
"id": "a821f0c5",
"metadata": {
"editable": true
},
"source": [
"### 2a)\n",
"\n",
"Finalize the OLS and Ridge regression determination of the optimal parameters $bm{\\theta}$."
]
},
{
"cell_type": "markdown",
"id": "d637130e",
"metadata": {
"editable": true
},
"source": [
"### 2b)\n",
"\n",
"Explore the results as function of different values of the hyperparameter $\\lambda$. See for example exercise 4 from week 36."
]
},
{
"cell_type": "markdown",
"id": "b455ce7e",
"metadata": {
"editable": true
},
"source": [
"## Implementing the simplest form for gradient descent\n",
"\n",
"Alternatively, we can fit the ridge regression model using gradient\n",
"descent. This is useful to visualize the iterative convergence and is\n",
"necessary if $n$ and $p$ are so large that the closed-form might be\n",
"too slow or memory-intensive. We derive the gradients from the cost\n",
"functions defined above. Use the gradients of the Ridge and OLS cost functions with respect to\n",
"the parameters $\\boldsymbol{\\theta}$ and set up (using the template below) your own gradient descent code for OLS and Ridge regression.\n",
"\n",
"Below is a template code for gradient descent implementation of ridge:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "cfa1eb29",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Gradient descent parameters, learning rate eta first\n",
"eta = 0.1\n",
"# Then number of iterations\n",
"num_iters = 1000\n",
"\n",
"# Initialize weights for gradient descent\n",
"theta = np.zeros(n_features)\n",
"\n",
"# Arrays to store history for plotting\n",
"cost_history = np.zeros(num_iters)\n",
"\n",
"# Gradient descent loop\n",
"m = n_samples # number of examples\n",
"for t in range(num_iters):\n",
" # Compute prediction error\n",
" error = X_norm.dot(theta) - y_centered \n",
" # Compute cost for OLS and Ridge (MSE + regularization for Ridge) for monitoring\n",
" cost_OLS = ?\n",
" cost_Ridge = ?\n",
" cost_history[t] = ?\n",
" # Compute gradients for OSL and Ridge\n",
" grad_OLS = ?\n",
" grad_Ridge = ?\n",
" # Update parameters theta\n",
" theta_gdOLS = ?\n",
" theta_gdRidge = ? \n",
"\n",
"# After the loop, theta contains the fitted coefficients\n",
"theta_gdOLS = ?\n",
"theta_gdRidge = ?\n",
"print(\"Gradient Descent OLS coefficients:\", theta_gdOLS)\n",
"print(\"Gradient Descent Ridge coefficients:\", theta_gdRidge)"
]
},
{
"cell_type": "markdown",
"id": "dc78d58d",
"metadata": {
"editable": true
},
"source": [
"### 3a)\n",
"\n",
"Discuss the results as function of the learning rate paramaters and the number of iterations."
]
},
{
"cell_type": "markdown",
"id": "15060acb",
"metadata": {
"editable": true
},
"source": [
"### 3b)\n",
"\n",
"Add a stopping parameter as function of the number iterations. \n",
"\n",
"If everything worked correctly, the learned coefficients should be\n",
"close to the true values [5.0, -3.0, 0.0, …, 2.0, …] that we used to\n",
"generate the data. Keep in mind that due to regularization and noise,\n",
"the learned values will not exactly equal the true ones, but they\n",
"should be in the same ballpark."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
+2 -1
View File
@@ -46,4 +46,5 @@ parts:
- file: exercisesweek35.ipynb
- file: week35.ipynb
- file: exercisesweek36.ipynb
- file: week36.ipynb
- file: week36.ipynb
- file: exercisesweek37.ipynb