Linear Regression Demo¶

About This Demo¶

In this demo, you will see how the closed form solution is used to find the optimal solution for linear regression.

Getting Started¶

Python Initialization¶

Please run the following code to initialize your Python kernel. You should be running a version of Python 3.x.

In [ ]:
import sys
import numpy as np

# Non-interactive plots
%matplotlib inline
import matplotlib.pyplot as plt

print("Python version:", sys.version.split(" ")[0])

Generate Data¶

First, let's generate some data. We will sample $x$ randomly between $0$ and $1$, and let $y$ be sampled as $y = 3x + 4 + \varepsilon$, where $\varepsilon\sim\mathcal{N}(0, 0.1)$ is noise sampled from a normal (Gaussian) random variable with mean $0$ and standard deviation $0.1$.

In [ ]:
# Specify sample size
N = 40

# Sample N points randomly along x-axis
X = np.random.rand(N, 1)

# Add a constant dimension (of all ones)
X = np.hstack((X, np.ones((N, 1))))

# Define a linear function
w = np.array([3, 4])

# Define labels
y = X @ w + (np.random.randn(N) * 0.1)

Visualize Data¶

Now, run the code below to visualize the data, which will roughly lie on a line.

In [ ]:
plt.plot(X[:, 0], y, ".", label=r"Sampled Data ($y = 3x + 4 + \epsilon$)")
plt.title(r"Sampled Data ($y = 3x + 4 + \epsilon$, $\epsilon\sim\mathcal{N}(0, 0.1)$)")
plt.legend(loc="upper left")
plt.xlabel("$x$")
plt.ylabel("$y$")
plt.show()

Learning Using Closed Form Solution¶

Recall the closed form solution $\mathbf{w}$ when $\mathbf{X}$ is a $n \times d$ matrix with each data point as a row:

$$ \mathbf{w} = \left(\mathbf{X}^\top\mathbf{X}\right)^{-1}\mathbf{X}^\top\mathbf{y} $$

The closed form solution is encoded and stored in the variable w_closed by running the next cell.

In [ ]:
w_closed = np.linalg.inv(X.T @ X) @ (X.T @ y)

Quick Quiz¶

There are two ways for calculating the closed form solution. Which one is more time-efficient?

  1. (np.linalg.inv(X.T @ X) @ X.T) @ y

  2. np.linalg.inv(X.T @ X) @ (X.T @ y)

You will find the answer later in the notebook, but do take a break and think how the order of operations affects efficiency!

Visualize Closed Form Solution¶

You can visualize the closed form solution with a line that is drawn over your data, using this code:

In [ ]:
def plot_linear(X, y, w):
    # Plot the sampled data points
    plt.plot(X[:, 0], y, ".", label=r"Sampled Data ($y = 3x + 4 + \epsilon$)")

    # Define two points with x-value 0 and 1 (and constant dimension)
    z = np.array(
        [
            [0, 1],
            [1, 1],
        ]
    )
    
    # Draw line w_closed through these two points
    plt.plot(z[:, 0], z @ w, "-", label="Closed Form Solution")

    plt.title("Sampled Data and Closed Form Solution")
    plt.legend(loc="upper left")
    plt.xlabel("$x$")
    plt.ylabel("$y$")
    plt.show()
In [ ]:
plot_linear(X, y, w_closed)

Pro-Tip: NumPy Linear Matrix Solver¶

Computing matrix inverses can be numerically unstable and slow. Instead, one can use the Numpy linear matrix solver to solve the following linear system:

$$ \mathbf{X}^\top\mathbf{X}\mathbf{w} = \mathbf{X}^\top\mathbf{y} $$

The solution is the same, but it is typically faster and more stable in case $\mathbf{X}^\top\mathbf{X}$ is not invertible.

In [ ]:
w_closed_np = np.linalg.solve(X.T @ X, X.T @ y)
In [ ]:
plot_linear(X, y, w_closed_np)

Scikit-Learn Approach¶

Scikit-learn (or sklearn) is a Python library with implementations for numerous machine learning and data science models. Scikit-learn provides a standard step-by-step training procedure across different machine learning models, simplifying model training and prediction. The typical process for selecting, training, and predicting with a model of your choice is as follows:

  1. Define the classifier clf using a call to the model class

  2. Train clf using clf.fit on training data

  3. Predict on test data using clf.predict, getting predictions as output

Scikit-learn provides a linear regression solver, which is demonstrated below.

In [ ]:
from sklearn.linear_model import LinearRegression

# Set parameter to False since intercept is already included in X (constant dim)
clf = LinearRegression(fit_intercept=False)
clf.fit(X, y)
w_sklearn = clf.coef_
In [ ]:
plot_linear(X, y, w_sklearn)

Answer to Quiz¶

Answer 2 is more efficient than answer 1 because

  1. (np.linalg.inv(X.T @ X) @ X.T) @ y performs two matrix-matrix multiplications ($2d^2n$ calculations), one inverse solve ($d^3$ calculations), and one matrix-vector multiplications ($dn$ calculations)

  2. np.linalg.inv(X.T @ X) @ (X.T @ y) performs one matrix-matrix multiplication ($d^2n$ calculations), one inverse solve ($d^3$ calculations), and two matrix-vector multiplications ($2dn$ calculations)

Add those up and you end up comparing:

  1. $2d^2n + d^3 + dn$ calculations for (np.linalg.inv(X.T @ X) @ X.T) @ y

  2. $d^2n + d^3 + 2dn$ calculations for np.linalg.inv(X.T @ X) @ (X.T @ y)

The number of calculations for answer 2 is smaller because $dn \leq d^2n$, with equality only when $d=1$.