%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_openml
from scipy.stats import multivariate_normal, norm
from scipy.special import softmax, logsumexp
In the lectures the principal component analysis (PCA) was introduced as a method for dimensionality reduction and feature extraction, i.e., to condense data by mapping it to a lower dimensional space of the most important features.
Let \begin{equation*} \mathbf{X} = \begin{bmatrix} \mathbf{x}_1^\intercal \\ \vdots \\ \mathbf{x}_N^\intercal \end{bmatrix} \in \mathbb{R}^{N \times D} \end{equation*} be a matrix of $N$ data samples $\mathbf{x}_n \in \mathbb{R}^D$, which are centered around zero. We consider a PCA with $M < D$ components.
To project the data points $\mathbf{x}_n$ to the $M$-dimensional space that is defined by the $M$ principal components of $\mathbf{X}$, the so-called principal subspace of $\mathbf{X}$, we can use the singular value decomposition of $\mathbf{X}$. Let $\mathbf{X} = \mathbf{U} \mathbf{\Sigma} \mathbf{V}^\mathsf{T}$ be the singular value decomposition of the data matrix $\mathbf{X}$ with the singular values sorted in descending order.
Then the projection $\mathbf{z}_n$ of data point $\mathbf{x}_n$ to the principal subspace of $\mathbf{X}$ is given by \begin{equation} \mathbf{z}_n^\mathsf{T} = \mathbf{x}_n^\mathsf{T} \begin{bmatrix} \mathbf{v}_1 & \cdots & \mathbf{v}_M \end{bmatrix}, \end{equation} where $\mathbf{v}_i$ is the $i$th column of matrix $\mathbf{V}$. The vector $\mathbf{z}_n$ can be seen as an encoding of the data point $\mathbf{x}_n$ in a lower dimensional space that is constructed by the directions for which the data shows the largest variations.
With the help of the singular value decomposition of $\mathbf{X}$, we can also compute reconstructions (or "decodings") $\tilde{\mathbf{x}}_n$ from the encodings $\mathbf{z}_n$ by \begin{equation*} \tilde{\mathbf{x}}_n^\intercal = \mathbf{z}_n^\intercal \begin{bmatrix} \mathbf{v}^\intercal_1 \\ \vdots \\ \mathbf{v}^\intercal_M \end{bmatrix}. \end{equation*} If we use $M < D$ components, usually we are not able to recover the original data from the lower dimensional encodings exactly. Ideally, we would like the reconstructions to be as good as possible while keeping $M$ as small as possible.
The singular value decomposition of a matrix $\mathbf{X} \in \mathbb{R}^{N \times D}$ is defined as a factorization of the form $\mathbf{X} = \mathbf{U} \mathbf{\Sigma} \mathbf{V}^\mathsf{T}$ where $\mathbf{U} \in \mathbb{R}^{N \times N}$ and $\mathbf{V} \in \mathbb{R}^{D \times D}$ are orthogonal matrices and $\mathbf{\Sigma} \in \mathbb{R}^{N \times D}$ is a rectangular diagonal matrix with non-negative numbers on the diagonal. The diagonal entries of $\mathbf{\Sigma}$ are the so-called singular values of $\mathbf{X}$. A common convention is to sort the singular values in descending order, in which case the diagonal matrix $\mathbf{\Sigma}$ is uniquely determined by $\mathbf{X}$.
In this exercise, we perform and analyse PCA of the MNIST image data set. The MNIST data set consists of 60000 training and 10000 test data points. Each data point consists of a grayscale image with 28 $\times$ 28 pixels of a handwritten digit. The digit has been size-normalized and centered within a fixed-sized image. Each image is also labeled with the digit (0, 1, ..., 8, or 9) it is depicting.
The following code block loads the MNIST data set.
# load MNIST data from https://www.openml.org/d/554
images, labels = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False)
# normalize images to [0, 1]
images = images / 255
# convert labels to integers
labels = labels.astype(int)
# split into training and test dataset
train_images, train_labels = images[:60_000], labels[:60_000]
test_images, test_labels = images[60_000:], labels[60_000:]
The images are loaded as vectors $\mathbf{x} = [x_1 \dots x_{784}]^\mathsf{T}$ where each input variable $x_j$ corresponds to one of the $28 \times 28 = 784$ pixels in the image. The figure below shows the first 100 images in the training data set.
# plot first 100 training images
fig, axes = plt.subplots(nrows=10, ncols=10, figsize=(10, 10))
for image, ax in zip(train_images, axes.flat):
ax.set_xticks(())
ax.set_yticks(())
ax.grid(False)
ax.imshow(image.reshape(28, 28), vmin=0.0, vmax=1.0, cmap='gray_r')
plt.show()
Let \begin{equation*} \mathbf{X} = \begin{bmatrix} \mathbf{x}_1^\mathsf{T} \\ \vdots \\ \mathbf{x}_{60000}^\mathsf{T} \end{bmatrix} \in \mathbb{R}^{60000 \times 784} \end{equation*} be a matrix of the MNIST training data set where each row $\mathbf{x}_i^\mathsf{T}$ represents an image of the training data set (all pixels are normalized to the interval $[0, 1]$). This matrix is huge, it contains $60000 \times 784 = 47040000$ entries!
Many entries in this matrix are zeros (corresponding to white pixels), and in particular the entries corresponding to white pixels close to the margins of an image are probably not informative and not relevant. In this exercise we will study how much information is lost if we compress the MNIST data set to $M = 2$ principal components.
We define the mean of the training images as \begin{equation*} \overline{\mathbf{x}} = \frac{1}{60000} \sum_{i=1}^{60000} \mathbf{x}_i, \end{equation*} and hence the centered training images are given by $\mathbf{X} - \overline{\mathbf{x}}^\mathsf{T}$.
We compute the singular value decomposition $\mathbf{X} - \overline{\mathbf{x}}^\mathsf{T} = \mathbf{U} \boldsymbol{\Sigma} \mathbf{V}^\mathsf{T}$ of the centered MNIST training data with the function numpy.linalg.svd.
# center training images
train_mean = train_images.mean(axis=0)
train_images_centered = train_images - train_mean
U, S, Vt = np.linalg.svd(train_images_centered, full_matrices=False)
Variable S contains the singular values of train_images_centered, in descending order.
# four largest singular values
S[:4]
Note that Vt corresponds to $\mathbf{V}^\mathsf{T}$, i.e., it is the transpose of $\mathbf{V}$. We can recover train_images_centered from its singular value decomposition U, S, and Vt.
np.allclose(train_images_centered, U @ np.diag(S) @ Vt)
# alternative:
np.allclose(train_images_centered, (U * S) @ Vt)
Compute the two-dimensional encodings of the images in the MNIST training and the test data set in the two-dimensional latent space spanned by the $M = 2$ principal components of the centered training data, the so-called principal subspace.
Hints:
U, S, and/or Vt.# compute encodings of the training data
train_encodings = train_images_centered @ Vt.T[:, :2]
# compute encodings of the test data
test_images_centered = test_images - train_mean
test_encodings = test_images_centered @ Vt.T[:, :2]
Generate 2D scatter plots of the encodings that show the clusters for different labels in the latent space. You can make use of the function plot_encodings below.
# plot `train_encodings` and `test_encodings` with colorcoding of the corresponding labels
def plot_encodings(train_encodings, train_labels, test_encodings, test_labels):
# create two plots side by side
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 6))
# plot encodings of training data
ax = axes[0]
ax.scatter(
train_encodings[:, 0], train_encodings[:, 1],
c=train_labels, cmap=plt.cm.tab10, vmin=-0.5, vmax=9.5, alpha=0.7
)
ax.set_xlabel("$z_1$")
ax.set_ylabel("$z_2$")
ax.set_title("training data")
# plot encodings of test data
ax = axes[1]
scatter = ax.scatter(
test_encodings[:, 0], test_encodings[:, 1],
c=test_labels, cmap=plt.cm.tab10, vmin=-0.5, vmax=9.5, alpha=0.7
)
ax.set_xlabel("$z_1$")
ax.set_ylabel("$z_2$")
ax.set_title("test data")
# add colorbar
cb = fig.colorbar(scatter, ticks=range(10), ax=axes.ravel().tolist())
cb.ax.set_title("digit")
return fig
plot_encodings(train_encodings, train_labels, test_encodings, test_labels)
plt.show()
Compute the reconstructions of the test images by mapping the encodings of the test data from the latent space back to the space of images.
test_reconstructions = train_mean + test_encodings @ Vt[:2, :]
Plot some test images and their reconstructed counterparts. You can use the function plot_reconstructions below. Which digits can be reconstructed and decoded quite well, and which ones seem to be more challenging? Remember that the reconstructions are obtained by considering only the two principal components.
# plot a grid of random pairs of `originals` and `reconstructions`
def plot_reconstructions(originals, reconstructions, labels, num_rows=4, num_cols=2):
# indices of displayed samples
n = originals.shape[0]
indices = np.random.choice(n, size=num_rows*num_cols, replace=False)
fig, axes = plt.subplots(nrows=num_rows, ncols=num_cols, figsize=(10, 10))
for (idx, ax) in zip(indices, axes.flat):
# extract original, reconstruction, and label
original = originals[idx]
reconstruction = reconstructions[idx]
label = labels[idx]
# configure subplot
ax.set_xticks(())
ax.set_yticks(())
ax.grid(False)
ax.set_title(f"Label: {label}", fontweight='bold')
# plot original and reconstructed image in a grid
grid = np.ones((32, 62))
grid[2:30, 2:30] = original.reshape(28, 28)
grid[2:30, 32:60] = reconstruction.reshape(28, 28)
ax.imshow(grid, vmin=0.0, vmax=1.0, cmap='gray_r')
return fig
plot_reconstructions(test_images, test_reconstructions, test_labels)
plt.show()
The comparison of the original images and their reconstructions provides us with some intuition for how much information is lost by the compression of the images to the two-dimensional latent space. As a less subjective measure we calculate the average squared reconstruction error \begin{equation*} \mathrm{sqerr} := \frac{1}{10000} \sum_{i=1}^{10000} \|\mathbf{x}_i - \tilde{\mathbf{x}}_i\|^2_2 \end{equation*} of the images $\mathbf{x}_i \in {[0,1]}^{784}$ and their reconstructions $\tilde{\mathbf{x}}_i \in \mathbb{R}^{784}$ ($i = 1,\ldots, 10000$) in the MNIST test data set. An advantage of an objective measure such as the average squared reconstruction error is that it enables us to compare the PCA with other models for dimensionality reduction.
What average squared reconstruction error do you get with PCA?
sqerr = ((test_images - test_reconstructions) ** 2).sum(axis=1).mean()
print(f"Average squared reconstruction error: {sqerr}")
In contrast to (regular) PCA, the so-called probabilistic PCA (PPCA) allows a probabilistic interpretation of the principal components. The probabilistic formulation of PCA also allows us to extend the method and alter its underlying assumptions quite easily.
As in exercise 8.1, let $\mathbf{x} \in \mathbb{R}^D$ represent a data sample that we want to decode from a lower dimensional representation $\mathbf{z} \in \mathbb{R}^M$ with $M < D$. The PPCA model assumes that $\mathbf{z}$ is standard normally distributed and $\mathbf{x}$ can be decoded by a noisy linear transformation of $\mathbf{z}$. Mathematically, the model is given by \begin{align*} p(\mathbf{x} \,|\, \mathbf{z}) &= \mathcal{N}\left(\mathbf{x}; \mathbf{W}\mathbf{z} + \boldsymbol{\mu}, \sigma^2 \mathbf{I}_D\right), \\ p(\mathbf{z}) &= \mathcal{N}(\mathbf{z}; \boldsymbol{0}, \mathbf{I}_M), \end{align*} with parameters $\mathbf{W} \in \mathbb{R}^{D \times M}$, $\boldsymbol{\mu} \in \mathbb{R}^D$, and $\sigma^2 > 0$. Michael E. Tipping and Christopher M. Bishop show in "Probabilistic Principal Component Analysis" that for $\sigma^2 \to 0$ the model recovers the standard PCA (but the components of $\mathbf{z}$ might be permuted).
We assume that the data $\mathbf{x}_1, \ldots, \mathbf{x}_N$ is identically and independently distributed according to the PPCA model. In a maximum likelihood setting, one determines the parameters $\mathbf{W}$, $\boldsymbol{\mu}$, and $\sigma^2$ that maximize the likelihood \begin{equation*} p(\mathbf{x}_1, \ldots, \mathbf{x}_N ; \mathbf{W}, \boldsymbol{\mu}, \sigma^2) = \prod_{n=1}^N p(\mathbf{x}_n; \mathbf{W}, \boldsymbol{\mu}, \sigma^2), \end{equation*} or equivalently the log-likelihood \begin{equation*} \log p(\mathbf{x}_1, \ldots, \mathbf{x}_N; \mathbf{W}, \boldsymbol{\mu}, \sigma^2) = \sum_{n=1}^N \log p(\mathbf{x}_n; \mathbf{W}, \boldsymbol{\mu}, \sigma^2). \end{equation*}
(Pen and paper exercise)
Show that for the model of the probabilistic PCA \begin{equation*} p(\mathbf{x}) = \mathcal{N}(\mathbf{x}; \boldsymbol{\mu}, \mathbf{C}), \end{equation*} where $\mathbf{C} = \mathbf{W}\mathbf{W}^\mathsf{T} + \sigma^2 \mathbf{I}_D$.
(Pen and paper exercise)
Show that the distribution of the latent variable $\mathbf{z}$ conditioned on $\mathbf{x}$ is Gaussian as well and given by \begin{equation*} p(\mathbf{z} \,|\, \mathbf{x}) = \mathcal{N}\left(\mathbf{z}; \mathbf{M}^{-1} \mathbf{W}^\mathsf{T} (\mathbf{x} - \boldsymbol{\mu}), \sigma^2 \mathbf{M}^{-1} \right), \end{equation*} where $\mathbf{M} = \mathbf{W}^\mathsf{T} \mathbf{W} + \sigma^2 \mathbf{I}_M$.
In this exercise we estimate the parameters of a Gaussian mixture model with the expectation-maximization (EM) algorithm.
A Gaussian mixture model with $m \geq 1$ components consists of $m$ mixture components $\mathcal{N}(\mu_1, \Sigma_1), \ldots, \mathcal{N}(\mu_m, \Sigma_m)$ and corresponding non-negative mixture weights $w_1, \ldots, w_m$ with $\sum_{i=1}^m w_i = 1$. It has the probability density function \begin{equation*} \operatorname{GMM}(x; w_1, \mu_1, \Sigma_1, \ldots, w_m, \mu_m, \Sigma_m) = \sum_{i=1}^m w_i \mathcal{N}(x; \mu_i, \Sigma_i). \end{equation*} One can obtain a sample $x$ from the Gaussian mixture model with a two-step procedure:
We consider a data set $\mathbf{X} \in \mathbb{R}^{300 \times 2}$ of 300 samples that are generated from a two-dimensional Gaussian mixture model with mixture weights $w_1 = 0.7$ and $w_2 = 0.3$ and mixture components with parameters \begin{equation*} \mu_1 = \begin{bmatrix} 5 \\ 7\end{bmatrix}, \quad \Sigma_1 = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix}, \quad \mu_2 = \begin{bmatrix} 1 \\ 2\end{bmatrix}, \quad \Sigma_2 = \begin{bmatrix} 2 & 0 \\ 0 & 1 \end{bmatrix}. \end{equation*}
def plot_2dnormal(normal, color):
# plot center
plt.plot(normal.mean[0], normal.mean[1], '*', ms=5, color=color)
# get countour grid
x, y = np.mgrid[-3:3:.01, -3:3:.01]
# rescale x, y
x = normal.cov[0,0] * x + normal.mean[0]
y = normal.cov[1,1] * y + normal.mean[1]
# plot countour
pos = np.dstack((x, y))
plt.contour(x, y, normal.pdf(pos), colors=color, levels=3)
# mixture weights
weights = [0.7, 0.3]
# mixture components
component1 = multivariate_normal(mean=[1, 2], cov=[[2, 0], [0, 1]])
component2 = multivariate_normal(mean=[5, 7], cov=[[2, 1], [1, 2]])
components = [component1, component2]
# sample N = 300 samples from the Gaussian mixture model
np.random.seed(1234) # for reproducibility
N = 300
X = np.stack([np.random.choice(components, p=weights).rvs() for _ in range(N)])
plt.figure()
plt.scatter(X[:,0], X[:,1])
plot_2dnormal(component1, color='red')
plot_2dnormal(component2, color='blue')
plt.show()
Implement a function e_step(X, weights, components) that receives as input
X (an array of size $300 \times 2$ in the model above),weights (a list [p, 1 - p] in the model above), andcomponents (a list of two multivariate_normal distributions in the model above).and outputs a matrix of the likelihood of each data point for each mixture component. More concretely, the entry at the $i$th row and $j$th column of the returned matrix should be \begin{equation*} \frac{w_i \mathcal{N}\left(x_j; \mu_i, \Sigma_i\right)}{\sum_{k=1}^m w_k \mathcal{N}\left(x_j; \mu_k , \Sigma_k\right)}. \end{equation*} I.e., in the example here the function should return a matrix of size $2 \times 300$.
This computation corresponds to the expectation step in the EM algorithm.
def e_step(X, weights, components):
# compute unnormalized log probabilities
# (usually it is numerically better to work with `logpdf` instead of `pdf`)
unnormalized_logprobs = [
np.log(w) + component.logpdf(X) for w, component in zip(weights, components)
]
# compute probabilities with softmax function
probs_matrix = softmax(np.vstack(unnormalized_logprobs), axis=0)
return probs_matrix
Based on the output of e_step we can estimate to which mixture component a data point seems to belong.
# evaluate the function on the dataset
probs = e_step(X, weights, components)
# compute to which component data points seem to belong
belong_to = probs.argmax(axis=0)
# plot data
plt.figure()
plt.scatter(X[:, 0], X[:, 1], c=belong_to)
for c in components:
plot_2dnormal(c, color='black')
plt.show()
Implement the M-step of the EM algorithm with a function m_step(X, probs) that receives as input
X (an array of size $300 \times 2$ in the model above) andprobs (output of e_step implemented above, array of size $2 \times 300$ in the model above)and outputs the updated parameter estimates of the Gaussian mixture model, i.e.,
[p, 1 - p] in the model above) andmultivariate_normal distributions in the model above).Hint: The formulas for the updated parameter estimates can be found in eq. 10.16 in http://smlbook.org/.
def m_step(X, probs):
# sum of probs for each component
sum_probs = probs.sum(axis=1)
# compute weights (eq. 10.16a): average of probs for each component
weights = sum_probs / probs.shape[1]
# compute means of components (eq. 10.16b): weighted average of data
mus = (probs @ X) / sum_probs[:, None]
# compute covariance matrices of components (eq. 10.16c):
# weighted covariance matrix of data
centeredX = X - mus[:, None, :] # size ncomponents x nsamples x ndims
probs_centeredX = probs[..., None] * centeredX
covs = (probs_centeredX.transpose(0, 2, 1) @ centeredX) / sum_probs[:, None, None]
# add multivariate_normal component
components = [
multivariate_normal(mean=mu, cov=cov) for mu, cov in zip(mus, covs)
]
return weights, components
We can perform a sanity check:
weights, components = m_step(X, probs)
print('weights:')
print(weights)
for i, c in enumerate(components):
print('')
print('Normal {}'.format(i+1))
print('- mean:')
print(c.mean)
print('- cov:')
print(c.cov)
If everything went right, you should obtain estimates close to the ones used to generate the dataset:
Run the code below to plot 3 iterations of the EM algorithm.
# initial parameter estimates
component1_estimated = multivariate_normal(mean=[0, 0], cov=np.eye(2))
component2_estimated = multivariate_normal(mean=[10, 10], cov=np.eye(2))
components_estimated = [component1_estimated, component2_estimated]
weights_estimated = [0.5, 0.5]
for i in range(3):
# expectation step
probs = e_step(X, weights_estimated, components_estimated)
belong_to = probs.argmax(axis=0)
# plot estimates
plt.figure()
plt.scatter(X[:, 0], X[:, 1], c=belong_to)
for c in components_estimated:
plot_2dnormal(c, color='black')
plt.title(f"iteration {i}")
plt.show()
# maximization step
weights_estimated, components_estimated = m_step(X, probs)
Adapt the code in exercise 8.3 c) and use the EM algorithm to estimate the parameters of a Gaussian mixture model for the two-dimensional encodings of the MNIST training data set computed in exercise 8.1. You have to choose the number of mixture components and the initial parameter estimates.
# initial parameter estimates
m = 3
components_estimated = [multivariate_normal(mean=[i, i], cov=np.eye(2)) for i in range(m)]
weights_estimated = [1 / m for _ in range(m)]
for i in range(5):
# expectation step
probs = e_step(train_encodings, weights_estimated, components_estimated)
belong_to = probs.argmax(axis=0)
# plot estimates
plt.figure()
plt.scatter(train_encodings[:, 0], train_encodings[:, 1], c=belong_to)
for c in components_estimated:
plot_2dnormal(c, color='black')
plt.title(f"iteration {i}")
plt.show()
# maximization step
weights_estimated, components_estimated = m_step(train_encodings, probs)
The EM algorithm is not restricted to clustering. In this exercise we use it for a problem that combines the Gaussian mixture model from exercise 8.3 with the linear regression models from the earlier sessions: the data consists of pairs $(x_n, y_n)$ that are generated by several linear relationships, but for each data point we do not know which relationship generated it.
We consider a mixture of $K$ linear regression models \begin{align*} p(c_n = k) &= \pi_k, \\ p(y_n \,|\, x_n, c_n = k) &= \mathcal{N}\left(y_n; \mathbf{w}_k^\mathsf{T} \boldsymbol{\phi}(x_n), \beta_k^{-1}\right), \end{align*} where $c_n \in \{1, \ldots, K\}$ is a latent variable that indicates which component generated data point $n$ and $\boldsymbol{\phi}(x) = [1 \;\, x]^\mathsf{T}$ is the feature vector. The parameters of the model are the mixture weights $\pi_1, \ldots, \pi_K \geq 0$ with $\sum_{k=1}^K \pi_k = 1$, the regression weights $\mathbf{w}_1, \ldots, \mathbf{w}_K \in \mathbb{R}^2$, and the noise precisions $\beta_1, \ldots, \beta_K > 0$. Marginalizing out $c_n$ yields \begin{equation*} p(y_n \,|\, x_n) = \sum_{k=1}^K \pi_k \mathcal{N}\left(y_n; \mathbf{w}_k^\mathsf{T} \boldsymbol{\phi}(x_n), \beta_k^{-1}\right). \end{equation*} Note that we denote the mixture weights by $\pi_k$ (instead of $w_k$ as in exercise 8.3) to avoid confusion with the regression weights $\mathbf{w}_k$.
As in the earlier sessions, we collect the feature vectors of $N$ data points in the matrix $\boldsymbol{\Phi} \in \mathbb{R}^{N \times 2}$ with rows $\boldsymbol{\phi}(x_n)^\mathsf{T}$, and the targets in the vector $\mathbf{y} = [y_1 \cdots y_N]^\mathsf{T}$.
The following code generates $N = 200$ data points from a mixture of two lines with mixture weights $\pi_1 = 0.6$ and $\pi_2 = 0.4$, regression weights $\mathbf{w}_1 = [1 \;\, 1.5]^\mathsf{T}$ and $\mathbf{w}_2 = [3 \;\, {-1}]^\mathsf{T}$, and noise standard deviations $\beta_1^{-1/2} = 0.5$ and $\beta_2^{-1/2} = 0.8$.
# true parameters (row k of `true_W` contains intercept and slope of line k)
true_pis = np.array([0.6, 0.4])
true_W = np.array([[1.0, 1.5], [3.0, -1.0]])
true_betas = np.array([1 / 0.5**2, 1 / 0.8**2])
# sample N = 200 data points from the mixture of linear regressions
np.random.seed(1234) # for reproducibility
N = 200
x = np.random.uniform(-3, 3, size=N)
c = np.random.choice(2, size=N, p=true_pis)
Phi = np.column_stack([np.ones(N), x]) # feature matrix with rows [1, x_n]
y = np.sum(Phi * true_W[c], axis=1) + np.random.normal(size=N) / np.sqrt(true_betas[c])
plt.figure()
plt.scatter(x, y)
plt.xlabel("$x$")
plt.ylabel("$y$")
plt.show()
(Pen and paper exercise)
Derive the EM algorithm for the mixture of linear regressions.
Hints:
Solution:
E-step: By Bayes' theorem, \begin{equation*} p(c_n = k \,|\, x_n, y_n) = \frac{p(y_n \,|\, x_n, c_n = k) \, p(c_n = k)}{\sum_{j=1}^K p(y_n \,|\, x_n, c_n = j) \, p(c_n = j)}, \end{equation*} which is exactly the stated expression for $r_{nk}$.
M-step: Up to terms that do not depend on the parameters, \begin{equation*} Q = \sum_{k=1}^K \left[ N_k \log \pi_k + \frac{N_k}{2} \log \beta_k - \frac{\beta_k}{2} \sum_{n=1}^N r_{nk} {\left(y_n - \mathbf{w}_k^\mathsf{T} \boldsymbol{\phi}(x_n)\right)}^2 \right]. \end{equation*} The regression weights $\mathbf{w}_k$ only appear in the last term, i.e., we have to minimize the weighted sum of squares \begin{equation*} \sum_{n=1}^N r_{nk} {\left(y_n - \mathbf{w}_k^\mathsf{T} \boldsymbol{\phi}(x_n)\right)}^2 = {(\mathbf{y} - \boldsymbol{\Phi} \mathbf{w}_k)}^\mathsf{T} \mathbf{R}_k (\mathbf{y} - \boldsymbol{\Phi} \mathbf{w}_k), \end{equation*} in which data point $n$ is weighted by how responsible component $k$ is for it. Setting the gradient $-2 \boldsymbol{\Phi}^\mathsf{T} \mathbf{R}_k (\mathbf{y} - \boldsymbol{\Phi} \mathbf{w}_k)$ to zero gives \begin{equation*} \mathbf{w}_k = {\left(\boldsymbol{\Phi}^\mathsf{T} \mathbf{R}_k \boldsymbol{\Phi}\right)}^{-1} \boldsymbol{\Phi}^\mathsf{T} \mathbf{R}_k \mathbf{y}. \end{equation*} For $K = 1$ all responsibilities are $r_{n1} = 1$, i.e., $\mathbf{R}_1 = \mathbf{I}_N$, and we recover the least squares solution ${(\boldsymbol{\Phi}^\mathsf{T} \boldsymbol{\Phi})}^{-1} \boldsymbol{\Phi}^\mathsf{T} \mathbf{y}$, which is the maximum likelihood estimate of a single linear regression model with Gaussian noise.
Setting the derivative of $Q$ with respect to $\beta_k$ to zero gives $N_k / (2\beta_k) - \frac{1}{2} \sum_{n=1}^N r_{nk} {(y_n - \mathbf{w}_k^\mathsf{T} \boldsymbol{\phi}(x_n))}^2 = 0$, i.e., \begin{equation*} \frac{1}{\beta_k} = \frac{1}{N_k} \sum_{n=1}^N r_{nk} {\left(y_n - \mathbf{w}_k^\mathsf{T} \boldsymbol{\phi}(x_n)\right)}^2, \end{equation*} the weighted mean squared residual of component $k$ (evaluated at the updated $\mathbf{w}_k$).
Maximizing $\sum_{k=1}^K N_k \log \pi_k$ subject to $\sum_{k=1}^K \pi_k = 1$ (e.g., with a Lagrange multiplier) gives, as for the Gaussian mixture model, \begin{equation*} \pi_k = \frac{N_k}{N}. \end{equation*}
Implement the EM algorithm from (a):
e_step_regression(Phi, y, pis, W, betas) that returns the $K \times N$ matrix of responsibilities $r_{nk}$ (the entry in the $k$th row and $n$th column should be $r_{nk}$, analogously to e_step in exercise 8.3),m_step_regression(Phi, y, probs) that receives the responsibilities and returns the updated parameters pis (array of size $K$), W (array of size $K \times 2$ whose $k$th row is $\mathbf{w}_k^\mathsf{T}$), and betas (array of size $K$), andlog_likelihood_regression(Phi, y, pis, W, betas) that returns the log-likelihood $\sum_{n=1}^N \log p(y_n \,|\, x_n)$.Hint: As in exercise 8.3 it is numerically better to work with log-probabilities, e.g., with norm.logpdf, softmax, and logsumexp.
def component_logprobs_regression(Phi, y, pis, W, betas):
# compute K x N matrix with entries log(pi_k) + log N(y_n; w_k^T phi(x_n), 1 / beta_k)
means = W @ Phi.T
stds = 1 / np.sqrt(betas)
return np.log(pis)[:, None] + norm.logpdf(y, loc=means, scale=stds[:, None])
def e_step_regression(Phi, y, pis, W, betas):
# K x N matrix of responsibilities r_nk
probs = ...
# normalize the unnormalized log probabilities of each data point with the softmax function
probs = softmax(component_logprobs_regression(Phi, y, pis, W, betas), axis=0)
return probs
def log_likelihood_regression(Phi, y, pis, W, betas):
# log-likelihood sum_n log p(y_n | x_n)
log_likelihood = ...
# log p(y_n | x_n) = log sum_k exp(log(pi_k) + log N(y_n; w_k^T phi(x_n), 1 / beta_k))
log_likelihood = logsumexp(component_logprobs_regression(Phi, y, pis, W, betas), axis=0).sum()
return log_likelihood
def m_step_regression(Phi, y, probs):
# mixture weights, array of size K
pis = ...
# regression weights (weighted least squares), array of size K x 2 whose kth row is w_k^T
W = ...
# noise precisions, array of size K
betas = ...
# sum of responsibilities for each component
sum_probs = probs.sum(axis=1)
# update mixture weights
pis = sum_probs / probs.shape[1]
# update regression weights (weighted least squares) and noise precisions
W = np.stack([
np.linalg.solve(Phi.T @ (r[:, None] * Phi), Phi.T @ (r * y)) for r in probs
])
squared_residuals = (y - W @ Phi.T) ** 2 # size K x N
betas = sum_probs / (probs * squared_residuals).sum(axis=1)
return pis, W, betas
We use the following functions to plot the data together with the estimated lines, and to run the EM algorithm for a given number of iterations while tracking the log-likelihood. Similar to exercise 8.3, the data points are colored according to the component that they most likely belong to.
# plot data points colored by most likely component and the lines of all components
def plot_regression_mixture(x, y, W, probs, ax):
belong_to = probs.argmax(axis=0)
ax.scatter(x, y, c=belong_to, cmap=plt.cm.tab10, vmin=-0.5, vmax=9.5, alpha=0.5)
xs = np.linspace(x.min(), x.max(), 2)
for k, w in enumerate(W):
ax.plot(xs, w[0] + w[1] * xs, color=plt.cm.tab10(k), linewidth=3)
ax.set_xlabel("$x$")
ax.set_ylabel("$y$")
# run `num_iterations` iterations of the EM algorithm with the given M-step
def run_em_regression(Phi, y, pis, W, betas, num_iterations, m_step=None):
if m_step is None:
m_step = m_step_regression
log_likelihoods = [log_likelihood_regression(Phi, y, pis, W, betas)]
for _ in range(num_iterations):
probs = e_step_regression(Phi, y, pis, W, betas)
pis, W, betas = m_step(Phi, y, probs)
log_likelihoods.append(log_likelihood_regression(Phi, y, pis, W, betas))
return pis, W, betas, np.array(log_likelihoods)
Run the code below to plot the first iterations of the EM algorithm.
# initial parameter estimates
pis_init = np.array([0.5, 0.5])
W_init = np.array([[0.0, 1.0], [0.0, -1.0]])
betas_init = np.array([1.0, 1.0])
pis_estimated, W_estimated, betas_estimated = pis_init, W_init, betas_init
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(15, 8), sharex=True, sharey=True)
for i, ax in enumerate(axes.flat):
# expectation step
probs = e_step_regression(Phi, y, pis_estimated, W_estimated, betas_estimated)
# plot estimates
plot_regression_mixture(x, y, W_estimated, probs, ax)
ax.set_title(f"iteration {i}")
# maximization step
pis_estimated, W_estimated, betas_estimated = m_step_regression(Phi, y, probs)
plt.show()
Run the EM algorithm for 100 iterations with the same initial parameter estimates and plot the log-likelihood as a function of the iterations. Does the log-likelihood ever decrease? Compare the final parameter estimates with the parameters that were used to generate the data.
pis_ml, W_ml, betas_ml, log_likelihoods = run_em_regression(
Phi, y, pis_init, W_init, betas_init, num_iterations=100
)
plt.figure()
plt.plot(log_likelihoods)
plt.xlabel("iteration")
plt.ylabel("log-likelihood")
plt.show()
print("log-likelihood never decreases:", np.all(np.diff(log_likelihoods) >= -1e-9))
print("final log-likelihood:", log_likelihoods[-1])
print("mixture weights:", pis_ml)
print("regression weights:")
print(W_ml)
print("noise standard deviations:", 1 / np.sqrt(betas_ml))
The log-likelihood increases monotonically, as guaranteed by the EM algorithm, and converges after a few iterations. The estimates are close to the true parameters: mixture weights close to $[0.6, 0.4]$, regression weights close to $[1, 1.5]$ and $[3, -1]$, and noise standard deviations close to $0.5$ and $0.8$. The largest uncertainty is in the region around $x = 0.8$ where the two lines cross, since there the data points could have been generated by either line.
(Pen and paper exercise)
Suppose that all $K$ components are initialized with the same regression weights and noise precisions, i.e., $\mathbf{w}_k = \mathbf{w}$ and $\beta_k = \beta$ for all $k$ (the mixture weights $\pi_k$ may be arbitrary). Show that the EM algorithm never leaves such a configuration. What are the parameter estimates after one iteration, and which well-known estimator do you obtain?
Verify your answer numerically by running the EM algorithm with W_init = np.zeros((2, 2)). How can this problem be avoided in practice?
Solution:
If $\mathbf{w}_k = \mathbf{w}$ and $\beta_k = \beta$ for all $k$, then the Gaussian factors $\mathcal{N}(y_n; \mathbf{w}^\mathsf{T} \boldsymbol{\phi}(x_n), \beta^{-1})$ in the numerator and denominator of $r_{nk}$ are the same for all components and cancel, i.e., \begin{equation*} r_{nk} = \frac{\pi_k}{\sum_{j=1}^K \pi_j} = \pi_k \end{equation*} for all data points $n$. Hence $\mathbf{R}_k = \pi_k \mathbf{I}_N$ and $N_k = N \pi_k$, and the M-step yields \begin{align*} \pi_k &= \frac{N \pi_k}{N} = \pi_k, \\ \mathbf{w}_k &= {\left(\pi_k \boldsymbol{\Phi}^\mathsf{T} \boldsymbol{\Phi}\right)}^{-1} \pi_k \boldsymbol{\Phi}^\mathsf{T} \mathbf{y} = {\left(\boldsymbol{\Phi}^\mathsf{T} \boldsymbol{\Phi}\right)}^{-1} \boldsymbol{\Phi}^\mathsf{T} \mathbf{y}, \\ \frac{1}{\beta_k} &= \frac{1}{N} \sum_{n=1}^N {\left(y_n - \mathbf{w}_k^\mathsf{T} \boldsymbol{\phi}(x_n)\right)}^2. \end{align*} The mixture weights do not change, and all components obtain the same regression weights and noise precision, namely the maximum likelihood estimates of a single linear regression model, i.e., the ordinary least squares solution and the mean squared residual. Since all components are identical again, the same argument applies in every subsequent iteration: the EM algorithm is stuck at a stationary point of the likelihood that effectively describes the data by a single line.
In practice, the symmetry is broken by initializing the components differently, e.g., randomly, and usually one runs the EM algorithm from several initializations and keeps the solution with the largest log-likelihood.
# symmetric initialization
pis_sym, W_sym, betas_sym, log_likelihoods_sym = run_em_regression(
Phi, y, pis_init, np.zeros((2, 2)), betas_init, num_iterations=100
)
print("regression weights:")
print(W_sym)
print("least squares solution:", np.linalg.lstsq(Phi, y, rcond=None)[0])
print("noise standard deviations:", 1 / np.sqrt(betas_sym))
print(f"final log-likelihood: {log_likelihoods_sym[-1]} (compared to {log_likelihoods[-1]} in (b))")
# some random initializations
for seed in range(5):
rng = np.random.default_rng(seed)
_, W_random, _, log_likelihoods_random = run_em_regression(
Phi, y, pis_init, rng.normal(scale=2, size=(2, 2)), betas_init, num_iterations=100
)
print(f"random initialization {seed}: final log-likelihood {log_likelihoods_random[-1]:.2f}")
We now fit a mixture of $K = 3$ linear regressions to the same data. We initialize the first two components as in (b), and the third component with a line that passes exactly through the first two data points and a large noise precision $\beta_3 = 10^4$.
# line through the first two data points
slope = (y[1] - y[0]) / (x[1] - x[0])
w3 = np.array([y[0] - slope * x[0], slope])
# initial parameter estimates
pis_init3 = np.ones(3) / 3
W_init3 = np.vstack([W_init, w3])
betas_init3 = np.array([1.0, 1.0, 1e4])
Run the EM algorithm for (up to) 20 iterations with this initialization and plot the log-likelihood. What happens to the estimate of $\beta_3$? Compare the final log-likelihood with the one obtained in (b). Is the solution with larger log-likelihood the better model of the data?
(Pen and paper exercise) Show that the likelihood $\prod_{n=1}^N p(y_n \,|\, x_n)$ of the mixture of linear regressions with $K \geq 2$ components is unbounded. What does this imply for maximum likelihood estimation in this model?
pis_collapse, W_collapse, betas_collapse, log_likelihoods_collapse = run_em_regression(
Phi, y, pis_init3, W_init3, betas_init3, num_iterations=19
)
print("noise precisions:", betas_collapse)
print("mixture weights:", pis_collapse)
print(f"final log-likelihood: {log_likelihoods_collapse[-1]} (compared to {log_likelihoods[-1]} in (b))")
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 5))
axes[0].plot(log_likelihoods_collapse, label="K = 3")
axes[0].axhline(log_likelihoods[-1], color="k", linestyle="--", label="final log-likelihood in (b)")
axes[0].set_xlabel("iteration")
axes[0].set_ylabel("log-likelihood")
axes[0].legend()
probs = e_step_regression(Phi, y, pis_collapse, W_collapse, betas_collapse)
plot_regression_mixture(x, y, W_collapse, probs, axes[1])
plt.show()
Solution:
The third component collapses onto the first two data points: its line keeps passing through them and $\beta_3$ grows to an astronomically large value (around $10^{30}$ after 19 iterations), i.e., the noise standard deviation of the third component goes to zero. In the 20th iteration the residuals of the third component are exactly zero in floating point arithmetic, and we obtain $\beta_3 = \infty$ and a log-likelihood of nan. Before that, the log-likelihood becomes larger than the log-likelihood of the solution in (b), even though the solution in (b) is clearly the better description of the data - the third component explains just two data points perfectly and nothing else.
This is not a coincidence: choose any two data points $n \neq m$ with $x_n \neq x_m$ and let $\mathbf{w}_K$ be the regression weights of the line that passes through both, i.e., $y_n = \mathbf{w}_K^\mathsf{T} \boldsymbol{\phi}(x_n)$ and $y_m = \mathbf{w}_K^\mathsf{T} \boldsymbol{\phi}(x_m)$. Fix $\pi_K \in (0, 1)$ and the parameters of the other components. Then \begin{equation*} p(y_n \,|\, x_n) \geq \pi_K \mathcal{N}\left(y_n; \mathbf{w}_K^\mathsf{T} \boldsymbol{\phi}(x_n), \beta_K^{-1}\right) = \pi_K \sqrt{\frac{\beta_K}{2\pi}} \xrightarrow{\beta_K \to \infty} \infty, \end{equation*} and similarly for data point $m$, whereas for all other data points $p(y_i \,|\, x_i) \geq (1 - \pi_K) \cdot (\text{mixture of the other } K - 1 \text{ components})$ stays bounded away from zero. Hence the likelihood goes to infinity as $\beta_K \to \infty$. (With two regression weights per line, any two data points can be fitted exactly; the same singularity appears in Gaussian mixture models when a component collapses onto a single data point.)
Thus the maximum likelihood estimate does not exist, and the EM algorithm can converge to such degenerate solutions. The "good" solution in (b) is only a local maximum of the likelihood.
The singularity in (d) can be avoided by putting a prior on the parameters and computing a maximum a posteriori (MAP) estimate instead. We use the Gauss-Gamma prior from the exercises on Bayesian linear regression (with prior mean $\boldsymbol{0}$ and prior covariance matrix $\lambda^{-1} \mathbf{I}_2$) independently for each component, \begin{equation*} p(\mathbf{w}_k, \beta_k) = \mathcal{N}\left(\mathbf{w}_k; \boldsymbol{0}, {(\lambda \beta_k)}^{-1} \mathbf{I}_2\right) \operatorname{Gam}(\beta_k; a_0, b_0), \end{equation*} with hyperparameters $\lambda > 0$, $a_0 \geq 1$, and $b_0 > 0$, where $\operatorname{Gam}(\beta; a, b) = \frac{1}{\Gamma(a)} b^a \beta^{a - 1} e^{-b\beta}$. The EM algorithm can be used to compute the MAP estimate: the E-step does not change, and in the M-step we maximize $Q + \sum_{k=1}^K \log p(\mathbf{w}_k, \beta_k)$ instead of $Q$.
(Pen and paper exercise) Derive the updates of $\mathbf{w}_k$ and $\beta_k$ in the M-step (the update of the mixture weights $\pi_k$ does not change). Which regularized version of least squares do you obtain for $\mathbf{w}_k$? Explain why the collapse from (d) can not occur anymore.
Implement a function m_step_regression_map(Phi, y, probs) with the MAP updates, using $\lambda = 1$, $a_0 = 2$, and $b_0 = 0.5$, and run the EM algorithm with the initialization from (d) for 100 iterations. What happens to the third component?
Solution:
Up to terms that do not depend on $\mathbf{w}_k$ and $\beta_k$, the log prior of component $k$ is \begin{equation*} \log p(\mathbf{w}_k, \beta_k) = \frac{D}{2} \log \beta_k - \frac{\lambda \beta_k}{2} \|\mathbf{w}_k\|_2^2 + (a_0 - 1) \log \beta_k - b_0 \beta_k, \end{equation*} where $D = 2$ is the dimension of the feature vector. Adding it to the terms of $Q$ that depend on the parameters of component $k$ (see (a)), we have to maximize \begin{equation*} \left(\frac{N_k + D}{2} + a_0 - 1\right) \log \beta_k - \frac{\beta_k}{2} \left[{(\mathbf{y} - \boldsymbol{\Phi} \mathbf{w}_k)}^\mathsf{T} \mathbf{R}_k (\mathbf{y} - \boldsymbol{\Phi} \mathbf{w}_k) + \lambda \|\mathbf{w}_k\|_2^2 + 2 b_0\right]. \end{equation*} For any $\beta_k > 0$, the maximizing $\mathbf{w}_k$ minimizes the weighted sum of squares plus the penalty $\lambda \|\mathbf{w}_k\|_2^2$, which gives the weighted ridge regression solution \begin{equation*} \mathbf{w}_k = {\left(\boldsymbol{\Phi}^\mathsf{T} \mathbf{R}_k \boldsymbol{\Phi} + \lambda \mathbf{I}_D\right)}^{-1} \boldsymbol{\Phi}^\mathsf{T} \mathbf{R}_k \mathbf{y} \end{equation*} (cf. the exercise on regularization and priors). Note that thanks to the scaling of the prior covariance matrix with $\beta_k^{-1}$ it does not depend on $\beta_k$. Setting the derivative with respect to $\beta_k$ to zero gives \begin{equation*} \frac{1}{\beta_k} = \frac{\sum_{n=1}^N r_{nk} {\left(y_n - \mathbf{w}_k^\mathsf{T} \boldsymbol{\phi}(x_n)\right)}^2 + \lambda \|\mathbf{w}_k\|_2^2 + 2 b_0}{N_k + D + 2 a_0 - 2}. \end{equation*} Since the numerator is at least $2 b_0 > 0$ and the denominator is at most $N + D + 2 a_0 - 2$, the noise variance $\beta_k^{-1}$ is bounded from below by $2 b_0 / (N + D + 2 a_0 - 2) > 0$ in every iteration, so a component can not collapse onto a few data points anymore. (Equivalently: the log prior $(a_0 - 1) \log \beta_k - b_0 \beta_k$ goes to $-\infty$ linearly in $\beta_k$, which dominates the $\log \beta_k$ growth of the log-likelihood.)
In the experiment below the third component is not needed to explain the data: its mixture weight shrinks towards zero and its regression weights are pulled to the prior mean $\boldsymbol{0}$. The other two components are estimated as in (b). Note that the EM algorithm now increases the log posterior, so the log-likelihood that we track is not guaranteed to increase monotonically anymore.
def m_step_regression_map(Phi, y, probs, lam=1.0, a0=2.0, b0=0.5):
D = Phi.shape[1]
# mixture weights (unchanged), array of size K
pis = ...
# regression weights, array of size K x 2 whose kth row is w_k^T
W = ...
# noise precisions, array of size K
betas = ...
# sum of responsibilities for each component
sum_probs = probs.sum(axis=1)
# update mixture weights (unchanged)
pis = sum_probs / probs.shape[1]
# update regression weights (weighted ridge regression) and noise precisions
W = np.stack([
np.linalg.solve(Phi.T @ (r[:, None] * Phi) + lam * np.eye(D), Phi.T @ (r * y)) for r in probs
])
squared_residuals = (y - W @ Phi.T) ** 2 # size K x N
betas = (sum_probs + D + 2 * a0 - 2) / (
(probs * squared_residuals).sum(axis=1) + lam * (W ** 2).sum(axis=1) + 2 * b0
)
return pis, W, betas
pis_map, W_map, betas_map, log_likelihoods_map = run_em_regression(
Phi, y, pis_init3, W_init3, betas_init3, num_iterations=100, m_step=m_step_regression_map
)
print("mixture weights:", pis_map)
print("regression weights:")
print(W_map)
print("noise standard deviations:", 1 / np.sqrt(betas_map))
probs = e_step_regression(Phi, y, pis_map, W_map, betas_map)
fig, ax = plt.subplots()
plot_regression_mixture(x, y, W_map[:2], probs, ax)
plt.show()
Finally, we use the mixture of linear regressions for a quite different purpose: robust regression. The following data set is generated from a single line $y = 2 + 0.5 x$ with small noise, but it is contaminated with 15 outliers.
np.random.seed(1) # for reproducibility
N_inliers, N_outliers = 40, 15
# inliers
x_robust = np.random.uniform(0, 10, size=N_inliers + N_outliers)
y_robust = 2 + 0.5 * x_robust + np.random.normal(scale=0.4, size=N_inliers + N_outliers)
# outliers
x_robust[N_inliers:] = np.random.uniform(5, 10, size=N_outliers)
y_robust[N_inliers:] = np.random.uniform(-6, 2, size=N_outliers)
Phi_robust = np.column_stack([np.ones_like(x_robust), x_robust])
plt.figure()
plt.scatter(x_robust, y_robust)
plt.xlabel("$x$")
plt.ylabel("$y$")
plt.show()
Compute the least squares estimate of the regression weights of a single line and plot it together with the data. Then fit a mixture of $K = 2$ linear regressions with your implementation from (b), where you initialize both components with the least squares estimate, the mixture weights with $[0.5, 0.5]$, and the noise precisions with $[1, 0.01]$. Why does this initialization not suffer from the problem in (c)?
Plot the line of the component with the largest noise precision together with the least squares line. Visualize for each data point the probability that it is an outlier, i.e., that it was not generated by this component.
Hint: This idea is discussed in detail in the (quite entertaining) article Data analysis recipes: Fitting a model to data by Hogg, Bovy, and Lang.
# least squares estimate
w_ls = np.linalg.lstsq(Phi_robust, y_robust, rcond=None)[0]
# mixture of two linear regressions, initialized at the least squares estimate
pis_robust, W_robust, betas_robust, _ = run_em_regression(
Phi_robust, y_robust,
np.array([0.5, 0.5]), np.stack([w_ls, w_ls]), np.array([1.0, 0.01]),
num_iterations=200,
)
print("least squares estimate:", w_ls)
print("regression weights:")
print(W_robust)
print("noise standard deviations:", 1 / np.sqrt(betas_robust))
# probability of being an outlier = probability of not belonging to the component with the smallest noise
k = betas_robust.argmax()
probs = e_step_regression(Phi_robust, y_robust, pis_robust, W_robust, betas_robust)
outlier_probs = 1 - probs[k]
plt.figure()
plt.scatter(x_robust, y_robust, c=outlier_probs, cmap="coolwarm", vmin=0, vmax=1)
plt.colorbar(label="outlier probability")
xs = np.linspace(0, 10, 2)
plt.plot(xs, w_ls[0] + w_ls[1] * xs, "k--", label="least squares")
plt.plot(xs, W_robust[k, 0] + W_robust[k, 1] * xs, "k", label="mixture of regressions")
plt.plot(xs, 2 + 0.5 * xs, "g:", label="true line")
plt.xlabel("$x$")
plt.ylabel("$y$")
plt.legend()
plt.show()
Solution:
The least squares estimate is heavily affected by the outliers: they pull the line down, such that it describes neither the inliers nor the outliers. The mixture of regressions instead assigns the outliers to the component with the large noise variance, which acts as a "background" component, and the other component recovers the true line $y = 2 + 0.5x$ almost exactly. The responsibilities provide, for free, a probability for each data point of being an outlier, and all outliers are identified correctly.
Even though both components are initialized with the same regression weights, the configuration is not symmetric as in (c) since the noise precisions differ: data points close to the line are more likely under the component with the small noise variance, whereas data points far away from the line are more likely under the component with the large noise variance. Hence the responsibilities depend on the data points and the components separate in the subsequent M-steps.