11. Latent Variable Models and MLE#

This chapter is adapted from AM207 (Harvard, Fall 2021). Watch the recorded lecture.

In this chapter

  1. Motivation for Latent Variable Models

  2. Common Latent Variable Models

  3. Maximum Likelihood Estimation for Latent Variable Models: Expectation Maximization

  4. Mixture of Gaussians

Hide code cell content

### Import basic libraries
import numpy as np
import scipy as sp
import pandas as pd
import sklearn as sk
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
%matplotlib inline

11.1. Motivation for Latent Variable Models#

A Model for Birth Weights#

Recall our model for birth weights, \(Y_1,\ldots, Y_N\). We posited that the birth weights are iid normally distributed with known \(\sigma^2\), \(Y_n \sim \mathcal{N}(\mu, 1)\).

Compare the maximum likelihood model and the Bayesian model for birth weight. Which model would you use to make clinical decisions? What’s hard about this comparison?

../_images/compare.jpg

A Similarity Measure for Distributions: Kullback–Leibler Divergence#

Visually comparing models to the empirical distribution of the data is impractical. Fortunately, there are a large number of quantitative measures for comparing two distributions, these are called divergence measures. For example, the Kullback–Leibler (KL) Divergence is defined for two distributions \(p(\theta)\) and \(q(\theta)\) supported on \(\Theta\) as:

\[ D_{\text{KL}}[q \,\|\, p] = \int_{\Theta} \log\left[\frac{q(\theta)}{p(\theta)} \right] q(\theta)d\theta \]

The KL-divergence \(D_{\text{KL}}[q \,\|\, p]\) is bounded below by 0, which happens if and only if \(q=p\). The KL-divergence also has information theoretic interpretations.

Note: The KL-divergence is defined in terms of the pdf’s of \(p\) and \(q\). If \(p\) is a distribution from which we only have samples and not the pdf (like the empirical distribution), we can nonetheless estimate \(D_{\text{KL}}[q \,\|\, p]\). Techniques that estimate the KL-divergence from samples are called non-parametric.

Class Membership as a Latent Variable#

We observe that there are three clusters in the data. We posit that there are three classes of infants in the study: infants with low birth weights, infants with normal birth weights and those with high birth weights. The numbers of infants in the classes are not equal.

For each observation \(Y_n\), we model its class membership \(Z_n\) as a categorical variable,

\[Z_n\sim Cat(\pi),\]

where \(\pi_i\) in \(\pi = [\pi_1, \pi_2, \pi_3]\) is the class proportion. Note that we don’t have the class membership \(Z_n\) in the data! So \(Z_n\) is called a latent variable.

Depending on the class, the \(n\)-th birth weight \(Y_n\) will have a different normal distribution,

\[ Y_n | Z_n \sim \mathcal{N}\left(\mu_{Z_n}, \sigma^2_{Z_n}\right) \]

where \(\mu_{Z_n}\) is one of the three class means \([\mu_1, \mu_2, \mu_3]\) and \(\sigma^2_{Z_n}\) is one of the three class variances \([\sigma^2_1, \sigma^2_2, \sigma^2_3]\).

11.2. Common Latent Variable Models#

Latent Variable Models#

Models that include an observed variable \(Y\) and at least one unobserved variable \(Z\) are called latent variable models. In general, our model can allow \(Y\) and \(Z\) to interact in many different ways. In this chapter, we will study models with one type of interaction:

../_images/graphical_model.jpg

Item-Response Models#

In item-response models, we measure an real-valued unobserved trait \(Z\) of a subject by performing a series of experiments with binary observable outcomes, \(Y\):

\[\begin{split}\begin{aligned} Z_n &\sim \mathcal{N}(\mu, \sigma^2),\\ \theta_n &= g(Z_n)\\ Y_n|Z_n &\sim Ber(\theta_n), \end{aligned}\end{split}\]

where \(n=1, \ldots, N\) and \(g\) is some fixed function of \(Z_n\).

Applications#

Item response models are used to model the way “underlying intelligence” \(Z\) relates to scores \(Y\) on IQ tests.

Item response models can also be used to model the way “suicidality” \(Z\) relates to answers on mental health surveys. Building a good model may help to infer when a patient is at psychiatric risk based on in-take surveys at points of care through out the health-care system.

Factor Analysis Models#

In factor analysis models, we posit that the observed data \(Y\) with many measurements is generated by a small set of unobserved factors \(Z\):

\[\begin{split}\begin{aligned} Z_n &\sim \mathcal{N}(0, I),\\ Y_n|Z_n &\sim \mathcal{N}(\mu + \Lambda Z_n, \Phi), \end{aligned}\end{split}\]

where \(n=1, \ldots, N\), \(Z_n\in \mathbb{R}^{D'}\) and \(Y_n\in \mathbb{R}^{D}\). We typically assume that \(D'\) is much smaller than \(D\).

Applications#

Factor analysis models are useful for biomedical data, where we typically measure a large number of characteristics of a patient (e.g. blood pressure, heart rate, etc), but these characteristics are all generated by a small list of health factors (e.g. diabetes, cancer, hypertension etc). Building a good model means we may be able to infer the list of health factors of a patient from their observed measurements.

11.3. Maximum Likelihood Estimation for Latent Variable Models: Expectation Maximization#

The Expectation Maximization Algorithm#

The expectation maximization (EM) algorithm maximize the ELBO of the model,

../_images/graphical_model.jpg
  1. Initialization: Pick \(\theta_0\), \(\phi_0\).

  2. Repeat \(i=1, \ldots, I\) times:

    E-Step:

    \[q_{\text{new}}(Z_n) = \underset{q}{\mathrm{argmax}}\; ELBO(\theta_{\text{old}}, \phi_{\text{old}}, q) = p(Z_n|Y_n, \theta_{\text{old}}, \phi_{\text{old}})\]

    M-Step:

    \[\begin{split}\begin{aligned} \theta_{\text{new}}, \phi_{\text{new}} &= \underset{\theta, \phi}{\mathrm{argmax}}\; ELBO(\theta, \phi, q_{\text{new}})\\ &= \underset{\theta, \phi}{\mathrm{argmax}}\; \sum_{n=1}^N\mathbb{E}_{Z_n\sim p(Z_n|Y_n, \theta_{\text{old}}, \phi_{\text{old}})}\left[\log \left( p(y_n, Z_n | \phi, \theta\right) \right]. \end{aligned}\end{split}\]

Example: EM for the Gaussian Mixture Model of Birth Weight#

Solving the M-Step#

We see that the optimization problem in the M-step: \(\mu_{\text{new}}, \sigma^2_{\text{new}}, \pi_{\text{new}} = \underset{\mu, \sigma^2, \pi}{\mathrm{argmax}}\; ELBO(\mu, \sigma^2, \pi, q_{\text{new}})\) is equivalent to two problems

\[\begin{split}\begin{aligned} &1.\quad \underset{\mu, \sigma^2}{\mathrm{argmax}}\; \sum_{n=1}^N \sum_{k=1}^K r_{n, k} \log \mathcal{N}(y_n; \mu_k, \sigma^2_k)\\ &2.\quad \underset{\pi}{\mathrm{argmax}}\; \sum_{n=1}^N \sum_{k=1}^K r_{n, k}\pi_k \end{aligned}\end{split}\]

We can solve each optimization problem analytically by finding stationary points of the gradient (or the Lagrangian):

  • \(\mu_{\text{new}} = \frac{1}{ \sum_{n=1}^N r_{n, k}} \sum_{n=1}^N r_{n, k} y_n\)

  • \(\sigma^2_{\text{new}} = \frac{1}{ \sum_{n=1}^N r_{n, k}} \sum_{n=1}^N r_{n, k} (y_n - \mu_{\text{new}})^2\)

  • \(\pi_{\text{new}} = \frac{\sum_{n=1}^N r_{n, k}}{N}\)

Example: EM for the Gaussian Mixture Model of Birth Weight#

All Together#

Initialization: Pick any \(\pi\), \(\mu\), \(\sigma^2\)

E-Step: Compute \(r_{n, k} = \displaystyle\frac{\pi_{k, \text{old}}\,\mathcal{N}(y_n; \mu_{k, \text{old}}, \sigma^2_{k, \text{old}})}{\mathcal{Z}}\), where \(\mathcal{Z} = \sum_{k=1}^K \pi_{k, \text{old}}\,\mathcal{N}(y_n; \mu_{k, \text{old}}, \sigma^2_{k, \text{old}})\).

M-Step: Compute model parameters:

  • \(\mu_{\text{new}} = \frac{1}{ \sum_{n=1}^N r_{n, k}} \sum_{n=1}^N r_{n, k} y_n\)

  • \(\sigma^2_{\text{new}} = \frac{1}{ \sum_{n=1}^N r_{n, k}} \sum_{n=1}^N r_{n, k} (y_n - \mu_{\text{new}})^2\)

  • \(\pi_{\text{new}} = \frac{\sum_{n=1}^N r_{n, k}}{N}\)

Implementing EM for the Gaussian Mixture Model of Birth Weight#

Hide code cell source

#Generate data
N = 2000
pis = [0.2, 0.6, 0.2]
mus = [4.3, 6, 7.8]
sigmas = [0.5**2, 0.7**2, 0.5**2]
K = 3
zs = np.random.choice(np.arange(K), size=N, p=pis)
y = np.array([np.random.normal(mus[z], sigmas[z]**0.5, 1)[0] for z in zs])

#initialization
mu_init = [2, 4, 5]
sigma_init = [2., 2., 2.]
pi_init = [0.33, 0.33, 0.33]

#implement EM
mu_current = mu_init
sigma_current = sigma_init
pi_current = pi_init

log_lkhd = []

total_iter = 1500
threshold = 1e-10

mu_diff = 1.
pi_diff = 1.
sigma_diff = 1.

i = 0

while i < total_iter and mu_diff > threshold and pi_diff > threshold and sigma_diff > threshold:
    #E-step
    r_unnormalized = np.array([(pi_current[k] *  sp.stats.norm(mu_current[k], sigma_current[k]**0.5).pdf(y)) for k in range(K)]).T
    r = r_unnormalized / r_unnormalized.sum(axis=1).reshape((-1, 1))
    #M-step
    mu_next = np.array([1. / r[:, k].sum() * (r[:, k] * y).sum() for k in range(K)])
    sigma_next = np.array([1. / r[:, k].sum() * (r[:, k] * (y - mu_next[k])**2).sum() for k in range(K)])
    pi_next = r.sum(axis=0) / r.shape[0]
    
    #compute log observed likelihood
    if i % 100 == 0:
        print('iteration ', i)
        ll = 0
        for n in range(len(y)):
            ll += np.log(np.sum([sp.stats.norm(mu_next[k], sigma_next[k]**0.5).pdf(y[n]) * pi_next[k] for k in range(K)])) 
        log_lkhd.append(ll)
        
    #convergence check
    mu_diff = np.linalg.norm(mu_next - mu_current)
    pi_diff = np.linalg.norm(pi_next - pi_current)
    sigma_diff = np.linalg.norm(sigma_next - sigma_current)
           
    #update parameters
    mu_current = mu_next
    sigma_current = sigma_next
    pi_current = pi_next
    i += 1
    
x = np.linspace(y.min(), y.max(), 100)
iteration  0
iteration  100
iteration  200
iteration  300
iteration  400
iteration  500
iteration  600
iteration  700
iteration  800
iteration  900
iteration  1000
iteration  1100
iteration  1200
iteration  1300
iteration  1400
fig, ax = plt.subplots(1, 1, figsize=(10, 5))
ax.hist(y, bins=60, density=True, color='gray', alpha=0.5, label='histogram of birth weights')
ax.plot(x, pi_current[0] * sp.stats.norm(mu_current[0], sigma_current[0]**0.5).pdf(x), color='red', label='First Gaussian')
ax.plot(x, pi_current[1] * sp.stats.norm(mu_current[1], sigma_current[1]**0.5).pdf(x), color='blue', label='Second Gaussian')
ax.plot(x, pi_current[2] * sp.stats.norm(mu_current[2], sigma_current[2]**0.5).pdf(x), color='green', label='Third Gaussian')
ax.set_title('GMM for Birth Weights')
ax.legend(loc='best')
plt.show()
../_images/68b2a26751c472dc32ae6ac9365f13cb5de6ae715c30e24bdc388f2f680666ab.png

Sanity Check: Log-Likelihood During Training#

Remember that plotting the MLE model against actual data is not always an option (e.g. high-dimensional data).

A sanity check for that your EM algorithm has been implemented correctly is to plot the observed data log-likelihood over the iterations of the algorithm:

\[ \ell_y(\mu, \sigma^2, \pi) = \sum_{n=1}^N \log \sum_{k=1}^K \mathcal{N}(y_n; \mu_k, \sigma_k^2) \pi_k \]
fig, ax = plt.subplots(1, 1, figsize=(10, 3))
ax.plot(range(len(log_lkhd)), log_lkhd, color='red', alpha=0.5)
ax.set_title('observed data log-likelihood over iterations of EM')
plt.show()
../_images/4b71194199426e8b2f435417ab565670130b9edbd50efa4339649e41bcd89bc3.png

11.4. Exercises#

These problems were originally assigned as homework. Data files are in the book’s data/ folder. Worked solutions, where available, are collapsed beneath the questions they answer; try each problem before expanding them.

Problem Set: Latent Variables for Data Augmentation#

Hide code cell content

### Import basic libraries
import numpy as np
import pandas as pd
import sklearn as sk
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
%matplotlib inline

A botany research lab in Cambridge is experimentally cross-breeding two types of hibiscus flowers: blue and pink. The goal is to study the genetic factor that creates an exotic flower whose petals are pink with a ring of blue on each.

There are four types of child plant that can result from this cross-breeding:

  • Type 1: blue petals

  • Type 2: pink petals

  • Type 3: purple petals

  • Type 4: pink petals with a blue ring on each.

Out of 197 initial cross-breedings, the nursery obtained the following counts of the four types of child plants:

\[Y = (y_1, y_2, y_3, y_4) = (125, 18, 20, 34)\]

where \(y_i\) represents the number of child plants that are of type \(i\).

The geneticist in the lab know that the probability of obtaining each type of child plant in any single breeding experiment is correlated by the inheritability \(\theta\) of a specific genetic factor. That is, the probabilities of obtaining the four subtypes are as follows:

\[ \frac{\theta+2}{4}, \frac{1-\theta}{4}, \frac{1-\theta}{4}, \frac{\theta}{4},\]

where \(\theta \in [0, 1]\) is unknown.

The lab chose to model the observed data using a multinomial model:

\[\begin{aligned} Y & \sim Mult\left(197, \left[\frac{\theta+2}{4}, \frac{1 - \theta}{4}, \frac{1 - \theta}{4}, \frac{\theta}{4} \right]\right) \end{aligned}\]

The aim of this problem is to estimate \(\theta\) from the observed counts.

Exercise: Part I: MLE Through Latent Variable Augmentation and EM

In models where directly computing the MLE is hard (you can think about if that is the case here), the optimization of the likelihood can often be simplified by introducing a latent variable into the model and then optimize the likelihood using EM - this process is called data augmentation.

The nursery augmented the data with a new variable \(Z\) such that:

\[Z + (y_1 - Z) = y_1.\]

That is, using \(Z\), they are breaking \(y_1\), the number of Type I child plants, into two subtypes, with \(Z\) being the count of Subtype #1 and \((y_1-Z)\) being the count of Subtype #2. The lab posited the probability of obtain the two subtype \(\theta/4\) and \(1/2\), respectively.

The augmented model (which includes the observed data \(y\) and the latent variable \(z\) they introduced) they derived is as follows:

\[\begin{split}\begin{aligned} Z | Y, \theta &\sim Bin\left(y_1, \frac{\theta}{2 + \theta}\right)\\ Y & \sim Mult\left(197, \left[\frac{1}{2} + \frac{\theta}{4}, \frac{1 - \theta}{4}, \frac{1 - \theta}{4}, \frac{\theta}{4} \right]\right) \end{aligned}\end{split}\]
  1. Show that the assumptions the lab made about \(Z\) implies that \(Z | Y, \theta \sim Bin\left(y_1, \frac{\theta}{2 + \theta}\right)\).

  2. Derive the EM updates for the augmented latent variable model.

  3. Implement the EM algorithm to estimate the MLE of \(\theta\). Choose an appropriate initialization point and an appropriate stopping condition.

11.5. Further Reading#

Latent Variable Models