This commit is contained in:
Morten Hjorth-Jensen
2025-09-01 07:42:38 +02:00
parent 79bb2aa946
commit c491c23130
8 changed files with 370 additions and 727 deletions
+2 -2
View File
@@ -346,7 +346,7 @@ $$
<p>In this case the standard OLS results in </p>
$$
\boldsymbol{\theta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{n-1}\boldsymbol{u}_i\boldsymbol{u}_i^T\boldsymbol{y},
\boldsymbol{\theta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y},
$$
<p>and</p>
@@ -360,7 +360,7 @@ the Ridge estimator converges to zero when the hyperparameter goes to
infinity.
</p>
<p>We will come back to more interpreations after we have gone through some of the statistical analysis part. </p>
<p>We will come back to more interpretions after we have gone through some of the statistical analysis part. </p>
<p>For more discussions of Ridge and Lasso regression, <a href="https://arxiv.org/abs/1509.09169" target="_self">Wessel van Wieringen's</a> article is highly recommended.
Similarly, <a href="https://arxiv.org/abs/1803.08823" target="_self">Mehta et al's article</a> is also recommended.
+2 -2
View File
@@ -1226,7 +1226,7 @@ $$
<p>In this case the standard OLS results in </p>
<p>&nbsp;<br>
$$
\boldsymbol{\theta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{n-1}\boldsymbol{u}_i\boldsymbol{u}_i^T\boldsymbol{y},
\boldsymbol{\theta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y},
$$
<p>&nbsp;<br>
@@ -1243,7 +1243,7 @@ the Ridge estimator converges to zero when the hyperparameter goes to
infinity.
</p>
<p>We will come back to more interpreations after we have gone through some of the statistical analysis part. </p>
<p>We will come back to more interpretions after we have gone through some of the statistical analysis part. </p>
<p>For more discussions of Ridge and Lasso regression, <a href="https://arxiv.org/abs/1509.09169" target="_blank">Wessel van Wieringen's</a> article is highly recommended.
Similarly, <a href="https://arxiv.org/abs/1803.08823" target="_blank">Mehta et al's article</a> is also recommended.
+2 -2
View File
@@ -1177,7 +1177,7 @@ $$
<p>In this case the standard OLS results in </p>
$$
\boldsymbol{\theta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{n-1}\boldsymbol{u}_i\boldsymbol{u}_i^T\boldsymbol{y},
\boldsymbol{\theta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y},
$$
<p>and</p>
@@ -1191,7 +1191,7 @@ the Ridge estimator converges to zero when the hyperparameter goes to
infinity.
</p>
<p>We will come back to more interpreations after we have gone through some of the statistical analysis part. </p>
<p>We will come back to more interpretions after we have gone through some of the statistical analysis part. </p>
<p>For more discussions of Ridge and Lasso regression, <a href="https://arxiv.org/abs/1509.09169" target="_blank">Wessel van Wieringen's</a> article is highly recommended.
Similarly, <a href="https://arxiv.org/abs/1803.08823" target="_blank">Mehta et al's article</a> is also recommended.
+2 -2
View File
@@ -1254,7 +1254,7 @@ $$
<p>In this case the standard OLS results in </p>
$$
\boldsymbol{\theta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{n-1}\boldsymbol{u}_i\boldsymbol{u}_i^T\boldsymbol{y},
\boldsymbol{\theta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y},
$$
<p>and</p>
@@ -1268,7 +1268,7 @@ the Ridge estimator converges to zero when the hyperparameter goes to
infinity.
</p>
<p>We will come back to more interpreations after we have gone through some of the statistical analysis part. </p>
<p>We will come back to more interpretions after we have gone through some of the statistical analysis part. </p>
<p>For more discussions of Ridge and Lasso regression, <a href="https://arxiv.org/abs/1509.09169" target="_blank">Wessel van Wieringen's</a> article is highly recommended.
Similarly, <a href="https://arxiv.org/abs/1803.08823" target="_blank">Mehta et al's article</a> is also recommended.
Binary file not shown.
File diff suppressed because it is too large Load Diff
-357
View File
@@ -1,357 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "2c329a04",
"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: Week 37: Linear Regression and Gradient descent -->"
]
},
{
"cell_type": "markdown",
"id": "432a2e5c",
"metadata": {
"editable": true
},
"source": [
"# Week 37: Linear Regression and Gradient descent\n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo, Norway\n",
"\n",
"Date: **September 1-5, 2025**"
]
},
{
"cell_type": "markdown",
"id": "8352513e",
"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": 2,
"id": "d7eebc41",
"metadata": {
"collapsed": false,
"editable": true,
"jupyter": {
"outputs_hidden": false
}
},
"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 @ theta_true + noise"
]
},
{
"cell_type": "markdown",
"id": "1640310e",
"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": "60bce352",
"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": "75322f31",
"metadata": {
"editable": true
},
"source": [
"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 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": 3,
"id": "4b3f945a",
"metadata": {
"collapsed": false,
"editable": true,
"jupyter": {
"outputs_hidden": false
}
},
"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 = y.mean()\n",
"y_centered = y - y_mean"
]
},
{
"cell_type": "markdown",
"id": "12aec8b3",
"metadata": {
"editable": true
},
"source": [
"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": "code",
"execution_count": 7,
"id": "ffdecd03",
"metadata": {
"collapsed": false,
"editable": true,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Closed-form Ridge coefficients: [ 4.98041921 -2.85683951 -0.01549982 0.15658961 -0.07810233 -0.05094777\n",
" 1.75377987 0.00679113 0.0343071 -0.04883458]\n"
]
}
],
"source": [
"# Set regularization parameter\n",
"lam = 1.0\n",
"\n",
"# Closed-form Ridge solution: w = (X^T X + lam * I)^{-1} X^T y\n",
"I = np.eye(n_features)\n",
"theta_closed_form = np.linalg.inv(X_norm.T.dot(X_norm) + lam * I).dot(X_norm.T).dot(y_centered)\n",
"\n",
"print(\"Closed-form Ridge coefficients:\", theta_closed_form)"
]
},
{
"cell_type": "markdown",
"id": "33ff39a5",
"metadata": {
"editable": true
},
"source": [
"This computes the ridge 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.\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",
"function defined above. The gradient of the ridge cost with respect to\n",
"the weight vector $w$ is:\n",
"\n",
"Below is the code for gradient descent implementation of ridge:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "5b72dc82",
"metadata": {
"collapsed": false,
"editable": true,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gradient Descent Ridge coefficients: [ 4.98041921 -2.85683951 -0.01549982 0.15658961 -0.07810233 -0.05094777\n",
" 1.75377987 0.00679113 0.0343071 -0.04883458]\n"
]
}
],
"source": [
"# Gradient descent parameters\n",
"alpha = 0.1\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 # shape (m,)\n",
" # Compute cost (MSE + regularization) for monitoring\n",
" cost = (1/(2*m)) * np.dot(error, error) + (lam/(2*m)) * np.dot(theta, theta)\n",
" cost_history[t] = cost\n",
" # Compute gradient\n",
" grad = (1/m) * (X_norm.T.dot(error) + lam * theta)\n",
" # Update weights\n",
" theta = theta - alpha * grad\n",
"\n",
"# After the loop, theta contains the fitted coefficients\n",
"theta_gd = theta\n",
"print(\"Gradient Descent Ridge coefficients:\", theta_gd)"
]
},
{
"cell_type": "markdown",
"id": "1fc5b8d0",
"metadata": {
"editable": true
},
"source": [
"Let us confirm that the two approaches (closed-form and gradient\n",
"descent) give similar results, and then evaluate the model. First,\n",
"compare the learned coefficients to the true coefficients:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "a510e4e6",
"metadata": {
"collapsed": false,
"editable": true,
"jupyter": {
"outputs_hidden": false
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True coefficients: [ 5. -3. 0. 0. 0. 0. 2. 0. 0. 0.]\n",
"Closed-form learned coefficients: [ 4.98041921 -2.85683951 -0.01549982 0.15658961 -0.07810233 -0.05094777\n",
" 1.75377987 0.00679113 0.0343071 -0.04883458]\n",
"Gradient descent learned coefficients: [ 4.98041921 -2.85683951 -0.01549982 0.15658961 -0.07810233 -0.05094777\n",
" 1.75377987 0.00679113 0.0343071 -0.04883458]\n"
]
}
],
"source": [
"print(\"True coefficients:\", theta_true)\n",
"print(\"Closed-form learned coefficients:\", theta_closed_form)\n",
"print(\"Gradient descent learned coefficients:\", theta_gd)"
]
},
{
"cell_type": "markdown",
"id": "07081487",
"metadata": {
"editable": true
},
"source": [
"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": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.15"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+2 -2
View File
@@ -928,7 +928,7 @@ For the sake of simplicity, let us assume that the design matrix is orthonormal,
In this case the standard OLS results in
!bt
\[
\bm{\theta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{n-1}\bm{u}_i\bm{u}_i^T\bm{y},
\bm{\theta}^{\mathrm{OLS}} = \bm{X}^T\bm{y},
\]
!et
@@ -944,7 +944,7 @@ that is the Ridge estimator scales the OLS estimator by the inverse of a factor
the Ridge estimator converges to zero when the hyperparameter goes to
infinity.
We will come back to more interpreations after we have gone through some of the statistical analysis part.
We will come back to more interpretions after we have gone through some of the statistical analysis part.
For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended.
Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended.