Þ¤pathÙI/home/runner/work/course/course/lectures/Latent Variable Models and VB.jl¬cell_resultsÞjÙ$26c74c9a-d294-11ef-2d31-67bd57d56d7cЧrunning§runtimeξ¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c74c9a-d294-11ef-2d31-67bd57d56d7c¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ƈ׷has_pluto_hook_features¤bodyÚz
Update Equations

For this specific case (GMM model with factorization constraints), Bishop shows that the equations for the optimal solutions (Eq. B-10.9) are analytically solvable, leading to the following variational update equations (for $k=1,\ldots, K$ ):

$$\begin{align*} \alpha_k &= \alpha_0 + N_k \tag{B-10.58} \\ \beta_k &= \beta_0 + N_k \tag{B-10.60} \\ m_k &= \frac{1}{\beta_k} \left( \beta_0 m_0 + N_k \bar{x}_k \right) \tag{B-10.61} \\ W_k^{-1} &= W_0^{-1} + N_k S_k + \frac{\beta_0 N_k}{\beta_0 + N_k}\left( \bar{x}_k - m_0\right) \left( \bar{x}_k - m_0\right)^T \tag{B-10.62} \\ \nu_k &= \nu_0 + N_k \tag{B-10.63} \end{align*}$$

where we used

$$\begin{align*} \log \rho_{nk} &= \mathbb{E}\left[ \log \pi_k\right] + \frac{1}{2}\mathbb{E}\left[ \log | \Lambda_k | \right] - \frac{D}{2} \log(2\pi) \\ & \qquad - \frac{1}{2}\mathbb{E}\left[(x_k - \mu_k)^T \Lambda_k(x_k - \mu_k) \right] \tag{B-10.46} \\ r_{nk} &= \frac{\rho_{nk}}{\sum_{j=1}^K \rho_{nj}} \tag{B-10.49} \\ N_k &= \sum_{n=1}^N r_{nk} \tag{B-10.51} \\ \bar{x}_k &= \frac{1}{N_k} \sum_{n=1}^N r_{nk} x_n \tag{B-10.52} \\ S_k &= \frac{1}{N_k} \sum_{n=1}^N r_{nk} \left( x_n - \bar{x}_k\right) \left( x_n - \bar{x}_k\right)^T \tag{B-10.53} \end{align*}$$

°persist_js_stateÂÙ$430a56c9-93ad-4513-b11c-2ac212109b12Чrunning§runtimeΊ\¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$430a56c9-93ad-4513-b11c-2ac212109b12¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Á�|·has_pluto_hook_features¤bodyÙ¨
Solution

See later in this lecture.

°persist_js_stateÂÙ$26c6347c-d294-11ef-056f-7b78a9e22272Чrunning§runtimeÎÄM¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c6347c-d294-11ef-056f-7b78a9e22272¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ã2D·has_pluto_hook_features¤bodyÚz

However, for the Gaussian mixture model (same log-likelihood function with $z_{nk}$ replacing $y_{nk}$), the class labels $\{z_{nk}\}$ are unobserved and they need to be estimated alongside with the parameters.

°persist_js_stateÂÙ$26c8c7fa-d294-11ef-0444-6555ecf5c721Чrunning§runtime΂`¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c8c7fa-d294-11ef-0444-6555ecf5c721¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÊvÉ·has_pluto_hook_features¤bodyÚT

The Local Free Energy in a Factor Graph

Consider an edge $x_j$ in a Forney-style factor graph for a generative model $p(x) = p(x_1,x_2,\ldots,x_N)$.

Assume that the graph structure (factorization) is specified by

$$p(x) = \prod_{a=1}^M p_a(x_a)$$

where $a$ is a set of indices.

Also, we assume a mean-field approximation for the posterior:

$$q(x) = \prod_{i=1}^N q_i(x_i)$$

and consequently a corresponding free energy functional

$$\begin{align*} F[q] &= \sum_x q(x) \log \frac{q(x)}{p(x)} \\ &= \sum_i \sum_{x_i} \left(\prod_{i=1}^N q_i(x_i)\right) \log \frac{\prod_{i=1}^N q_i(x_i)}{\prod_{a=1}^M p_a(x_a)} \end{align*}$$

With these assumptions, it can be shown that the FE evaluates to (exercise)

$$F[q] = \sum_{a=1}^M \underbrace{\sum_{x_a} \left( \prod_{j\in N(a)} q_j(x_j)\cdot \left(-\log p_a(x_a)\right) \right) }_{\text{node energy }U[p_a]} - \sum_{i=1}^N \underbrace{\sum_{x_i} q_i(x_i) \log \frac{1}{q_i(x_i)}}_{\text{edge entropy }H[q_i]}$$

In words, the FE decomposes into a sum of (expected) energies for the nodes minus the entropies on the edges.

°persist_js_stateÂÙ$2497529b-7703-4e3e-b9db-83f8dbf43fa8Чrunning§runtimeÎE«;¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$2497529b-7703-4e3e-b9db-83f8dbf43fa8¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šºÝð·has_pluto_hook_features¤bodyÚ2

Challenge: Density Modeling for the Old Faithful Data Set

°persist_js_stateÂÙ$5a94e2a4-7134-462e-9dc5-56083769049fЧrunning§runtimeΛ¾¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$5a94e2a4-7134-462e-9dc5-56083769049f¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÉcN·has_pluto_hook_features¤bodyÚ

Entropy and The Free Energy Functional (*)

The Free energy functional $\mathrm{F}[q] = -\sum_z q(z) \log p(x,z) - \sum_z q(z) \log \frac{1}{q(z)}$ decomposes into "Energy minus Entropy". So apparently the entropy of the posterior $q(z)$ is maximized. This entropy maximization may seem puzzling at first because inference should intuitively lead to more informed posteriors, i.e., posterior distributions whose entropy is smaller than the entropy of the prior. Explain why entropy maximization is still a reasonable objective.

°persist_js_stateÂÙ$26c5c1ae-d294-11ef-15c6-13cae5bc0dc8Чrunning§runtimeαò¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c5c1ae-d294-11ef-15c6-13cae5bc0dc8¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÂK·has_pluto_hook_features¤bodyÚæ

We consider the same model as we did in the generative classification lesson: the data for each class is distributed as a Gaussian:

$$\begin{align*} p(x_n | z_{nk}=1) &= \mathcal{N}\left( x_n | \mu_k, \Sigma_k\right)\\ p(z_{nk}=1) &= \pi_k \end{align*}$$

which can be summarized with the selection variables $z_{nk}$ as

$$\begin{align*} p(x_n,z_n) &= \prod_{k=1}^K (\underbrace{\pi_k \cdot \mathcal{N}\left( x_n | \mu_k, \Sigma_k\right) }_{p(x_n,z_{nk}=1)})^{z_{nk}} \end{align*}$$

Again, this is the same model as we defined for the generative classification model: A Gaussian-Categorical model but now with unobserved classes.

This model (with unobserved class labels) is known as a Gaussian Mixture Model (GMM).

°persist_js_stateÂÙ$dff0212b-f3e8-4592-8cd4-f52bcdb782fbЧrunning§runtimeÎy¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$dff0212b-f3e8-4592-8cd4-f52bcdb782fb¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šÄ¾Â·has_pluto_hook_features¤bodyÚÖ

🎯 Key concept

A Gaussian Mixture Model has the same form as the Gaussian-Categorical model,

$$\begin{align} p(x_n | z_{nk}=1) &= \mathcal{N}\left( x_n | \mu_k, \Sigma_k\right)\\ p(z_{nk}=1) &= \pi_k \end{align}$$

but now the class labels $z_{nk}$ are unobserved in the data set. A model with unobserved ("latent") variables is referred to as a latent variable model.

°persist_js_stateÂÙ$26c704f6-d294-11ef-1b3d-d52f0fb1c81dЧrunning§runtimeÎj#¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c704f6-d294-11ef-1b3d-d52f0fb1c81d¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ň±·has_pluto_hook_features¤bodyÚs

Visualization of Constrained VFEM

The following image by David Blei illustrates the Variational Bayes approach:

°persist_js_stateÂÙ$c90176ea-918b-4643-a10f-cef277c5ea75Чrunning§runtimeÎ ý‡¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$c90176ea-918b-4643-a10f-cef277c5ea75¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassigneeÀ²last_run_timestampËAÚ¹&™•K8·has_pluto_hook_features¤body °persist_js_stateÂÙ$93e7c7d5-a940-4764-8784-07af2f056e49Чrunning§runtimeÎ'¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$93e7c7d5-a940-4764-8784-07af2f056e49¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ægä·has_pluto_hook_features¤bodyÚc
Inference by Constrained VFEM

Assume that we have observed $D = \left\{x_1, x_2, \ldots, x_N\right\}$ and are interested to infer a posterior distribution for the parameters $\pi$, $\mu$ and $\Lambda$.

We will approximate Bayesian inference by VFE minimization. For the specified model, this leads to VFE minimization with respect to the hyperparameters, i.e., we need to minimize the function

$$F(\alpha_0, m_0, \beta_0, W_0, \nu_0) \,.$$

In general, this function can be optimized in various ways, e.g., by a gradient-descent procedure.

It turns out that adding the following factorization constraints on the variational posterior makes the VFEM task analytically tractible:

$$\begin{equation} q(z,\pi,\mu,\Lambda) = q(z) \cdot q(\pi,\mu,\Lambda) \,. \tag{B-10.42} \end{equation}$$

°persist_js_stateÂÙ$7a3c0ff7-0b32-4954-ae28-b644f4d966efЧrunning§runtimeÎþ×w¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$7a3c0ff7-0b32-4954-ae28-b644f4d966ef¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassigneeÀ²last_run_timestampËAÚ¹&¡9ãηhas_pluto_hook_features¤body©em_result°persist_js_stateÂÙ$26c5a93a-d294-11ef-23a1-cbcf0c370fc9Чrunning§runtimeΩ¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c5a93a-d294-11ef-23a1-cbcf0c370fc9¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&– ·has_pluto_hook_features¤bodyÙú

The Gaussian Mixture Model

The spread of the data in the Old Faithful data set looks like it could be modeled by two Gaussians. Let's develop a model for this data set.

°persist_js_stateÂÙ$3e897a59-e7b5-492c-8a8a-724248513a72Чrunning§runtimeÎиdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$3e897a59-e7b5-492c-8a8a-724248513a72¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Æ;~·has_pluto_hook_features¤bodyÚ a
Model Specification

We consider a Gaussian Mixture Model, specified by

$$\begin{align*} p(x,z|\theta) &= p(x|z,\mu,\Lambda)p(z|\pi) \\ &= \prod_{n=1}^N \prod_{k=1}^K \mathcal{N}\left( x_n | \mu_k, \Lambda_k^{-1}\right)^{z_{nk}} \cdot \prod_{n=1}^N \prod_{k=1}^K \pi_k^{z_{nk}} \\ &= \prod_{n=1}^N \prod_{k=1}^K \left(\pi_k \cdot \mathcal{N}\left( x_n | \mu_k, \Lambda_k^{-1}\right)\right)^{z_{nk}} \tag{B-10.37,38} \end{align*}$$

Let us introduce some priors for the parameters $\pi$, $\mu$, and $\Lambda$. We factorize the prior and choose conjugate distributions by

$$p(\pi,\mu,\Lambda) = p(\pi) p(\mu|\Lambda) p(\Lambda)$$

with

$$\begin{align} p(\pi) &= \mathrm{Dir}(\pi|\alpha_0) = C(\alpha_0) \prod_k \pi_k^{\alpha_0-1} \tag{B-10.39} \\ p(\mu|\Lambda) &= \prod_k \mathcal{N}\left(\mu_k | m_0, \left( \beta_0 \Lambda_k\right)^{-1} \right) \tag{B-10.40} \\ p(\Lambda) &= \prod_k \mathcal{W}\left( \Lambda_k | W_0, \nu_0 \right) \tag{B-10.40} \end{align}$$

where $\mathcal{W}\left( \cdot \right)$ is a Wishart distribution (i.e., a multi-dimensional Gamma distribution).

The full generative model is now specified by

$$p(x,z,\pi,\mu,\Lambda) = \underbrace{p(x|z,\mu,\Lambda) p(z|\pi)}_{\text{B-10.37-38}} \underbrace{p(\pi) p(\mu|\Lambda) p(\Lambda)}_{\text{B-10.39-40}} \tag{B-10.41}$$

with hyperparameters $\{ \alpha_0, m_0, \beta_0, W_0, \nu_0\}$.

°persist_js_stateÂÙ$26c8068a-d294-11ef-3983-a1be55128b3fЧrunning§runtimeÎoO¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c8068a-d294-11ef-3983-a1be55128b3f¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–É#æ·has_pluto_hook_features¤bodyÚ

Variational Inference in Practice

For most realistic models of complex real-world problems, Bayes rule is not tractable in closed form. As a result, the use of approximate variational Bayesian inference has seen rapid growth in practical applications.

Toolboxes such as RxInfer enable users to define sophisticated probabilistic models and automate the inference process via constrained VFE minimization. Remarkably, specifying even complex models typically requires no more than a single page of code.

In contrast to traditional algorithm design, where solving a problem might require implementing a custom solution in, say, $40$ pages of code, automated inference in a probabilistic model offers a radically more efficient and modular approach. This shift has the potential to fundamentally change how we design and deploy information processing systems in the future.

°persist_js_stateÂÙ$ae7ed1fc-fc36-4327-be55-a142477ca0adЧrunning§runtimeÎ a¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$ae7ed1fc-fc36-4327-be55-a142477ca0ad¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šÒüü·has_pluto_hook_features¤bodyÚW
Click to see proof

$$\begin{align*} F[q] &= \underbrace{ \int q(z) \log \frac{q(z)}{p(z)} \mathrm{d}z }_{\text{complexity}} - \underbrace{\int q(z) \log p(x|z) \mathrm{d}z}_{\text{accuracy}} \\ &= \int q(z) \log \frac{q(z)}{ p(x|z) p(z) }\mathrm{d}z \\ &= \int q(z) \log \frac{q(z)}{ p(z|x) p(x)}\mathrm{d}z \quad \text{( since } p(x|z) p(z) = p(z|x) p(x)\text{ )} \\ &= \underbrace{\int q(z) \log \frac{q(z)}{p(z|x)}\mathrm{d}z}_{\text{inference bound}\geq 0} - \underbrace{\log p(x)}_{\text{log-evidence}} \end{align*}$$

°persist_js_stateÂÙ$86c33a7c-135a-461f-a17e-b50bca418e13Чrunning§runtimeÎ! /¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$86c33a7c-135a-461f-a17e-b50bca418e13¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassigneeÀ²last_run_timestampËAÚ¹&�5ÞY·has_pluto_hook_features¤bodyÙ5sufficientStatistics (generic function with 1 method)°persist_js_stateÂÙ$26c8b682-d294-11ef-1331-2bcf8baec73fЧrunning§runtimeÎà´¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c8b682-d294-11ef-1331-2bcf8baec73f¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÊOηhas_pluto_hook_features¤bodyÚ

Message Passing for Free Energy Minimization

The Sum-Product (SP) update rule implements perfect Bayesian inference.

Sometimes, the SP update rule is not analytically solvable.

Fortunately, for many well-known Bayesian approximation methods, a message passing update rule can be created, e.g. Variational Message Passing (VMP) for variational inference.

In general, all of these message passing algorithms can be interpreted as minimization of a constrained free energy (e.g., see Senoz et al. (2021), and hence these message passing schemes comply with Caticha's Method of Maximum Relative Entropy, which, as discussed in the variational Bayes lesson is the proper way for updating beliefs.

Different message passing updates rules can be combined to get a hybrid inference method in one model.

°persist_js_stateÂÙ$f42a1a65-20ce-452f-9974-bc8146943574Чrunning§runtimeΆ·¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$f42a1a65-20ce-452f-9974-bc8146943574¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ç¡Z·has_pluto_hook_features¤bodyÙ„

Theoretical Underpinning of VFE Minimization

°persist_js_stateÂÙ$edb179df-5cff-4e7b-8645-6da4818dceeeЧrunning§runtimeή¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$edb179df-5cff-4e7b-8645-6da4818dceee¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Åj'·has_pluto_hook_features¤bodyÚ¤
3. Other constraints, e.g., the Expectation-Maximization (EM) algorithm

Beyond form and factorization constraints on $q(z)$, several ad hoc algorithms have been developed to simplify VFE minimization for particular models.

In particular, the Expectation-Maximization (EM) algorithm is a famous special case of constrained VFE minimization. The EM algorithm places some constraints on both the posterior $q(z)$ and the prior $p(z)$ (see the OPTIONAL SLIDE for more info) that essentially reduce VFE minimization to maximum likelihood estimation.

°persist_js_stateÂÙ$06512595-bdb7-4adf-88ae-62af20210891Чrunning§runtime͘Ÿdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$06512595-bdb7-4adf-88ae-62af20210891¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šëJí·has_pluto_hook_features¤bodyÚ4

Challenge Revisited: Modeling of the Old Faithful Data Set

°persist_js_stateÂÙ$3deadfd0-9fbb-476a-a7de-5dd694e55a65Чrunning§runtimeΦ:¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$3deadfd0-9fbb-476a-a7de-5dd694e55a65¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–‹ʷhas_pluto_hook_features¤bodyÚè

Eq. B-9.12 reveals the link to the name Gaussian mixture model. The priors $\pi_k$ for the $k$-th class are also called mixture coefficients.

Be aware that Eq. B-9.12 is not the generative model for the GMM! The generative model is the joint distribution $p(x,z,\pi,\mu,\Sigma)$ over all variables, including the latent variables.

°persist_js_stateÂÙ$3654551d-5d08-4bb0-8a0d-c7d42225bc69Чrunning§runtimeÎ_°¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$3654551d-5d08-4bb0-8a0d-c7d42225bc69¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÅF„·has_pluto_hook_features¤bodyÚ˜
2. Factorization constraints

In addition to form constraints, it is also common to constrain the posterior $q(z)$ by a specific factorization. For instance, in the mean-field factorization constraints, we constrain the variational posterior to factorize fully into a set of independent factors, i.e.,

$$q(z) = \prod_{j=1}^m q_j(z_j)\,, \tag{B-10.5}$$

Variational inference with mean-field factorization has been worked out in detail as the Coordinate Ascent Variational Inference (CAVI) algorithm. See the Optional Slide on CAVI for details.

Mean-field factorization is just an example of various factorization constraints that have been successfully applied to VFEM.

°persist_js_stateÂÙ$670f83cb-66d6-40ab-9c42-50e022a9bd4cЧrunning§runtimeÎQó¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$670f83cb-66d6-40ab-9c42-50e022a9bd4c¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ä,é·has_pluto_hook_features¤bodyÙÎ

In other words, global minimization of $F[q]$ recovers Bayes rule exactly, namely, both the posterior and evidence are revealed.

°persist_js_stateÂÙ$c563de07-0036-4dc4-87ee-e8363e9b6b1bЧrunning§runtimeÍ:-¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$c563de07-0036-4dc4-87ee-e8363e9b6b1b¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&›¤j¾·has_pluto_hook_features¤bodyÚŒ
� Previous lecture Next lecture →
°persist_js_stateÂÙ$90fbe618-fc81-480b-b685-69cd97e5b8edЧrunning§runtimeÎH ¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$90fbe618-fc81-480b-b685-69cd97e5b8ed¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&›¢Ù#·has_pluto_hook_features¤bodyÙ¯°persist_js_stateÂÙ$f8c8013a-3e87-4d01-a3ae-86b39cf1f002Чrunning§runtimeθdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$f8c8013a-3e87-4d01-a3ae-86b39cf1f002¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Áší·has_pluto_hook_features¤bodyÙ`

The Gaussian Mixture Model

°persist_js_stateÂÙ$4e0c025d-fa39-462d-8e7d-e66d220e9595Чrunning§runtimeÍ �¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$4e0c025d-fa39-462d-8e7d-e66d220e9595¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassigneeÀ²last_run_timestampËAÚ¹&šõ§ ·has_pluto_hook_features¤body °persist_js_stateÂÙ$ce7d086b-ff20-4da1-a4e8-52b5b7dc9e2bЧrunning§runtimeο_�¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$ce7d086b-ff20-4da1-a4e8-52b5b7dc9e2b¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šwU;·has_pluto_hook_features¤bodyÚP¾ °persist_js_stateÂÙ$26c58298-d294-11ef-2a53-2b42b48e0725Чrunning§runtimeÎâ‡Q¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c58298-d294-11ef-2a53-2b42b48e0725¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&š²ë«·has_pluto_hook_features¤bodyÚ

Preliminaries

Goal
Materials
°persist_js_stateÂÙ$26c728f0-d294-11ef-0c01-6143abe8c3f0Чrunning§runtimeÎ £¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c728f0-d294-11ef-0c01-6143abe8c3f0¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Źå·has_pluto_hook_features¤bodyÚ›

Figure caption: The Bayesian posterior $p(z|x)$ (upper-right) is the posterior that would be obtained through executing Bayes rule, but unfortunately, Bayes rule is not tractable here. Instead, we propose a variational posterior $q(z;\nu)$, parameterized by $\nu$. The area inside the ellipsis represents the region reachable by choosing values for the parameter $\nu$. Note that $p(z|x)$ is not reachable. We start the FE minimization process by choosing an initial value $\nu^{\text{init}}$, which corresponds to the posterior $q(z;\nu^{\text{init}})$, as indicated in the figure. VFE minimization yields a final value $\nu^{*}$ that minimizes the KL divergence between $q(z;\nu)$ and $p(z|x)$.

°persist_js_stateÂÙ$df171940-eb54-48e2-a2b8-1a8162cabf3eЧrunning§runtimeÎ .¥Š¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$df171940-eb54-48e2-a2b8-1a8162cabf3e¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassigneeÀ²last_run_timestampËAÚ¹&˜ËÌ:·has_pluto_hook_features¤body °persist_js_stateÂÙ$489cbd24-1a69-4a00-a2e9-53c2c57cef65Чrunning§runtimeÎ6Ks¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$489cbd24-1a69-4a00-a2e9-53c2c57cef65¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassigneeÀ²last_run_timestampËAÚ¹&œ†�·has_pluto_hook_features¤bodyÙ(plotGMM (generic function with 1 method)°persist_js_stateÂÙ$26c7b428-d294-11ef-150a-bb37e37f4b5dЧrunning§runtimeÎh¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c7b428-d294-11ef-150a-bb37e37f4b5d¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÇÁY·has_pluto_hook_features¤bodyÚz

Observations as Variational Constraints

We derived variational inference by substituting a variational posterior $q(z)$ for the Bayesian posterior $p(z|x)$ in the CA decomposition of (negative log) Bayesian evidence for a model. This led to a straightforward derivation of the VFE functional, but revealed nothing about the foundations of variational inference. Is variational inference any good?

To approach this question, let us first recognize that, in the context of a given model $p(x,z)$, new observations $x$ can generally be formulated as a constraint on a posterior distribution $q$. For instance, observing a new data point $x_1 = 5$ can be formalized as a constraint $q(x_1) = \delta(x_1 - 5)$, where $\delta(\cdot)$ is the Dirac delta function.

Viewing observations as delta-function constraints enables us to interpret them as a specific instance of variational constraints, on par with form and factorization (and other) constraints, all of which shape the variational posterior in constrained VFE minimization.

°persist_js_stateÂÙ$8b887c4a-273c-40fe-83e9-5c79ac6946f8Чrunning§runtimeΗ¢¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$8b887c4a-273c-40fe-83e9-5c79ac6946f8¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ǃǷhas_pluto_hook_features¤bodyÙå

Implementation

Reading this lecture online? Click "View code" in the top right to read the implementation of this visualisation.

°persist_js_stateÂÙ$26c5f8d6-d294-11ef-3bcd-4d5e0391698dЧrunning§runtimeÎ O¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c5f8d6-d294-11ef-3bcd-4d5e0391698d¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Âߘ·has_pluto_hook_features¤bodyÚ\

Latent Variable Models

A GMM contains both observed variables $\{x_n\}$, and unobserved variables, namely unobserved (synonym: latent, hidden) parameters $\theta= \{\pi_k,\mu_k, \Sigma_k\}$ and unobserved class labels $\{z_{nk}\}$.

From a Bayesian viewpoint, both the class labels $\{z_{nk}\}$ and the parameters $\theta$ are just unobserved variables for which we can set a prior and compute a posterior by Bayes rule.

Note that $z_{nk}$ carries a subscript $n$, indicating that its value depends not only on the class index $k$, but also on the specific observation $n$. This contrasts with global model parameters $\theta$, which are shared across all data points.

Observation-specific latent variables can be a powerful modeling tool for capturing additional structure in the data, particularly information about the hidden causes of individual observations. In the case of the Gaussian Mixture Model (GMM), the latent variables $z_{nk}$ represent unobserved class memberships, specifying which component generated each data point.

Models that incorporate unobserved variables, often specific to each observation, are broadly known as Latent Variable Models (LVMs). These latent variables help explain the hidden structure or generative process underlying the observed data.

By adding model structure through (equations among) observation-dependent latent variables, we can often build more accurate models for very complex processes. Unfortunately, adding structure through observation-dependent latent variables in models is also often accompanied by a more complex inference task.

°persist_js_stateÂÙ$663ac0ef-0577-43af-8df5-15e046ef875cЧrunning§runtimeÎHÍþ·¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$663ac0ef-0577-43af-8df5-15e046ef875c¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime­image/svg+xml¬rootassigneeÀ²last_run_timestampËAÚ¹&Ÿ*b·has_pluto_hook_features¤bodyÉBJ °persist_js_stateÂÙ$baec0494-9557-49d1-b4d8-a8030d3281b7Чrunning§runtimeÎ ŠŠ¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$baec0494-9557-49d1-b4d8-a8030d3281b7¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ä]§·has_pluto_hook_features¤bodyÚK

Approximate Bayesian Inference by VFE Minimization

In practice, even if we cannot attain the global minimum of VFE, we can still use a local minimum,

$$\hat{q}(z) \approx \arg\min_q F[q]$$

to accomplish approximate Bayesian inference by:

$$\begin{align*} \hat{q}(z) &\approx p(z|x) \\ F[\hat{q}] &\approx -\log p(x) \end{align*}$$

Executing inference by minimizing the VFE functional is called Variational Bayes (VB) or Variational Inference (VI).

(As an aside), note that Bishop introduces in Eq. B-10.3 an Evidence Lower BOund (in modern machine learning literature abbreviated as ELBO) $\mathcal{L}[q]$ that equals the negative VFE ($\mathcal{L}[q]=-F[q]$). In this class, we prefer to discuss inference in terms of minimizing VFE rather than maximizing ELBO, but note that these two concepts are equivalent. (We prefer the Free Energy formulation because of the terminology in the Free Energy Principle, which we introduce in the Intelligent Agents and active Inference lesson).

°persist_js_stateÂÙ$18f5d694-8869-4265-98ac-9ef7ff451eafЧrunning§runtimeÎ9£¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$18f5d694-8869-4265-98ac-9ef7ff451eaf¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šÕOð·has_pluto_hook_features¤bodyÚ ¨
°persist_js_stateÂÙ$c7351bf1-447e-475b-8965-d259c01bfd57Чrunning§runtimeÎýиdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$c7351bf1-447e-475b-8965-d259c01bfd57¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šÒÉÉ·has_pluto_hook_features¤bodyÚ¯
Click to see proof

$$\begin{align} p(x_n) &= \sum_{z_n} p(x_n,z_n) \\ &= \sum_{z_n} \prod_{k=1}^K \left(\pi_k \cdot \mathcal{N}\left( x_n | \mu_k, \Sigma_k\right) \right)^{z_{nk}} \\ &= \sum_{j=1}^K \prod_{k=1}^K \left( \pi_k \cdot \mathcal{N}\left( x_n | \mu_k, \Sigma_k\right) \right)^{I_{kj}} \;\; \text{(use }z_n \text{ is one-hot coded)}\\ &= \sum_{j=1}^K \pi_j \cdot \mathcal{N}\left( x_n | \mu_j, \Sigma_j\right) \end{align}$$

where $I_{kj} = 1$ if $k=j$ and $0$ otherwise.

°persist_js_stateÂÙ$55a1c42b-20d8-47a3-aa00-7af905db537cЧrunning§runtimeÎ.CE¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$55a1c42b-20d8-47a3-aa00-7af905db537c¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassigneeÀ²last_run_timestampËAÚ¹&�K~,·has_pluto_hook_features¤bodyÙ(updateR (generic function with 1 method)°persist_js_stateÂÙ$747a7e1e-b921-4882-b00a-1b00bef8433dЧrunning§runtimeÎ…(ݸdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$747a7e1e-b921-4882-b00a-1b00bef8433d¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&› ë··has_pluto_hook_features¤bodyÚ«
Click for the solution

Note that Free Energy minimization is a balancing act: FE minimization implies entropy maximization and at the same time energy minimization. Minimizing the energy term leads to aligning $q(z)$ with $\log p(x,z)$, ie, it tries to move the bulk of the function $q(z)$ to areas in $z$-space where $p(x,z)$ is large ($p(x,z)$ is here just a function of $z$, since x is observed).

However, aside from aligning with $p(x,z)$, we want $q(z)$ to be as uninformative as possible. Everything that can be inferred should be represented in $p(x,z)$ (which is prior times likelihood). We don't want to learn anything that is not in either the prior or the likelihood. The entropy term balances the energy term by favoring distributions that are as uninformative as possible.

°persist_js_stateÂÙ$b3bb7349-1965-4734-83ed-ba6fef0ccc41Чrunning§runtimeÎ%<¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$b3bb7349-1965-4734-83ed-ba6fef0ccc41¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÈT·has_pluto_hook_features¤bodyÚª

Variational Inference and The Maximum Entropy Principle

In Caticha (2010) (based on earlier work by Shore and Johnson (1980)), the Principle of Maximum (Relative) Entropy is developed as a method for rational updating of priors to posteriors when faced with new information in the form of constraints.

Caticha's argumentation is as follows:

$$q^* = \arg\max_q S[q]\,, \quad \text{subject to all constraints.} $$

Similarly to Cox' method for deriving Probability Theory from a set of sensical axioms, Caticha then introduced the following axioms, based on a rational principle (the principle of minimal updating, see Caticha 2010), that the ranking function needs to adhere to:

  1. Locality: local information has local effects.

  2. Coordinate invariance: the system of coordinates carries no information.

  3. Independence: When systems are known to be independent, it should not matter whether they are treated separately or jointly.

It turns out that these three criteria uniquely identify the Relative Entropy as the proper ranking function:

$$\begin{align*} S[q] = - \sum_z q(x,z) \log \frac{q(x,z)}{p(x,z)} \end{align*}$$

This procedure for finding the variational posterior $q$ is called the Principle of Maximum (Relative) Entropy (PME). Note that, since $S[q]=-F[q]$, constrained Relative Entropy maximization is equivalent to constrained VFE minimization!

Therefore, when information is supplied in the form of constraints on the posterior (such as form/factorization constraints and new observations as data constraints), we should select the posterior that minimizes the constrained Variational Free Energy. Constrained FE minimization is the proper method for inference!

Bayes rule is the global solution of constrained VFEM when all constraints are data constraints, ie, delta distributions on $q(x)$. Hence, Bayes rule is a special case of constrained VFEM. Bayes rule only applies to updating beliefs on the basis of new observations.

°persist_js_stateÂÙ$26c6e002-d294-11ef-15a4-33e30d0d76ecЧrunning§runtimeÎô<¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c6e002-d294-11ef-15a4-33e30d0d76ec¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ã×€·has_pluto_hook_features¤bodyÚÕ

The Global VFE Minimum Recovers Bayes Rule

It turns out that we can perform (approximate) Bayesian inference by minimizing the Variational Free Energy (VFE) with respect to the variational distribution $q$.

To explain inference by VFE minimization (abbreviated as VFEM), we first rewrite the VFE in terms of "inference bound" minus "log-evidence" terms (the bound-evidence (BE) decomposition):

$$\begin{align*} F[q] &= \underbrace{ \int q(z) \log \frac{q(z)}{p(z)} \mathrm{d}z }_{\text{complexity}} - \underbrace{\int q(z) \log p(x|z) \mathrm{d}z}_{\text{accuracy}} \\ &= \underbrace{\int q(z) \log \frac{q(z)}{p(z|x)}\mathrm{d}z}_{\text{inference bound}\geq 0} - \underbrace{\log p(x)}_{\text{log-evidence}} \end{align*}$$

°persist_js_stateÂÙ$60a50f12-063c-4247-9c9c-bb41d5dc9811Чrunning§runtimeÎãݸdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$60a50f12-063c-4247-9c9c-bb41d5dc9811¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÉDg·has_pluto_hook_features¤bodyÙ:

Summary

°persist_js_stateÂÙ$0e9e62ea-1b2f-4e80-b78b-2001ae46093fЧrunning§runtimeβ°¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$0e9e62ea-1b2f-4e80-b78b-2001ae46093f¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassigneeÀ²last_run_timestampËAÚ¹&œ`зhas_pluto_hook_features¤bodyÙ*get_color (generic function with 1 method)°persist_js_stateÂÙ$40ce0abb-a086-4977-9131-10f60ab44152Чrunning§runtimeÎ2€¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$40ce0abb-a086-4977-9131-10f60ab44152¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šé§?·has_pluto_hook_features¤bodyÚh

🎯 Key concept

VFE minimization transforms a Bayesian inference problem (that involves integration) into an optimization problem! Generally, optimization problems are easier to solve than integration problems.

°persist_js_stateÂÙ$4ff85bda-22bb-408d-a50a-461834b7c0ffЧrunning§runtime͘¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$4ff85bda-22bb-408d-a50a-461834b7c0ff¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&› ÀÊ·has_pluto_hook_features¤bodyÚK
°persist_js_stateÂÙ$26c75b5e-d294-11ef-173e-b3f46a1df536Чrunning§runtimeΖt¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c75b5e-d294-11ef-173e-b3f46a1df536¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Æ¥Ó·has_pluto_hook_features¤bodyÚ

Exam guide: Working out VFE minimization for the GMM to these update equations (eqs B-10.58 through B-10.63) is not something that you need to reproduce without assistance at the exam. Rather, the essence is that it is possible to arrive at closed-form variational update equations for the GMM. You should understand though how FEM works conceptually and in principle be able to derive variational update equations for very simple models that do not involve clever mathematical tricks.

°persist_js_stateÂÙ$fd233604-120a-4838-a660-d5021bccecd0Чrunning§runtimeÎôÚ€¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$fd233604-120a-4838-a660-d5021bccecd0¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime­image/svg+xml¬rootassigneeÀ²last_run_timestampËAÚ¹&¡¢œ™·has_pluto_hook_features¤bodyÉ ; °persist_js_stateÂÙ$c18b7c1b-8011-469b-ad92-7d50c23c46e3Чrunning§runtimeÎ:9»¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$c18b7c1b-8011-469b-ad92-7d50c23c46e3¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeÙ!application/vnd.pluto.tree+object¬rootassignee¯const plot_lims²last_run_timestampËAÚ¹&›ÐY°·has_pluto_hook_features¤bodyƒ¨objectid°ae2ec98d0122aedc¤typeªNamedTuple¨elements’’¤xlim’ƒ¨objectid°7b3b6e4d0ce70e0a¤type¥Tuple¨elements’’’£1.3ªtext/plain’’£5.5ªtext/plainÙ!application/vnd.pluto.tree+object’¤ylim’ƒ¨objectid°fc6c5f93bd4de540¤type¥Tuple¨elements’’’¢41ªtext/plain’’¢99ªtext/plainÙ!application/vnd.pluto.tree+object°persist_js_stateÂÙ$bbdca8c2-022f-42be-bcf7-80d86f7f269cЧrunning§runtimeÎ7ð¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$bbdca8c2-022f-42be-bcf7-80d86f7f269c¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Èið·has_pluto_hook_features¤bodyÚ ç

Model Performance Evaluation, Revisited

Let us reconsider the Bound-Evidence decomposition of the VFE for a model $p(x,z)$ with variational posterior $q(z)$,

$$\begin{align} \mathrm{F}[q] = \underbrace{\sum_z q(z) \log \frac{q(z)}{p(z|x)}}_{\text{inference bound}\geq 0} \underbrace{- \log p(x)}_{\text{surprise}} \tag{BE} \end{align}$$

The VFE comprises two cost terms:

$$p(x) = \sum_z p(x,z) \,.$$

$$\sum_z q(z) \log \frac{q(z)}{p(z |x)} \geq 0 \,,$$

quantifies the cost of imperfect inference, i.e., the discrepancy between the variational posterior $q(z)$ and the true Bayesian posterior $p(z | x)$.

In any practical setting, using a model implies performing inference within that model. Therefore, the effective cost of applying a model is not merely the surprise but also must include the cost of inference.

Put more bluntly: a model with very high Bayesian evidence $p(x)$ may still be practically unusable due to exorbitant inference costs.

In the literature, the VFE is typically interpreted as an approximation (more precisely, an upper-bound) to the surprise, $-\log p(x)$, which is often regarded as the “true� measure of model performance. However, we argue that this perspective should be reversed: the VFE should be considered the true performance metric in practice, as it accounts for both model fit and the tractability of inference. The surprise can be viewed as a special case of the VFE, corresponding to a zero inference bound, that only applies when ideal Bayesian inference is computationally feasible.

°persist_js_stateÂÙ$cc547bfa-a130-4382-af47-73de56e4741bЧrunning§runtimeÎqù¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$cc547bfa-a130-4382-af47-73de56e4741b¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassignee¬old_faithful²last_run_timestampËAÚ¹&œMbé·has_pluto_hook_features¤bodyÙË272×2 Matrix{Float64}: 3.6 79.0 1.8 54.0 3.333 74.0 2.283 62.0 4.533 85.0 2.883 55.0 4.7 88.0 â‹® 4.75 75.0 4.117 81.0 2.15 46.0 4.417 90.0 1.817 46.0 4.467 74.0°persist_js_stateÂÙ$62868f61-95c7-4e07-854f-a171aadc667bЧrunning§runtimeͽѸdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$62868f61-95c7-4e07-854f-a171aadc667b¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&›x‰U·has_pluto_hook_features¤bodyÚH

Code Example: EM-algorithm for the GMM on the Old-Faithful data set

°persist_js_stateÂÙ$26c5d734-d294-11ef-20a3-afd2c3324323Чrunning§runtimeÎéF¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c5d734-d294-11ef-20a3-afd2c3324323¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–±B·has_pluto_hook_features¤bodyÚj

GMM is a Flexible Model

GMMs are very popular models. They have decent computational properties and are universal approximators of densities (as long as there are enough Gaussians, of course).

(In the above figure, the Gaussian components are shown in red and the pdf of the mixture models in blue).

°persist_js_stateÂÙ$26c9121e-d294-11ef-18e6-ed8105503adcЧrunning§runtimeÎv¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c9121e-d294-11ef-18e6-ed8105503adc¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ë©ô·has_pluto_hook_features¤bodyÚ \

The Bethe Free Energy and Belief Propagation

We showed that, under mean field assumptions, the FE can be decomposed into a sum of local FE contributions for the nodes ($a$) and edges ($i$):

$$\begin{align*} F[q] = \sum_{a=1}^M \underbrace{\sum_{x_a} \left( \prod_{j\in N(a)} q_j(x_j)\cdot \left(-\log p_a(x_a)\right) \right) }_{\text{node energy }U[p_a]} - \sum_{i=1}^N \underbrace{\sum_{x_i} q_i(x_i) \log \frac{1}{q_i(x_i)}}_{\text{edge entropy }H[q_i]} \end{align*}$$

The mean field assumption is very strong and may lead to large inference costs ($\mathrm{KL}(q(x),p(x|\text{data}))$). A more relaxed assumption is to allow joint posterior beliefs over the variables that attach to a node. This idea is expressed by the Bethe Free Energy:

$$\begin{align*} F_B[q] = \sum_{a=1}^M \left( \sum_{x_a} q_a(x_a) \log \frac{q_a(x_a)}{p_a(x_a)} \right) - \sum_{i=1}^N (d_i - 1) \sum_{x_i} q_i(x_i) \log {q_i(x_i)} \end{align*}$$

where $q_a(x_a)$ is the posterior joint belief over the variables $x_a$ (i.e., the set of variables that attach to node $a$), $q_i(x_i)$ is the posterior marginal belief over the variable $x_i$ and $d_i$ is the number of factor nodes that link to edge $i$. Moreover, $q_a(x_a)$ and $q_i(x_i)$ are constrained to obey the following equalities:

$$\begin{align*} \sum_{x_a \backslash x_i} q_a(x_a) &= q_i(x_i), ~~~ \forall i, \forall a \\ \sum_{x_i} q_i(x_i) &= 1, ~~~ \forall i \\ \sum_{x_a} q_a(x_a) &= 1, ~~~ \forall a \\ \end{align*}$$

We form the Lagrangian by augmenting the Bethe Free Energy functional with the constraints:

$$\begin{align*} L[q] = F_B[q] + \sum_i\sum_{a \in N(i)} \lambda_{ai}(x_i) \left(q_i(x_i) - \sum_{x_a\backslash x_i} q(x_a) \right) + \sum_{i} \gamma_i \left( \sum_{x_i}q_i(x_i) - 1\right) + \sum_{a}\gamma_a \left( \sum_{x_a}q_a(x_a) -1\right) \end{align*}$$

The stationary solutions for this Lagrangian are given by

$$\begin{align*} q_a(x_a) &= f_a(x_a) \exp\left(\gamma_a -1 + \sum_{i \in N(a)} \lambda_{ai}(x_i)\right) \\ q_i(x_i) &= \exp\left(1- \gamma_i + \sum_{a \in N(i)} \lambda_{ai}(x_i)\right) ^{\frac{1}{d_i - 1}} \end{align*}$$

where $N(i)$ denotes the factor nodes that have $x_i$ in their arguments and $N(a)$ denotes the set of variables in the argument of $f_a$.

Stationary solutions are functions of Lagrange multipliers. This means that Lagrange multipliers need to be determined. Lagrange multipliers can be determined by plugging the stationary solutions back into the constraint specification and solving for the multipliers which ensure that the constraint is satisfied. The first constraint we consider is normalization, which yields the following identification:

$$\begin{align*} \gamma_a &= 1 - \log \Bigg(\sum_{x_a}f_a(x_a)\exp\left(\sum_{i \in N(a)}\lambda_{ai}(x_i)\right)\Bigg)\\ \gamma_i &= 1 + (d_i-1) \log\Bigg(\sum_{x_i}\exp\left( \frac{1}{d_i-1}\sum_{a \in N(i)} \lambda_{ai}(x_i)\right)\Bigg). \end{align*}$$

The functional form of the Lagrange multipliers that corresponds to the normalization constraint enforces us to obtain the Lagrange multipliers that correspond to the marginalization constraint. To do so we solve for

$$\begin{align*} \sum_{x_a \backslash x_i} f_a(x_a) \exp\left(\sum_{i \in N(a)} \lambda_{ai}(x_i)\right) &= \exp\left(\sum_{a \in N(i)} \lambda_{ai}(x_i)\right) ^{\frac{1}{d_i - 1}} \exp\left(\lambda_{ai}(x_i)\right)\sum_{x_a \backslash x_i} f_a(x_a) \exp\Bigg(\sum_{\substack{{j \in N(a)} j \neq i}}\lambda_{aj}(x_j)\Bigg) \\ &= \exp\left(\sum_{a \in N(i)} \lambda_{ai}(x_i)\right) ^{\frac{1}{d_i - 1}} \exp\left(\lambda_{ai}(x_i) + \lambda_{ia}(x_i)\right) \\ &= \exp\left(\sum_{a \in N(i)} \lambda_{ai}(x_i)\right) ^{\frac{1}{d_i - 1}}\, , \end{align*}$$

where we defined an auxilary function

$$\begin{align*} \exp(\lambda_{ia}(x_i)) \triangleq \sum_{x_a \backslash x_i} f_a(x_a) \exp\Bigg(\sum_{\substack{{j \in N(a)} j \neq i}}\lambda_{aj}(x_j)\Bigg) \,. \end{align*}$$

This definition is valid since it can be inverted by the relation

$$\begin{align*} \lambda_{ia}(x_i) = \frac{2-d_i}{d_i - 1}\lambda_{ai}(x_i) + \frac{1}{d_i -1}\sum_{\substack{c \in N(i)\\c \neq a}}\lambda_{ci}(x_i) \end{align*}$$

In general it is not possible to solve for the Lagrange multipliers analytically and we resort to iteratively obtaining the solutions. This leads to the Belief Propagation algorithm where the exponentiated Lagrange multipliers (messages) are updated iteratively via

$$\begin{align*} \mu_{ia}^{(k+1)}(x_i) &= \sum_{x_a \backslash x_i} f_a(x_a) \prod_{\substack{{j \in N(a)} j \neq i}}\mu^{(k)}_{aj}(x_j) \mu_{ai}^{(k)}(x_i) \\ &= \prod_{\substack{c \in N(i) c \neq a}}\mu^{(k)}_{ic}(x_i)\,, \end{align*}$$

where $k$ denotes iteration number and the messages are defined as

$$\begin{align*} \mu_{ia}(x_i) &\triangleq \exp(\lambda_{ia}(x_i))\\ \mu_{ai}(x_i) &\triangleq \exp(\lambda_{ai}(x_i))\,. \end{align*}$$

For a more complete overview of message passing as Bethe Free Energy minimization, see Senoz et al. (2021).

°persist_js_stateÂÙ$26c67f04-d294-11ef-03a4-838ae255689dЧrunning§runtimeΣF¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c67f04-d294-11ef-03a4-838ae255689d¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ùª·has_pluto_hook_features¤bodyÚ‘

The Variational Free Energy Functional

We'll start from scratch. Consider a model $p(x,z) = p(x|z) p(z)$, where $x$ and $z$ are observed and latent variables, respectively. $z$ may include parameters but also observation-dependent latent variables.

The goal of Bayesian inference is to transform the (known) likelihood-times-prior factorization of the full model to a posterior-times-evidence decomposition:

$$ \underbrace{p(x|z) p(z)}_{\text{what we know}} \rightarrow \underbrace{p(z|x) p(x)}_{\text{what we want}} $$

Remember from the Bayesian machine learning lesson that negative log-evidence can be decomposed as "complexity" minus "accuracy" terms (the CA decomposition):

$$ -\log p(x) = \underbrace{ \int p(z|x) \log \frac{p(z|x)}{p(z)} \mathrm{d}z }_{\text{complexity}} - \underbrace{\int p(z|x) \log p(x|z) \mathrm{d}z}_{\text{accuracy}} $$

The CA decomposition cannot be evaluated because it depends on the posterior $p(z|x)$, which cannot be evaluated since it is the objective of the inference process.

Let's now introduce a distribution $q(z)$ (called the "variational" or "approximate" posterior distribution) that we will use to approximate the posterior $p(z|x)$. Since we propose the distribution $q(z)$ ourselves, we will assume that $q(z)$ can be evaluated.

If we substitute $q(z)$ for $p(z|x)$ in the CA decomposition, then we obtain

$$ F[q] \triangleq \underbrace{ \int q(z) \log \frac{q(z)}{p(z)} \mathrm{d}z }_{\text{complexity}} - \underbrace{\int q(z) \log p(x|z) \mathrm{d}z}_{\text{accuracy}} $$

This expression is called the Variational Free Energy (VFE), represented by the symbol $F$. We treat $F$ as a function of the posterior $q(z)$. Technically, a function of a function is called a functional, and we write square brackets (e.g., $F[q]$) to differentiate functionals from functions (e.g., $q(z)$).

Note that all factors in the CA decomposition of VFE (i.e., $q(z)$, $p(z)$, and $p(x|z)$) can be evaluated as a function of $z$ (and $x$ is observed), and therefore the VFE can be evaluated. This is important: log-evidence $\log p(x)$ cannot be evaluated, but $F[q]$ can be evaluated!

°persist_js_stateÂÙ$4ee377c2-a126-4c40-8053-517d40c5ef9dЧrunning§runtimeξÏ\¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$4ee377c2-a126-4c40-8053-517d40c5ef9d¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeÙ!application/vnd.pluto.tree+object¬rootassignee«vfem_result²last_run_timestampËAÚ¹&ž€±â·has_pluto_hook_features¤bodyƒ¨objectid°f34ebda5250321fc¤typeªNamedTuple¨elements’’«clusters_vb’Ú6×120 Matrix{Distribution}: FullNormal( dim: 2 μ: [2.33575, 69.4662] Σ: [0.333333 0.0; 0.0 33.3333] ) … FullNormal( dim: 2 μ: [1.98036, 54.6905] Σ: [0.0396588 0.36343; 0.36343 33.5136] ) FullNormal( dim: 2 μ: [2.06093, 90.0417] Σ: [0.333333 0.0; 0.0 33.3333] ) FullNormal( dim: 2 μ: [3.80446, 86.3386] Σ: [0.409737 0.2216; 0.2216 20.2179] ) FullNormal( dim: 2 μ: [3.31476, 72.6624] Σ: [0.333333 0.0; 0.0 33.3333] ) FullNormal( dim: 2 μ: [3.95635, 79.2482] Σ: [0.163805 1.07272; 1.07272 45.0006] ) FullNormal( dim: 2 μ: [3.82633, 60.1778] Σ: [0.333333 0.0; 0.0 33.3333] ) FullNormal( dim: 2 μ: [2.70389, 57.3163] Σ: [0.423094 4.68636; 4.68636 69.6156] ) FullNormal( dim: 2 μ: [4.51578, 72.9886] Σ: [0.333333 0.0; 0.0 33.3333] ) FullNormal( dim: 2 μ: [4.42087, 80.5662] Σ: [0.101807 0.45467; 0.45467 28.6922] ) FullNormal( dim: 2 μ: [3.57291, 62.0741] Σ: [0.333333 0.0; 0.0 33.3333] ) … FullNormal( dim: 2 μ: [2.47015, 55.678] Σ: [0.265131 2.95173; 2.95173 55.8681] ) ªtext/plain’¡R’Ú ½6×272×120 Array{Float64, 3}: [:, :, 1] = 0.166667 0.166667 0.166667 0.166667 … 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 0.166667 … 0.166667 0.166667 0.166667 0.166667 [:, :, 2] = 0.0334305 0.791507 0.117296 … 0.000181688 0.35124 0.000683434 0.00660918 1.37119e-7 0.00131983 0.0162787 4.30092e-10 3.01916e-6 0.696345 0.00758745 0.690529 0.119728 0.00164355 0.112473 0.00654938 0.0525124 0.028048 6.40983e-5 0.23365 0.0260373 0.237536 3.09111e-6 0.085711 0.863556 6.58269e-7 0.830583 0.0195301 0.14839 0.0770954 … 0.000192033 0.413466 0.0302208 [:, :, 3] = 4.79769e-5 0.833547 0.00260193 … 2.86942e-11 0.507932 2.60733e-11 0.00240698 1.74887e-13 0.000398605 0.00348038 3.81342e-18 4.02216e-5 0.759349 6.16739e-5 0.888971 0.141414 5.20313e-6 0.0813542 0.00269402 0.0444204 0.0204209 3.27016e-5 0.154463 0.00708219 0.227581 2.50573e-16 0.0286477 0.854988 1.88366e-18 0.905215 0.00792119 0.121971 0.0589594 … 8.45028e-5 0.3376 0.0063085 ;;; … [:, :, 118] = 5.57557e-15 0.971682 5.87457e-10 … 7.95452e-34 0.879584 2.47811e-34 0.000747297 1.70009e-16 0.000140195 0.000987611 2.9377e-22 1.15159e-5 0.795695 4.55769e-8 0.894567 0.210516 4.33408e-9 0.0789169 0.00136513 0.00511513 0.0183056 1.91638e-5 0.0342483 0.00131846 0.199161 5.66805e-17 0.040229 0.78847 5.56927e-19 0.919692 0.00303156 0.0232029 0.0467582 … 7.22977e-6 0.0861679 6.14603e-5 [:, :, 119] = 5.52427e-15 0.971747 5.83772e-10 … 7.79499e-34 0.879796 2.43091e-34 0.000747632 1.66959e-16 0.000140074 0.000987866 2.8557e-22 1.14753e-5 0.795849 4.53433e-8 0.894583 0.210577 4.31487e-9 0.0788944 0.0013654 0.00509487 0.018306 1.92023e-5 0.0341879 0.00131701 0.199007 5.65938e-17 0.0402015 0.788409 5.56709e-19 0.919716 0.00303171 0.0231584 0.0467695 … 7.20931e-6 0.0860159 6.09146e-5 [:, :, 120] = 5.4742e-15 0.971811 5.80166e-10 … 7.64098e-34 0.880006 2.38533e-34 0.000747971 1.63981e-16 0.000139955 0.000988127 2.77643e-22 1.1435e-5 0.796001 4.51133e-8 0.894599 0.210637 4.29596e-9 0.0788722 0.00136566 0.00507485 0.0183063 1.92405e-5 0.0341281 0.00131557 0.198853 5.65073e-17 0.0401742 0.788349 5.56486e-19 0.91974 0.00303184 0.0231145 0.0467807 … 7.18899e-6 0.0858656 6.03781e-5ªtext/plain°persist_js_stateÂÙ$26c5cfb4-d294-11ef-05bb-59d5e27cf37cЧrunning§runtimeÎú�¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c5cfb4-d294-11ef-05bb-59d5e27cf37c¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Âl©·has_pluto_hook_features¤bodyÚ<

The Marginal Distribution for the GMM

In the literature, the GMM is often introduced by the marginal distribution for an observed data point $x_n$, given by

$$\begin{align*}{} p(x_n) &= \sum_{z_n} p(x_n,z_n) \\ &= \sum_{k=1}^K \pi_k \cdot \mathcal{N}\left( x_n | \mu_k, \Sigma_k \right) \tag{B-9.12} \end{align*}$$

°persist_js_stateÂÙ$a7fb83cb-1f40-4c8a-9fda-2165f91e413eЧrunning§runtimeÎ?ø¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$a7fb83cb-1f40-4c8a-9fda-2165f91e413e¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime­image/svg+xml¬rootassigneeÀ²last_run_timestampËAÚ¹&¡³¥œ·has_pluto_hook_features¤bodyÉ7 °persist_js_stateÂÙ$64819124-865e-48b8-a916-2ce08dba0accЧrunning§runtimeÎH¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$64819124-865e-48b8-a916-2ce08dba0acc¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&›x±)·has_pluto_hook_features¤bodyÙ °persist_js_stateÂÙ$16d90f11-5933-4145-b219-19774eba25d6Чrunning§runtimeÎ.WçS¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$16d90f11-5933-4145-b219-19774eba25d6¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šóÛ·has_pluto_hook_features¤bodyÙ‹ °persist_js_stateÂÙ$06170e31-e865-4178-8af0-41d82df95d71Чrunning§runtimeÎÈâ8¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$06170e31-e865-4178-8af0-41d82df95d71¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&› 2·has_pluto_hook_features¤bodyÚþ

🎯 Key concept

Constrained VFE minimization is consistent with the Maximum Entropy Principle, which prescribes how to rationally update beliefs when new information becomes available. In this framework, the updated posterior is the distribution that minimizes VFE (or equivalently, KL divergence to the prior) subject to the imposed constraints.

°persist_js_stateÂÙ$f1f7407d-86a1-4f24-b78a-61a411d1f371Чrunning§runtime΀ٸdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$f1f7407d-86a1-4f24-b78a-61a411d1f371¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ã|·has_pluto_hook_features¤bodyÙV

Variational Inference

°persist_js_stateÂÙ$5af3ff1b-1655-4dd9-a089-91544fc85a0eЧrunning§runtimeλŽ/¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$5af3ff1b-1655-4dd9-a089-91544fc85a0e¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&¡aøº·has_pluto_hook_features¤bodyÚ<°persist_js_stateÂÙ$8555aec9-4e80-49e7-8514-ef4a2236801bЧrunning§runtimeÍ36¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$8555aec9-4e80-49e7-8514-ef4a2236801b¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassignee¡N²last_run_timestampËAÚ¹&�,qm·has_pluto_hook_features¤body£272°persist_js_stateÂÙ$26c65092-d294-11ef-39cc-1953a725f285Чrunning§runtimeÎ…¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c65092-d294-11ef-39cc-1953a725f285¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ãdõ·has_pluto_hook_features¤bodyÚ�

Can we still compute an approximate posterior? In this lesson, we introduce an approximate Bayesian inference method known as Variational Bayes (VB) (also known as Variational Inference) that can be used for Bayesian inference in models with latent variables. Later in this lesson, we will use VB to do inference in the GMM.

°persist_js_stateÂÙ$3948225e-90d8-4b78-ba9b-5f98e228285aЧrunning§runtimeÎ-(q„¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$3948225e-90d8-4b78-ba9b-5f98e228285a¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime­image/svg+xml¬rootassigneeÀ²last_run_timestampËAÚ¹&�&×o·has_pluto_hook_features¤bodyÈì4 °persist_js_stateÂÙ$95d47a10-f3f8-479b-afe0-21241104b758Чrunning§runtimeÍe*¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$95d47a10-f3f8-479b-afe0-21241104b758¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šëÃ/·has_pluto_hook_features¤bodyÚ*

Code Example: VFEM for GMM on Old Faithfull data set

°persist_js_stateÂÙ$26c62ebe-d294-11ef-0cfb-ef186203e890Чrunning§runtimeÎØ4¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c62ebe-d294-11ef-0cfb-ef186203e890¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ãa·has_pluto_hook_features¤bodyÚ$

Since the class labels $y_{nk} \in \{0,1\}$ were assumed to be given by the data set, maximization of this expression decomposed into a set of simple update rules for the Gaussian and multinomial distributions.

°persist_js_stateÂÙ$c4b23b39-e6e4-44ec-b204-0c7d7d5a4026Чrunning§runtimeί¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$c4b23b39-e6e4-44ec-b204-0c7d7d5a4026¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ä'·has_pluto_hook_features¤bodyÚ‚

Since the second term (log-evidence) does not involve $q(z)$, VFEM over $q$ will bring $q(z)$ closer to the Bayesian posterior $p(z|x)$.

Since $D_{\text{KL}}[q(z),p(z|x)]\geq 0$ for any $q(z)$, and $D_{\text{KL}}[q(z),p(z|x)]= 0$ only if $q(z) = p(z|x)$, the VFE is always an upper bound on (minus) log-evidence, i.e.,

$$F[q] \geq -\log p(x) \,.$$

As a result, global minimization of VFE leads to

$$q^*(z) = \arg\min_q F[q]$$

where

$$\begin{align} q^*(z) &= p(z|x) \tag{= posterior}\\ F[q^*] &= -\log p(x) \tag{= -log evidence} \end{align}$$

°persist_js_stateÂÙ$26c5b896-d294-11ef-1d8e-0feb99d2d45bЧrunning§runtimeÎõ‹¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c5b896-d294-11ef-1d8e-0feb99d2d45b¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Â#ê·has_pluto_hook_features¤bodyÚè

We associate a one-hot coded hidden class label $z_n$ with each observation $x_n$:

$$\begin{equation*} z_{nk} = \begin{cases} 1 & \text{if } x_n \in \mathcal{C}_k \text{ (the $k$-th class)}\\ 0 & \text{otherwise} \end{cases} \end{equation*}$$

°persist_js_stateÂÙ$26c623f6-d294-11ef-13c0-19edd43592c0Чrunning§runtimeÎ…8¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c623f6-d294-11ef-13c0-19edd43592c0¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–÷has_pluto_hook_features¤bodyÚ—

Inference for GMM is Difficult

Indeed, the fact that the observation-dependent class labels are unobserved for the GMM, leads to a problem for processing new data by Bayes rule in a GMM.

Consider a given data set $D = \{x_1,x_2,\ldots,x_N\}$. We recall here the log-likelihood for the Gaussian-Categorial Model, see the generative classification lesson:

$$\log\, p(D|\theta) = \sum_{n,k} y_{nk} \underbrace{ \log\mathcal{N}(x_n|\mu_k,\Sigma) }_{ \text{Gaussian} } + \underbrace{ \sum_{n,k} y_{nk} \log \pi_k }_{ \text{multinomial} } \,.$$

°persist_js_stateÂÙ$55570464-89c8-4d9b-b667-dfa64ac62294Чrunning§runtimeÎÙ¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$55570464-89c8-4d9b-b667-dfa64ac62294¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ËÅ]·has_pluto_hook_features¤bodyÙ4

Code

°persist_js_stateÂÙ$26c59b52-d294-11ef-1eba-d3f235f85eeeЧrunning§runtimeÎ-õ¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c59b52-d294-11ef-1eba-d3f235f85eee¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÁÇX·has_pluto_hook_features¤bodyÚŽ

Unobserved Classes

Consider again a set of observed data $D=\{x_1,\dotsc,x_N\}$.

This time, we suspect that there are unobserved class labels that would help explain (or predict) the data, e.g.,

°persist_js_stateÂÙ$f17c9d8a-9291-4110-bcf4-c582d23f986bЧrunning§runtimeΕ¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$f17c9d8a-9291-4110-bcf4-c582d23f986b¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ê�C·has_pluto_hook_features¤bodyÙâ

Variational Message Passing

Let us now consider the local free energy that is associated with edge corresponding to $x_j$.

°persist_js_stateÂÙ$dd1242db-fb20-4732-ac55-a3e021bbd2b7Чrunning§runtimeÎ;£¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$dd1242db-fb20-4732-ac55-a3e021bbd2b7¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeÙ!application/vnd.pluto.tree+object¬rootassignee¶const data_plot_kwargs²last_run_timestampËAÚ¹&œtŸ·has_pluto_hook_features¤bodyƒ¨objectid°cc4be3e3968086c0¤typeªNamedTuple¨elements”’ªmarkersize’¡4ªtext/plain’±markerstrokewidth’¡0ªtext/plain’¥color’¥:red4ªtext/plain’§opacity’£0.8ªtext/plain°persist_js_stateÂÙ$26c73cf0-d294-11ef-297b-354eb9c71f57Чrunning§runtimeÎúK¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c73cf0-d294-11ef-297b-354eb9c71f57¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Æ �·has_pluto_hook_features¤bodyÚ(

Derivation of VFEM Update Equations

Let's get back to the illustrative challenge at the beginning of this lesson: we want to do density modeling for the Old Faithful data set.

°persist_js_stateÂÙ$2d4adbf6-6de8-4e3a-ad6f-fa8bbfa5999eЧrunning§runtimeÎ!‘¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$2d4adbf6-6de8-4e3a-ad6f-fa8bbfa5999e¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–É�k·has_pluto_hook_features¤bodyÚ�

Mean Updating (*)

Explain the following update rule for the mean of the Gaussian cluster-conditional data distribution:

$$m_k = \frac{1}{\beta_k} \left( \beta_0 m_0 + N_k \bar{x}_k \right) \tag{B-10.61} $$

°persist_js_stateÂÙ$26c56fd8-d294-11ef-236d-81deef63f37cЧrunning§runtimeͪõ¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c56fd8-d294-11ef-236d-81deef63f37c¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šTÉK·has_pluto_hook_features¤bodyÚLatent Variable Models and Variational Bayes°persist_js_stateÂÙ$666680b2-315a-4d95-8f7f-3ae50018e112Чrunning§runtimeÍ&±¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$666680b2-315a-4d95-8f7f-3ae50018e112¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassigneeÀ²last_run_timestampËAÚ¹&šõ>´·has_pluto_hook_features¤body °persist_js_stateÂÙ$0349720e-5de4-4b39-babd-c0881588f1deЧrunning§runtimeÎçö†¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$0349720e-5de4-4b39-babd-c0881588f1de¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassignee¡X²last_run_timestampËAÚ¹&œd{Ì·has_pluto_hook_features¤bodyÙÃ2×272 Matrix{Float64}: 3.6 1.8 3.333 2.283 4.533 2.883 … 4.117 2.15 4.417 1.817 4.467 79.0 54.0 74.0 62.0 85.0 55.0 81.0 46.0 90.0 46.0 74.0°persist_js_stateÂÙ$cd7cf2d0-aff7-49dc-bb12-dc73c6433768Чrunning§runtimeÎ%0äĸdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$cd7cf2d0-aff7-49dc-bb12-dc73c6433768¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime­image/svg+xml¬rootassigneeÀ²last_run_timestampËAÚ¹& ¢œ·has_pluto_hook_features¤bodyÉi °persist_js_stateÂÙ$b4d965d1-91d8-43f8-84a5-b37ad5c6cafaЧrunning§runtimeÎù•¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$b4d965d1-91d8-43f8-84a5-b37ad5c6cafa¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ãñ�·has_pluto_hook_features¤bodyÚ…

Note that the inference bound is a Kullback-Leibler (KL) divergence between an (approximate) posterior $q(z)$ and the (perfect) Bayesian posterior $p(z|x)$. To learn more:

°persist_js_stateÂÙ$32f0bbb4-dfc7-431e-9a3d-80162439edacЧrunning§runtimeÎ Ó׸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$32f0bbb4-dfc7-431e-9a3d-80162439edac¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ë_¢·has_pluto_hook_features¤bodyÚÉ

Apparently (see previous slide), there are three contributions to the free energy for $x_j$:

  • one entropy term for the edge $x_j$

  • two energy terms: one for each node that attaches to $x_j$ (in the figure: nodes $p_a$ and $p_b$)

The local free energy for $x_j$ can be written as (exercise)

$$ F[q_j] \propto \sum_{x_j} q(x_j) \log \frac{q_j(x_j)}{\nu_a(x_j)\cdot \nu_b(x_j)} $$

where

$$\begin{align*} \nu_a(x_j) &\propto \exp\left( \mathbb{E}_{q_{k}}\left[ \log p_a(x_a)\right]\right) \\ \nu_b(x_j) &\propto \exp\left( \mathbb{E}_{q_{l}}\left[ \log p_b(x_b)\right]\right) \end{align*}$$

and $\mathbb{E}_{q_{k}}\left[\cdot\right]$ is an expectation w.r.t. all $q(x_k)$ with $k \in N(a)\setminus {j}$.

$\nu_a(x_j)$ and $\nu_b(x_j)$ can be locally computed in nodes $a$ and $b$ respectively and can be interpreted as colliding messages over edge $x_j$.

Local free energy minimization is achieved by setting

$$ q_j(x_j) \propto \nu_a(x_j) \cdot \nu_b(x_j) $$

Note that message $\nu_a(x_j)$ depends on posterior beliefs over incoming edges ($k$) for node $a$, and in turn, the message from node $a$ towards edge $x_k$ depends on the belief $q_j(x_j)$. I.o.w., direct mutual dependencies exist between posterior beliefs over edges that attach to the same node.

These considerations lead to the Variational Message Passing procedure, which is an iterative free energy minimization procedure that can be executed completely through locally computable messages.

Procedure VMP, see Dauwels (2007), section 3

  1. Initialize all messages $q$ and $ν$, e.g., $q(\cdot) \propto 1$ and $\nu(\cdot) \propto 1$. <br/>

  2. Select an edge $z_k$ in the factor graph of $f(z_1,\ldots,z_m)$.<br/>

  3. Compute the two messages $\overrightarrow{\nu}(z_k)$ and $\overleftarrow{\nu}(z_k)$ by applying the following generic rule:

$$ \overrightarrow{\nu}(y) \propto \exp\left( \mathbb{E}_{q}\left[ \log g(x_1,\dots,x_n,y)\right] \right) $$

  1. Compute the marginal $q(z_k)$

$$ q(z_k) \propto \overrightarrow{\nu}(z_k) \overleftarrow{\nu}(z_k) $$

and send it to the two nodes connected to the edge $x_k$.

  1. Iterate 2–4 until convergence.

°persist_js_stateÂÙ$26c85a22-d294-11ef-3c8e-7b72a4313cedЧrunning§runtimeθè¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c85a22-d294-11ef-3c8e-7b72a4313ced¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&›wç·has_pluto_hook_features¤bodyÚm

FE Minimization by the Expectation-Maximization (EM) Algorithm

The EM algorithm is a special case of VFE minimization that focuses on Maximum-Likelihood estimation for models with latent variables.

Consider a model

$$p(x,z,\theta)$$

with observations $x = \{x_n\}$, latent variables $z=\{z_n\}$ and parameters $\theta$.

We can write the following VFE functional for this model:

$$\begin{align*} F[q] = \sum_z \sum_\theta q(z,\theta) \log \frac{q(z,\theta)}{p(x,z,\theta)} \end{align*}$$

The EM algorithm makes the following simplifying assumptions:

  1. The prior for the parameters is uninformative (uniform). This implies that

$$p(x,z,\theta) = p(x,z|\theta) p(\theta) \propto p(x,z|\theta)$$

  1. A factorization constraint

$$q(z,\theta) = q(z) q(\theta)$$

  1. The posterior for the parameters is a delta function:

$$q(\theta) = \delta(\theta - \hat{\theta})$$

Basically, these three assumptions turn VFE minimization into maximum likelihood estimation for the parameters $\theta$ and the VFE simplifies to

$$\begin{align*} F[q,\theta] = \sum_z q(z) \log \frac{q(z)}{p(x,z|\theta)} \end{align*}$$

The EM algorithm minimizes this FE by iterating (iteration counter: $i$) over

$$\begin{align} \mathcal{L}^{(i)}(\theta) &= \sum_z \overbrace{p(z|x,\theta^{(i-1)})}^{q^{(i)}(z)} \log p(x,z|\theta) \tag{the E-step} \\ \theta^{(i)} &= \arg\max_\theta \mathcal{L}^{(i)}(\theta) \tag{the M-step} \end{align} $$

These choices are optimal for the given FE functional. In order to see this, consider the two decompositions

$$\begin{align*} F[q,\theta] &= \underbrace{-\sum_z q(z) \log p(x,z|\theta)}_{\text{energy}} - \underbrace{\sum_z q(z) \log \frac{1}{q(z)}}_{\text{entropy}} \qquad &&\text{(EE)}\\ &= \underbrace{\sum_z q(z) \log \frac{q(z)}{p(z|x,\theta)}}_{\text{divergence}} - \underbrace{\log p(x|\theta)}_{\text{log-likelihood}} \qquad &&\text{(DE)} \end{align*}$$

The DE decomposition shows that the FE is minimized for the choice $q(z) := p(z|x,\theta)$. Also, for this choice, the FE equals the (negative) log-evidence (, which is this case simplifies to the log-likelihood).

The EE decomposition shows that the FE is minimized wrt $\theta$ by minimizing the energy term. The energy term is computed in the E-step and optimized in the M-step.

  • Note that in the EM literature, the energy term is often called the expected complete-data log-likelihood.)

In order to execute the EM algorithm, it is assumed that we can analytically execute the E- and M-steps. For a large set of models (including models whose distributions belong to the exponential family of distributions), this is indeed the case and hence the large popularity of the EM algorithm.

The EM algorihm imposes rather severe assumptions on the FE (basically approximating Bayesian inference by maximum likelihood estimation). Over the past few years, the rise of Probabilistic Programming languages has dramatically increased the range of models for which the parameters can by estimated autmatically by (approximate) Bayesian inference, so the popularity of EM is slowly waning. (More on this in the Probabilistic Programming lessons).

Bishop (2006) works out EM for the GMM in section 9.2.

°persist_js_stateÂÙ$d208f60e-56ea-4767-bd18-f29a853b7536Чrunning§runtimeÎ7wƒ¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$d208f60e-56ea-4767-bd18-f29a853b7536¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime­image/svg+xml¬rootassignee´const cluster_colors²last_run_timestampËAÚ¹&›øÂP·has_pluto_hook_features¤bodyȹ °persist_js_stateÂÙ$26c7696e-d294-11ef-25f2-dbc0946c0858Чrunning§runtimeΡð¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c7696e-d294-11ef-25f2-dbc0946c0858¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÆÄ&·has_pluto_hook_features¤bodyÙ·

Below we exemplify training of a Gaussian Mixture Model on the Old Faithful data set by VFE minimization, with the constraints as specified above.

°persist_js_stateÂÙ$58bd0d43-743c-4745-b353-4a89b35e85baЧrunning§runtimeÎWã%¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$58bd0d43-743c-4745-b353-4a89b35e85ba¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassigneeÀ²last_run_timestampËAÚ¹&™÷7v·has_pluto_hook_features¤body °persist_js_stateÂÙ$b91bc3b6-b815-4942-b297-c0e2b4b99654Чrunning§runtimeÎî©Ï¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$b91bc3b6-b815-4942-b297-c0e2b4b99654¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&›tKf·has_pluto_hook_features¤bodyÚ€
Click for the solution

Let's start with a prior estimate $\theta^{(i-1)}$ and we want to minimize the free energy functional wrt $q$. This leads to

$$\begin{align*} q^{(i)}(z) &= \arg\min_q F[q](\theta^{(i-1)}) \\ &= \arg\min_q \sum_z q(z) \log \frac{q(z)}{p(D,z|\theta^{(i-1)})} \\ &= \arg\min_q \sum_z q(z) \log \frac{q(z)}{p(z|D,\theta^{(i-1)}) \cdot p(D|\theta^{(i-1)})} \\ &= p(z|D,\theta^{(i-1)}) \end{align*}$$

Next, we use $q^{(i)}(z)=p(z|D,\theta^{(i-1)})$ and minimize the free energy w.r.t. $\theta$, leading to

$$\begin{align*} \theta^{(i)} &= \arg\min_\theta F[q^{(i)}](\theta) \\ &= \arg\min_\theta \sum_z p(z|D,\theta^{(i-1)}) \log \frac{p(z|D,\theta^{(i-1)})}{p(D,z|\theta)} \\ &= \arg\max_\theta \sum_z \underbrace{p(z|D,\theta^{(i-1)})}_{q^{(i)}(z)} \log p(D,z|\theta) \end{align*}$$

°persist_js_stateÂÙ$87d94630-c90b-4379-91bd-88641ee7b508Чrunning§runtimeÎO¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$87d94630-c90b-4379-91bd-88641ee7b508¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ê$p·has_pluto_hook_features¤bodyÙå

Implementation

Reading this lecture online? Click "View code" in the top right to read the implementation of this visualisation.

°persist_js_stateÂÙ$56bea391-b812-4fc4-8f27-fcb4cb984cf4Чrunning§runtimeÍ�Ÿdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$56bea391-b812-4fc4-8f27-fcb4cb984cf4¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&› 5·has_pluto_hook_features¤bodyÚ×

Exercises

°persist_js_stateÂÙ$de0c41a3-6319-4ae3-8a1a-ae6935910fa3Чrunning§runtimeεãĸdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$de0c41a3-6319-4ae3-8a1a-ae6935910fa3¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&› …Œ·has_pluto_hook_features¤bodyÚ°persist_js_stateÂÙ$a663d6d1-2d73-40c6-8a4c-9e41df74bc84Чrunning§runtimeÎ鿏depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$a663d6d1-2d73-40c6-8a4c-9e41df74bc84¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ác•·has_pluto_hook_features¤bodyÚ
Problem

You are asked to build a density model for a data set (Old Faithful, Bishop pg. 681) that clearly is not distributed as a single Gaussian:

°persist_js_stateÂÙ$26c5a1f6-d294-11ef-3565-39d027843fbbЧrunning§runtimeÎá7¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c5a1f6-d294-11ef-3565-39d027843fbb¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Áñ€·has_pluto_hook_features¤bodyÙý

Classification problems with unobserved classes are called Clustering problems. In clustering problems, the learning algorithm needs to discover the underlying classes from the observed data.

°persist_js_stateÂÙ$2f490e1f-e495-4f55-a3f8-60d6fd716d4eЧrunning§runtimeθdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$2f490e1f-e495-4f55-a3f8-60d6fd716d4e¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ɡӷhas_pluto_hook_features¤bodyÚ¿

The Expectation-Maximization (EM) algorithm (**)

Consider a model $p(x,z|\theta)$, where $D=\{x_1,x_2,\ldots,x_N\}$ is observed, $z$ are unobserved variables, and $\theta$ are parameters. The Expectation-Maximization (EM) algorithm estimates the parameters by iterating over the following two equations ($i$ is the iteration index):

$$\begin{align*} q^{(i)}(z) &= p(z|D,\theta^{(i-1)}) \\ \theta^{(i)} &= \arg\max_\theta \sum_z q^{(i)}(z) \cdot \log p(D,z|\theta) \end{align*}$$

Prove that this algorithm minimizes the Free Energy functional

$$\begin{align*} F[q](\theta) = \sum_z q(z) \log \frac{q(z)}{p(D,z|\theta)} \end{align*}$$

°persist_js_stateÂÙ$26c796c8-d294-11ef-25be-17dcd4a9d315Чrunning§runtimeÎø!¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c796c8-d294-11ef-25be-17dcd4a9d315¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Ç[Ä·has_pluto_hook_features¤bodyÚ’

The generated figure resembles Figure 10.6 in Bishop. The plots show VFEM results for a GMM of $K = 6$ Gaussians applied to the Old Faithful data set. The ellipses denote the two standard-deviation density contours for each of the components, and the color coding of the data points reflects the "soft" class label assignments.

°persist_js_stateÂÙ$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2Чrunning§runtimeÎsg¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2¹depends_on_disabled_cells¦queued¤logs�¦output†¤mimeªtext/plain¬rootassigneeÀ²last_run_timestampËAÚ¹&�Ai·has_pluto_hook_features¤bodyÙ6updateMeanPrecisionPi (generic function with 1 method)°persist_js_stateÂÙ$26c867d8-d294-11ef-2372-d75ed0bcc02dЧrunning§runtimeÎLƒ¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c867d8-d294-11ef-2372-d75ed0bcc02d¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÉþÒ·has_pluto_hook_features¤bodyÙÈ

We'll perform clustering on the data set from the challenge by fitting a GMM consisting of two Gaussians using the EM algorithm.

°persist_js_stateÂÙ$26c8160c-d294-11ef-2a74-6f7009a7c51eЧrunning§runtimeÎÊò¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c8160c-d294-11ef-2a74-6f7009a7c51e¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ɺ™·has_pluto_hook_features¤bodyÙJ

Optional Slides

°persist_js_stateÂÙ$26c64174-d294-11ef-2bbc-ab1a84532311Чrunning§runtimeÎÛj¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c64174-d294-11ef-2bbc-ab1a84532311¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÃI�·has_pluto_hook_features¤bodyÚï

There is no known conjugate prior for the latent variables in the GMM likelihood. Therefore, Bayes rule does not yield a closed-form expression for the posterior over the latent variables:

$$ \underbrace{p(\{z_{nk}\},\{\mu_k,\Sigma_k,\pi_k\} | D)}_{\text{posterior (no analytical solution)}} \propto \underbrace{p(D\,|\,\{z_{nk}\},\{\mu_k,\Sigma_k,\pi_k\})}_{\text{likelihood}} \cdot \underbrace{p( \{z_{nk}\},\{\mu_k,\Sigma_k,\pi_k\} )}_{\text{prior (no known conjugate)}} $$

°persist_js_stateÂÙ$208ba1bb-a4bf-4b8c-93d2-0d6c6c8d16d4Чrunning§runtimeÎêà¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$208ba1bb-a4bf-4b8c-93d2-0d6c6c8d16d4¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&›^·has_pluto_hook_features¤bodyÚ
Click for the solution

We see here an example of "precision-weighted means add" when two sources of information are fused, just like precision-weighted means add when two Gaussians are multiplied, eg a prior and likelihood. In this case, the prior is $m_0$ and the likelihood estimate is $\bar{x}$. $\beta_0$ can be interpreted as the number of pseudo-observations in the prior.

°persist_js_stateÂÙ$26c6f63c-d294-11ef-1090-e9238dd6ad3fЧrunning§runtimeÎyŸ¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c6f63c-d294-11ef-1090-e9238dd6ad3f¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–ÄéÝ·has_pluto_hook_features¤bodyÚÝ

Constrained VFE Minimization

It is common to add simplifying constraints to an optimization problem to make a difficult optimization task tractible. This is also standard practice when approximating Bayesian inference by FE minimization.

There are three important cases of adding constraints to the VFE functional that often alleviate the VFE minimization task:

  • form constraints on $q(z)$

  • factorization constraints on $q(z)$

  • other (ad hoc) constraints

We will shortly discuss these simplifications below.

°persist_js_stateÂÙ$aea77d69-9ecd-4be0-b6fd-c944d27d68dfЧrunning§runtimeÎ&k¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$aea77d69-9ecd-4be0-b6fd-c944d27d68df¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&–Å~·has_pluto_hook_features¤bodyÚ-
1. Form constraints

For almost every practical setting, we constrain the posterior $q(z)$ to belong to a specific parameterized family of probability distributions, e.g.,

$$q(z) = \mathcal{N}\left( z | \mu, \Sigma \right)\,.$$

In this case, the functional minimization problem for $F[q]$ simplifies to the minimization of an ordinary function

$$F(\mu,\Sigma) = \int \mathcal{N}\left( z | \mu, \Sigma \right) \log \frac{\mathcal{N}\left( z | \mu, \Sigma \right)}{p(x,z)}\mathrm{d}z$$

with respect to the parameters $\mu$ and $\Sigma$.

We can often use standard gradient-based optimization methods to minimize the function $F(\mu,\Sigma)\,.$

°persist_js_stateÂÙ$26c82f16-d294-11ef-0fe1-07326b56282fЧrunning§runtimeÎ"E¸depends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$26c82f16-d294-11ef-0fe1-07326b56282f¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&›uM·has_pluto_hook_features¤bodyÚ·

VFE Minimization with Mean-field Factorization Constraints: the CAVI Approach

Let's work out VFE minimization with additional mean-field constraints (=full factorization) constraints:

$$q(z) = \prod_{j=1}^m q_j(z_j)\,.$$

In other words, the posteriors for $z_j$ are all considered independent. This is a strong constraint but often leads to good solutions.

Given the mean-field constraints, it is possible to derive the following expression for the optimal solutions $q_j^*(z_j)$, for $j=1,\ldots,m$:

$$\begin{align} \log q_j^*(z_j) &\propto \mathrm{E}_{q_{-j}^*}\left[ \log p(x,z) \right] \\ &= \underbrace{\sum_{z_{-j}} q_{-j}^*(z_{-j}) \underbrace{\log p(x,z)}_{\text{"field"}}}_{\text{"mean field"}} \end{align} $$

where we defined $q_{-j}^*(z_{-j}) \triangleq q_1^*(z_1)q_2^*(z_2)\cdots q_{j-1}^*(z_{j-1})q_{j+1}^*(z_{j+1})\cdots q_m^*(z_m)$.

Proof (from Blei, 2017): We first rewrite the FE as a function of $q_j(z_j)$ only:

$$ F[q_j] = \mathbb{E}_{q_{j}}\left[ \mathbb{E}_{q_{-j}}\left[ \log p(x,z_j,z_{-j})\right]\right] - \mathbb{E}_{q_j}\left[ \log q_j(z_j)\right] + \mathtt{const.}\,,$$

where the constant holds all terms that do not depend on $z_j$. This expression can be written as

$$ F[q_j] = \sum_{z_j} q_j(z_j) \log \frac{q_j(z_j)}{\exp\left( \mathbb{E}_{q_{-j}}\left[ \log p(x,z_j,z_{-j})\right]\right)}$$

which is a KL-divergence that is minimized by Eq. B-10.9. (end proof)

This is not yet a full solution to the FE minimization task since the solution $q_j^*(z_j)$ depends on expectations that involve other solutions $q_{i\neq j}^*(z_{i \neq j})$, and each of these other solutions $q_{i\neq j}^*(z_{i \neq j})$ depends on an expection that involves $q_j^*(z_j)$.

In practice, we solve this chicken-and-egg problem by an iterative approach: we first initialize all $q_j(z_j)$ (for $j=1,\ldots,m$) to an appropriate initial distribution and then cycle through the factors in turn by solving eq.B-10.9 and update $q_{-j}^*(z_{-j})$ with the latest estimates. (See Blei, 2017, Algorithm 1, p864).

This algorithm for approximating Bayesian inference is known Coordinate Ascent Variational Inference (CAVI).

°persist_js_stateÂÙ$87715fcd-c92e-4bfa-8b0a-15e469548f3dЧrunning§runtimeΡŸdepends_on_skipped_cellsµpublished_object_keys�§errored§cell_idÙ$87715fcd-c92e-4bfa-8b0a-15e469548f3d¹depends_on_disabled_cells¦queued¤logs�¦output†¤mime©text/html¬rootassigneeÀ²last_run_timestampËAÚ¹&šé†]·has_pluto_hook_features¤bodyÚJ

🎯 Key concept

For a model $p(x,z) = p(x|z) p(x)$, the variational free energy functional

$$ F[q] = \underbrace{ \int q(z) \log \frac{q(z)}{p(z)} \mathrm{d}z }_{\text{complexity}} - \underbrace{\int q(z) \log p(x|z) \mathrm{d}z}_{\text{accuracy}}$$

is considered a functional of a variational posterior $q(z)$ over the latent variables $z$. Minimizing $F[q]$ accomplishes approximate Bayesian inference by

$$\begin{align*} \hat{q}(z) &\approx p(z|x) \\ F[\hat{q}] &\approx -\log p(x) \end{align*}$$

°persist_js_state±published_objects€­julia_version§v1.13.3±cell_dependenciesÞjÙ$26c74c9a-d294-11ef-2d31-67bd57d56d7c„´precedence_heuristic §cell_idÙ$26c74c9a-d294-11ef-2d31-67bd57d56d7c´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$430a56c9-93ad-4513-b11c-2ac212109b12„´precedence_heuristic §cell_idÙ$430a56c9-93ad-4513-b11c-2ac212109b12´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c6347c-d294-11ef-056f-7b78a9e22272„´precedence_heuristic §cell_idÙ$26c6347c-d294-11ef-056f-7b78a9e22272´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c8c7fa-d294-11ef-0444-6555ecf5c721„´precedence_heuristic §cell_idÙ$26c8c7fa-d294-11ef-0444-6555ecf5c721´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$2497529b-7703-4e3e-b9db-83f8dbf43fa8„´precedence_heuristic §cell_idÙ$2497529b-7703-4e3e-b9db-83f8dbf43fa8´downstream_cells_map€²upstream_cells_map�³challenge_statement�Ù$5a94e2a4-7134-462e-9dc5-56083769049f„´precedence_heuristic §cell_idÙ$5a94e2a4-7134-462e-9dc5-56083769049f´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c5c1ae-d294-11ef-15c6-13cae5bc0dc8„´precedence_heuristic §cell_idÙ$26c5c1ae-d294-11ef-15c6-13cae5bc0dc8´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$dff0212b-f3e8-4592-8cd4-f52bcdb782fb„´precedence_heuristic §cell_idÙ$dff0212b-f3e8-4592-8cd4-f52bcdb782fb´downstream_cells_map€²upstream_cells_mapƒ§@md_str�¨getindex�ªkeyconcept�Ù$26c704f6-d294-11ef-1b3d-d52f0fb1c81d„´precedence_heuristic §cell_idÙ$26c704f6-d294-11ef-1b3d-d52f0fb1c81d´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$c90176ea-918b-4643-a10f-cef277c5ea75„´precedence_heuristic§cell_idÙ$c90176ea-918b-4643-a10f-cef277c5ea75´downstream_cells_map„­LinearAlgebra�¦PDMats‘Ù$4ee377c2-a126-4c40-8053-517d40c5ef9d¦Random’Ù$cd7cf2d0-aff7-49dc-bb12-dc73c6433768Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413e°SpecialFunctions�²upstream_cells_map€Ù$93e7c7d5-a940-4764-8784-07af2f056e49„´precedence_heuristic §cell_idÙ$93e7c7d5-a940-4764-8784-07af2f056e49´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$7a3c0ff7-0b32-4954-ae28-b644f4d966ef„´precedence_heuristic §cell_idÙ$7a3c0ff7-0b32-4954-ae28-b644f4d966ef´downstream_cells_map‡¨clusters�¦Ï€_hat�£rec�¢Î³�©em_result“Ù$5af3ff1b-1655-4dd9-a089-91544fc85a0eÙ$fd233604-120a-4838-a660-d5021bccecd0Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413e±updateParameters!�·updateResponsibilities!�²upstream_cells_mapÞ¡/�¡^�£NaN�¡X‘Ù$0349720e-5de4-4b39-babd-c0881588f1de¤Text�¡-�§adjoint�¥fill!�¨MvNormal�¡N‘Ù$8555aec9-4e80-49e7-8514-ef4a2236801b£sum�§Float64�©Symmetric�¨deepcopy�§convert�¥push!�¡:�¢=>�¤conj�¦Matrix�¥undef�£pdf�¡*�Ù$26c5a93a-d294-11ef-23a1-cbcf0c370fc9„´precedence_heuristic §cell_idÙ$26c5a93a-d294-11ef-23a1-cbcf0c370fc9´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$3e897a59-e7b5-492c-8a8a-724248513a72„´precedence_heuristic §cell_idÙ$3e897a59-e7b5-492c-8a8a-724248513a72´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c8068a-d294-11ef-3983-a1be55128b3f„´precedence_heuristic §cell_idÙ$26c8068a-d294-11ef-3983-a1be55128b3f´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$ae7ed1fc-fc36-4327-be55-a142477ca0ad„´precedence_heuristic §cell_idÙ$ae7ed1fc-fc36-4327-be55-a142477ca0ad´downstream_cells_map€²upstream_cells_mapƒ§@md_str�ªhide_proof�¨getindex�Ù$86c33a7c-135a-461f-a17e-b50bca418e13„´precedence_heuristic §cell_idÙ$86c33a7c-135a-461f-a17e-b50bca418e13´downstream_cells_map�´sufficientStatistics‘Ù$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2²upstream_cells_map‰¤conj�¡/�£Int�¡:�¡-�¡N‘Ù$8555aec9-4e80-49e7-8514-ef4a2236801b£sum�§adjoint�¡*�Ù$26c8b682-d294-11ef-1331-2bcf8baec73f„´precedence_heuristic §cell_idÙ$26c8b682-d294-11ef-1331-2bcf8baec73f´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$f42a1a65-20ce-452f-9974-bc8146943574„´precedence_heuristic §cell_idÙ$f42a1a65-20ce-452f-9974-bc8146943574´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$edb179df-5cff-4e7b-8645-6da4818dceee„´precedence_heuristic §cell_idÙ$edb179df-5cff-4e7b-8645-6da4818dceee´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$06512595-bdb7-4adf-88ae-62af20210891„´precedence_heuristic §cell_idÙ$06512595-bdb7-4adf-88ae-62af20210891´downstream_cells_map€²upstream_cells_map�²challenge_solution�Ù$3deadfd0-9fbb-476a-a7de-5dd694e55a65„´precedence_heuristic §cell_idÙ$3deadfd0-9fbb-476a-a7de-5dd694e55a65´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$3654551d-5d08-4bb0-8a0d-c7d42225bc69„´precedence_heuristic §cell_idÙ$3654551d-5d08-4bb0-8a0d-c7d42225bc69´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$670f83cb-66d6-40ab-9c42-50e022a9bd4c„´precedence_heuristic §cell_idÙ$670f83cb-66d6-40ab-9c42-50e022a9bd4c´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$c563de07-0036-4dc4-87ee-e8363e9b6b1b„´precedence_heuristic §cell_idÙ$c563de07-0036-4dc4-87ee-e8363e9b6b1b´downstream_cells_map€²upstream_cells_map�²navigate_prev_next�Ù$90fbe618-fc81-480b-b685-69cd97e5b8ed„´precedence_heuristic §cell_idÙ$90fbe618-fc81-480b-b685-69cd97e5b8ed´downstream_cells_map€²upstream_cells_map‚¨Resource�¢=>�Ù$f8c8013a-3e87-4d01-a3ae-86b39cf1f002„´precedence_heuristic §cell_idÙ$f8c8013a-3e87-4d01-a3ae-86b39cf1f002´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$4e0c025d-fa39-462d-8e7d-e66d220e9595„´precedence_heuristic §cell_idÙ$4e0c025d-fa39-462d-8e7d-e66d220e9595´downstream_cells_map�®max_iterations’Ù$de0c41a3-6319-4ae3-8a1a-ae6935910fa3Ù$4ee377c2-a126-4c40-8053-517d40c5ef9d²upstream_cells_map€Ù$ce7d086b-ff20-4da1-a4e8-52b5b7dc9e2b„´precedence_heuristic §cell_idÙ$ce7d086b-ff20-4da1-a4e8-52b5b7dc9e2b´downstream_cells_map€²upstream_cells_map‚·PlutoUI.TableOfContents�§PlutoUI�Ù$26c58298-d294-11ef-2a53-2b42b48e0725„´precedence_heuristic §cell_idÙ$26c58298-d294-11ef-2a53-2b42b48e0725´downstream_cells_map€²upstream_cells_mapƒ§@md_str�¨getindex�¤HTML�Ù$26c728f0-d294-11ef-0c01-6143abe8c3f0„´precedence_heuristic §cell_idÙ$26c728f0-d294-11ef-0c01-6143abe8c3f0´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$df171940-eb54-48e2-a2b8-1a8162cabf3e„´precedence_heuristic§cell_idÙ$df171940-eb54-48e2-a2b8-1a8162cabf3e´downstream_cells_map�²BmlipTeachingTools�²upstream_cells_map€Ù$489cbd24-1a69-4a00-a2e9-53c2c57cef65„´precedence_heuristic §cell_idÙ$489cbd24-1a69-4a00-a2e9-53c2c57cef65´downstream_cells_map�§plotGMM’Ù$663ac0ef-0577-43af-8df5-15e046ef875cÙ$fd233604-120a-4838-a660-d5021bccecd0²upstream_cells_mapÞ¤mean�¡/�¦isless�©get_color‘Ù$0e9e62ea-1b2f-4e80-b78b-2001ae46093f¦repeat�§eachcol�¦Vector�¦length�¡+�©plot_lims‘Ù$c18b7c1b-8011-469b-ad92-7d50c23c46e3£sum�§Float64�£cov�¨scatter!�°data_plot_kwargs‘Ù$dd1242db-fb20-4732-ac55-a3e021bbd2b7¨LinRange�¡:�¤sqrt�£max�«covellipse!�¦Matrix�®cluster_colors‘Ù$d208f60e-56ea-4767-bd18-f29a853b7536¥undef�¤plot�¡*�Ù$26c7b428-d294-11ef-150a-bb37e37f4b5d„´precedence_heuristic §cell_idÙ$26c7b428-d294-11ef-150a-bb37e37f4b5d´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$8b887c4a-273c-40fe-83e9-5c79ac6946f8„´precedence_heuristic §cell_idÙ$8b887c4a-273c-40fe-83e9-5c79ac6946f8´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c5f8d6-d294-11ef-3bcd-4d5e0391698d„´precedence_heuristic §cell_idÙ$26c5f8d6-d294-11ef-3bcd-4d5e0391698d´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$663ac0ef-0577-43af-8df5-15e046ef875c„´precedence_heuristic §cell_idÙ$663ac0ef-0577-43af-8df5-15e046ef875c´downstream_cells_map€²upstream_cells_map‹¦isless�¡X‘Ù$0349720e-5de4-4b39-babd-c0881588f1de§plotGMM‘Ù$489cbd24-1a69-4a00-a2e9-53c2c57cef65«vfem_result‘Ù$4ee377c2-a126-4c40-8053-517d40c5ef9d¡+�¡>�§nothing�¡:�¡<�®iteration_vfem‘Ù$de0c41a3-6319-4ae3-8a1a-ae6935910fa3¢==�Ù$baec0494-9557-49d1-b4d8-a8030d3281b7„´precedence_heuristic §cell_idÙ$baec0494-9557-49d1-b4d8-a8030d3281b7´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$18f5d694-8869-4265-98ac-9ef7ff451eaf„´precedence_heuristic §cell_idÙ$18f5d694-8869-4265-98ac-9ef7ff451eaf´downstream_cells_map€²upstream_cells_map�¬NotebookCard�Ù$c7351bf1-447e-475b-8965-d259c01bfd57„´precedence_heuristic §cell_idÙ$c7351bf1-447e-475b-8965-d259c01bfd57´downstream_cells_map€²upstream_cells_mapƒ§@md_str�ªhide_proof�¨getindex�Ù$55a1c42b-20d8-47a3-aa00-7af905db537c„´precedence_heuristic §cell_idÙ$55a1c42b-20d8-47a3-aa00-7af905db537c´downstream_cells_map�§updateR‘Ù$4ee377c2-a126-4c40-8053-517d40c5ef9d²upstream_cells_mapÞ¡/�¡X‘Ù$0349720e-5de4-4b39-babd-c0881588f1de¡-�£exp�§digamma�§adjoint�¡K‘Ù$666680b2-315a-4d95-8f7f-3ae50018e112¡+�¡N‘Ù$8555aec9-4e80-49e7-8514-ef4a2236801b£sum�§Float64�¡:�¥Array�£log�¤conj�¥undef�¦logdet�¡*�Ù$747a7e1e-b921-4882-b00a-1b00bef8433d„´precedence_heuristic §cell_idÙ$747a7e1e-b921-4882-b00a-1b00bef8433d´downstream_cells_map€²upstream_cells_mapƒ­hide_solution�§@md_str�¨getindex�Ù$b3bb7349-1965-4734-83ed-ba6fef0ccc41„´precedence_heuristic §cell_idÙ$b3bb7349-1965-4734-83ed-ba6fef0ccc41´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c6e002-d294-11ef-15a4-33e30d0d76ec„´precedence_heuristic §cell_idÙ$26c6e002-d294-11ef-15a4-33e30d0d76ec´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$60a50f12-063c-4247-9c9c-bb41d5dc9811„´precedence_heuristic §cell_idÙ$60a50f12-063c-4247-9c9c-bb41d5dc9811´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$0e9e62ea-1b2f-4e80-b78b-2001ae46093f„´precedence_heuristic §cell_idÙ$0e9e62ea-1b2f-4e80-b78b-2001ae46093f´downstream_cells_map�©get_color‘Ù$489cbd24-1a69-4a00-a2e9-53c2c57cef65²upstream_cells_map‡¤mean�®cluster_colors‘Ù$d208f60e-56ea-4767-bd18-f29a853b7536£zip�£any�£sum�¡*�¥isnan�Ù$40ce0abb-a086-4977-9131-10f60ab44152„´precedence_heuristic §cell_idÙ$40ce0abb-a086-4977-9131-10f60ab44152´downstream_cells_map€²upstream_cells_mapƒ§@md_str�¨getindex�ªkeyconcept�Ù$4ff85bda-22bb-408d-a50a-461834b7c0ff„´precedence_heuristic §cell_idÙ$4ff85bda-22bb-408d-a50a-461834b7c0ff´downstream_cells_map€²upstream_cells_map�±keyconceptsummary�Ù$26c75b5e-d294-11ef-173e-b3f46a1df536„´precedence_heuristic §cell_idÙ$26c75b5e-d294-11ef-173e-b3f46a1df536´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$fd233604-120a-4838-a660-d5021bccecd0„´precedence_heuristic §cell_idÙ$fd233604-120a-4838-a660-d5021bccecd0´downstream_cells_map€²upstream_cells_map†¢==�¬iteration_em‘Ù$5af3ff1b-1655-4dd9-a089-91544fc85a0e¡X‘Ù$0349720e-5de4-4b39-babd-c0881588f1de©em_result‘Ù$7a3c0ff7-0b32-4954-ae28-b644f4d966ef§nothing�§plotGMM‘Ù$489cbd24-1a69-4a00-a2e9-53c2c57cef65Ù$c18b7c1b-8011-469b-ad92-7d50c23c46e3„´precedence_heuristic §cell_idÙ$c18b7c1b-8011-469b-ad92-7d50c23c46e3´downstream_cells_map�©plot_lims“Ù$cd7cf2d0-aff7-49dc-bb12-dc73c6433768Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413eÙ$489cbd24-1a69-4a00-a2e9-53c2c57cef65²upstream_cells_map€Ù$bbdca8c2-022f-42be-bcf7-80d86f7f269c„´precedence_heuristic §cell_idÙ$bbdca8c2-022f-42be-bcf7-80d86f7f269c´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$cc547bfa-a130-4382-af47-73de56e4741b„´precedence_heuristic §cell_idÙ$cc547bfa-a130-4382-af47-73de56e4741b´downstream_cells_map�¬old_faithful‘Ù$0349720e-5de4-4b39-babd-c0881588f1de²upstream_cells_map€Ù$62868f61-95c7-4e07-854f-a171aadc667b„´precedence_heuristic §cell_idÙ$62868f61-95c7-4e07-854f-a171aadc667b´downstream_cells_map€²upstream_cells_map�¬code_example�Ù$26c5d734-d294-11ef-20a3-afd2c3324323„´precedence_heuristic §cell_idÙ$26c5d734-d294-11ef-20a3-afd2c3324323´downstream_cells_map€²upstream_cells_map…¤Base�­Base.getindex�©@html_str�§@md_str�®Base.Docs.HTML�Ù$26c9121e-d294-11ef-18e6-ed8105503adc„´precedence_heuristic §cell_idÙ$26c9121e-d294-11ef-18e6-ed8105503adc´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c67f04-d294-11ef-03a4-838ae255689d„´precedence_heuristic §cell_idÙ$26c67f04-d294-11ef-03a4-838ae255689d´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$4ee377c2-a126-4c40-8053-517d40c5ef9d„´precedence_heuristic §cell_idÙ$4ee377c2-a126-4c40-8053-517d40c5ef9d´downstream_cells_map�«vfem_result’Ù$663ac0ef-0577-43af-8df5-15e046ef875cÙ$cd7cf2d0-aff7-49dc-bb12-dc73c6433768²upstream_cells_mapÞ¡/�£inv�¡-�®max_iterations‘Ù$4e0c025d-fa39-462d-8e7d-e66d220e9595¡K‘Ù$666680b2-315a-4d95-8f7f-3ae50018e112¨MvNormal�¤fill�¡+�¡N‘Ù$8555aec9-4e80-49e7-8514-ef4a2236801b§Float64�©Hermitian�§convert�¬Distribution�¯MersenneTwister�¦PDMats‘Ù$c90176ea-918b-4643-a10f-cef277c5ea75¡:�¥Array�§updateR‘Ù$55a1c42b-20d8-47a3-aa00-7af905db537c¦Matrix�µupdateMeanPrecisionPi‘Ù$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2¬PDMats.PDMat�¥undef�¤rand�¤ones�¡*�Ù$26c5cfb4-d294-11ef-05bb-59d5e27cf37c„´precedence_heuristic §cell_idÙ$26c5cfb4-d294-11ef-05bb-59d5e27cf37c´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413e„´precedence_heuristic §cell_idÙ$a7fb83cb-1f40-4c8a-9fda-2165f91e413e´downstream_cells_map€²upstream_cells_mapÞ¤mean�¡/�¸show_em_synthetic_labels‘Ù$64819124-865e-48b8-a916-2ce08dba0acc¡X‘Ù$0349720e-5de4-4b39-babd-c0881588f1de«Categorical�¬Random.seed!�¬iteration_em‘Ù$5af3ff1b-1655-4dd9-a089-91544fc85a0e¦Random‘Ù$c90176ea-918b-4643-a10f-cef277c5ea75©plot_lims‘Ù$c18b7c1b-8011-469b-ad92-7d50c23c46e3©em_result‘Ù$7a3c0ff7-0b32-4954-ae28-b644f4d966ef£any�£sum�§nothing�§Float64�£vec�°data_plot_kwargs‘Ù$dd1242db-fb20-4732-ac55-a3e021bbd2b7¡:�§scatter�¥isnan�¦Matrix�®cluster_colors‘Ù$d208f60e-56ea-4767-bd18-f29a853b7536¥undef�¤size�¤rand�¤ones�Ù$64819124-865e-48b8-a916-2ce08dba0acc„´precedence_heuristic §cell_idÙ$64819124-865e-48b8-a916-2ce08dba0acc´downstream_cells_map�¸show_em_synthetic_labels‘Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413e²upstream_cells_map‹°HypertextLiteral�¸HypertextLiteral.content�¤@htl�¨CheckBox�«PlutoRunner�»PlutoRunner.Core.applicable�¥@bind�·HypertextLiteral.Result�Ù#PlutoRunner.PlutoRunner.create_bond�·HypertextLiteral.Bypass�´PlutoRunner.Base.get�Ù$16d90f11-5933-4145-b219-19774eba25d6„´precedence_heuristic §cell_idÙ$16d90f11-5933-4145-b219-19774eba25d6´downstream_cells_map�ºshow_vfem_synthetic_labels‘Ù$cd7cf2d0-aff7-49dc-bb12-dc73c6433768²upstream_cells_map‹°HypertextLiteral�¸HypertextLiteral.content�¤@htl�¨CheckBox�«PlutoRunner�»PlutoRunner.Core.applicable�¥@bind�·HypertextLiteral.Result�Ù#PlutoRunner.PlutoRunner.create_bond�·HypertextLiteral.Bypass�´PlutoRunner.Base.get�Ù$06170e31-e865-4178-8af0-41d82df95d71„´precedence_heuristic §cell_idÙ$06170e31-e865-4178-8af0-41d82df95d71´downstream_cells_map€²upstream_cells_map�ªkeyconcept�Ù$f1f7407d-86a1-4f24-b78a-61a411d1f371„´precedence_heuristic §cell_idÙ$f1f7407d-86a1-4f24-b78a-61a411d1f371´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$5af3ff1b-1655-4dd9-a089-91544fc85a0e„´precedence_heuristic §cell_idÙ$5af3ff1b-1655-4dd9-a089-91544fc85a0e´downstream_cells_map‚¬iteration_em’Ù$fd233604-120a-4838-a660-d5021bccecd0Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413e©#438#bond�²upstream_cells_map�°HypertextLiteral�¸HypertextLiteral.content�«PlutoRunner�»PlutoRunner.Core.applicable�©eachindex�©@bindname�©em_result‘Ù$7a3c0ff7-0b32-4954-ae28-b644f4d966ef·HypertextLiteral.Result�¤join�Ù#PlutoRunner.PlutoRunner.create_bond�·HypertextLiteral.Bypass�¦Slider�´PlutoRunner.Base.get�Ù$8555aec9-4e80-49e7-8514-ef4a2236801b„´precedence_heuristic §cell_idÙ$8555aec9-4e80-49e7-8514-ef4a2236801b´downstream_cells_map�¡N”Ù$4ee377c2-a126-4c40-8053-517d40c5ef9dÙ$86c33a7c-135a-461f-a17e-b50bca418e13Ù$55a1c42b-20d8-47a3-aa00-7af905db537cÙ$7a3c0ff7-0b32-4954-ae28-b644f4d966ef²upstream_cells_map‚¡X‘Ù$0349720e-5de4-4b39-babd-c0881588f1de¤size�Ù$26c65092-d294-11ef-39cc-1953a725f285„´precedence_heuristic §cell_idÙ$26c65092-d294-11ef-39cc-1953a725f285´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$3948225e-90d8-4b78-ba9b-5f98e228285a„´precedence_heuristic §cell_idÙ$3948225e-90d8-4b78-ba9b-5f98e228285a´downstream_cells_map€²upstream_cells_map„°data_plot_kwargs‘Ù$dd1242db-fb20-4732-ac55-a3e021bbd2b7¡:�¡X‘Ù$0349720e-5de4-4b39-babd-c0881588f1de§scatter�Ù$95d47a10-f3f8-479b-afe0-21241104b758„´precedence_heuristic §cell_idÙ$95d47a10-f3f8-479b-afe0-21241104b758´downstream_cells_map€²upstream_cells_map�¬code_example�Ù$26c62ebe-d294-11ef-0cfb-ef186203e890„´precedence_heuristic §cell_idÙ$26c62ebe-d294-11ef-0cfb-ef186203e890´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$c4b23b39-e6e4-44ec-b204-0c7d7d5a4026„´precedence_heuristic §cell_idÙ$c4b23b39-e6e4-44ec-b204-0c7d7d5a4026´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c5b896-d294-11ef-1d8e-0feb99d2d45b„´precedence_heuristic §cell_idÙ$26c5b896-d294-11ef-1d8e-0feb99d2d45b´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c623f6-d294-11ef-13c0-19edd43592c0„´precedence_heuristic §cell_idÙ$26c623f6-d294-11ef-13c0-19edd43592c0´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$55570464-89c8-4d9b-b667-dfa64ac62294„´precedence_heuristic §cell_idÙ$55570464-89c8-4d9b-b667-dfa64ac62294´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c59b52-d294-11ef-1eba-d3f235f85eee„´precedence_heuristic §cell_idÙ$26c59b52-d294-11ef-1eba-d3f235f85eee´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$f17c9d8a-9291-4110-bcf4-c582d23f986b„´precedence_heuristic §cell_idÙ$f17c9d8a-9291-4110-bcf4-c582d23f986b´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$dd1242db-fb20-4732-ac55-a3e021bbd2b7„´precedence_heuristic §cell_idÙ$dd1242db-fb20-4732-ac55-a3e021bbd2b7´downstream_cells_map�°data_plot_kwargs”Ù$3948225e-90d8-4b78-ba9b-5f98e228285aÙ$cd7cf2d0-aff7-49dc-bb12-dc73c6433768Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413eÙ$489cbd24-1a69-4a00-a2e9-53c2c57cef65²upstream_cells_map€Ù$26c73cf0-d294-11ef-297b-354eb9c71f57„´precedence_heuristic §cell_idÙ$26c73cf0-d294-11ef-297b-354eb9c71f57´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$2d4adbf6-6de8-4e3a-ad6f-fa8bbfa5999e„´precedence_heuristic §cell_idÙ$2d4adbf6-6de8-4e3a-ad6f-fa8bbfa5999e´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c56fd8-d294-11ef-236d-81deef63f37c„´precedence_heuristic §cell_idÙ$26c56fd8-d294-11ef-236d-81deef63f37c´downstream_cells_map€²upstream_cells_map�¥title�Ù$666680b2-315a-4d95-8f7f-3ae50018e112„´precedence_heuristic §cell_idÙ$666680b2-315a-4d95-8f7f-3ae50018e112´downstream_cells_map�¡K“Ù$4ee377c2-a126-4c40-8053-517d40c5ef9dÙ$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2Ù$55a1c42b-20d8-47a3-aa00-7af905db537c²upstream_cells_map€Ù$0349720e-5de4-4b39-babd-c0881588f1de„´precedence_heuristic §cell_idÙ$0349720e-5de4-4b39-babd-c0881588f1de´downstream_cells_map�¡X™Ù$3948225e-90d8-4b78-ba9b-5f98e228285aÙ$8555aec9-4e80-49e7-8514-ef4a2236801bÙ$663ac0ef-0577-43af-8df5-15e046ef875cÙ$cd7cf2d0-aff7-49dc-bb12-dc73c6433768Ù$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2Ù$55a1c42b-20d8-47a3-aa00-7af905db537cÙ$fd233604-120a-4838-a660-d5021bccecd0Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413eÙ$7a3c0ff7-0b32-4954-ae28-b644f4d966ef²upstream_cells_map†¤conj�¦Matrix�¥Array�§adjoint�¬old_faithful‘Ù$cc547bfa-a130-4382-af47-73de56e4741b§Float64�Ù$cd7cf2d0-aff7-49dc-bb12-dc73c6433768„´precedence_heuristic §cell_idÙ$cd7cf2d0-aff7-49dc-bb12-dc73c6433768´downstream_cells_map€²upstream_cells_mapÞ¤mean�¡/�¡X‘Ù$0349720e-5de4-4b39-babd-c0881588f1de«Categorical�¬Random.seed!�«vfem_result‘Ù$4ee377c2-a126-4c40-8053-517d40c5ef9d¦Random‘Ù$c90176ea-918b-4643-a10f-cef277c5ea75¡+�©plot_lims‘Ù$c18b7c1b-8011-469b-ad92-7d50c23c46e3£sum�§nothing�§Float64�£vec�°data_plot_kwargs‘Ù$dd1242db-fb20-4732-ac55-a3e021bbd2b7¡:�§scatter�®iteration_vfem‘Ù$de0c41a3-6319-4ae3-8a1a-ae6935910fa3ºshow_vfem_synthetic_labels‘Ù$16d90f11-5933-4145-b219-19774eba25d6¦Matrix�®cluster_colors‘Ù$d208f60e-56ea-4767-bd18-f29a853b7536¥undef�¤size�¤rand�Ù$b4d965d1-91d8-43f8-84a5-b37ad5c6cafa„´precedence_heuristic §cell_idÙ$b4d965d1-91d8-43f8-84a5-b37ad5c6cafa´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$32f0bbb4-dfc7-431e-9a3d-80162439edac„´precedence_heuristic §cell_idÙ$32f0bbb4-dfc7-431e-9a3d-80162439edac´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c85a22-d294-11ef-3c8e-7b72a4313ced„´precedence_heuristic §cell_idÙ$26c85a22-d294-11ef-3c8e-7b72a4313ced´downstream_cells_map€²upstream_cells_mapƒ§@md_str�¨getindex�¤HTML�Ù$d208f60e-56ea-4767-bd18-f29a853b7536„´precedence_heuristic §cell_idÙ$d208f60e-56ea-4767-bd18-f29a853b7536´downstream_cells_map�®cluster_colors”Ù$cd7cf2d0-aff7-49dc-bb12-dc73c6433768Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413eÙ$489cbd24-1a69-4a00-a2e9-53c2c57cef65Ù$0e9e62ea-1b2f-4e80-b78b-2001ae46093f²upstream_cells_map�ªcolor_list�Ù$26c7696e-d294-11ef-25f2-dbc0946c0858„´precedence_heuristic §cell_idÙ$26c7696e-d294-11ef-25f2-dbc0946c0858´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$58bd0d43-743c-4745-b353-4a89b35e85ba„´precedence_heuristic§cell_idÙ$58bd0d43-743c-4745-b353-4a89b35e85ba´downstream_cells_mapƒ­Distributions�¥Plots�ªStatsPlots�²upstream_cells_map€Ù$b91bc3b6-b815-4942-b297-c0e2b4b99654„´precedence_heuristic §cell_idÙ$b91bc3b6-b815-4942-b297-c0e2b4b99654´downstream_cells_map€²upstream_cells_mapƒ­hide_solution�§@md_str�¨getindex�Ù$87d94630-c90b-4379-91bd-88641ee7b508„´precedence_heuristic §cell_idÙ$87d94630-c90b-4379-91bd-88641ee7b508´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$56bea391-b812-4fc4-8f27-fcb4cb984cf4„´precedence_heuristic §cell_idÙ$56bea391-b812-4fc4-8f27-fcb4cb984cf4´downstream_cells_map€²upstream_cells_map�©exercises�Ù$de0c41a3-6319-4ae3-8a1a-ae6935910fa3„´precedence_heuristic §cell_idÙ$de0c41a3-6319-4ae3-8a1a-ae6935910fa3´downstream_cells_map‚®iteration_vfem’Ù$663ac0ef-0577-43af-8df5-15e046ef875cÙ$cd7cf2d0-aff7-49dc-bb12-dc73c6433768©#440#bond�²upstream_cells_map�°HypertextLiteral�¸HypertextLiteral.content�«PlutoRunner�¡-�®max_iterations‘Ù$4e0c025d-fa39-462d-8e7d-e66d220e9595»PlutoRunner.Core.applicable�©@bindname�·HypertextLiteral.Result�¡:�Ù#PlutoRunner.PlutoRunner.create_bond�·HypertextLiteral.Bypass�¦Slider�´PlutoRunner.Base.get�Ù$a663d6d1-2d73-40c6-8a4c-9e41df74bc84„´precedence_heuristic §cell_idÙ$a663d6d1-2d73-40c6-8a4c-9e41df74bc84´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c5a1f6-d294-11ef-3565-39d027843fbb„´precedence_heuristic §cell_idÙ$26c5a1f6-d294-11ef-3565-39d027843fbb´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$2f490e1f-e495-4f55-a3f8-60d6fd716d4e„´precedence_heuristic §cell_idÙ$2f490e1f-e495-4f55-a3f8-60d6fd716d4e´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c796c8-d294-11ef-25be-17dcd4a9d315„´precedence_heuristic §cell_idÙ$26c796c8-d294-11ef-25be-17dcd4a9d315´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2„´precedence_heuristic §cell_idÙ$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2´downstream_cells_map�µupdateMeanPrecisionPi‘Ù$4ee377c2-a126-4c40-8053-517d40c5ef9d²upstream_cells_mapŽ¡/�£inv�´sufficientStatistics‘Ù$86c33a7c-135a-461f-a17e-b50bca418e13¡X‘Ù$0349720e-5de4-4b39-babd-c0881588f1de¡-�§adjoint�¡K‘Ù$666680b2-315a-4d95-8f7f-3ae50018e112¡+�§Float64�¡:�¥Array�¤conj�¥undef�¡*�Ù$26c867d8-d294-11ef-2372-d75ed0bcc02d„´precedence_heuristic §cell_idÙ$26c867d8-d294-11ef-2372-d75ed0bcc02d´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c8160c-d294-11ef-2a74-6f7009a7c51e„´precedence_heuristic §cell_idÙ$26c8160c-d294-11ef-2a74-6f7009a7c51e´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c64174-d294-11ef-2bbc-ab1a84532311„´precedence_heuristic §cell_idÙ$26c64174-d294-11ef-2bbc-ab1a84532311´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$208ba1bb-a4bf-4b8c-93d2-0d6c6c8d16d4„´precedence_heuristic §cell_idÙ$208ba1bb-a4bf-4b8c-93d2-0d6c6c8d16d4´downstream_cells_map€²upstream_cells_mapƒ­hide_solution�§@md_str�¨getindex�Ù$26c6f63c-d294-11ef-1090-e9238dd6ad3f„´precedence_heuristic §cell_idÙ$26c6f63c-d294-11ef-1090-e9238dd6ad3f´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$aea77d69-9ecd-4be0-b6fd-c944d27d68df„´precedence_heuristic §cell_idÙ$aea77d69-9ecd-4be0-b6fd-c944d27d68df´downstream_cells_map€²upstream_cells_map‚§@md_str�¨getindex�Ù$26c82f16-d294-11ef-0fe1-07326b56282f„´precedence_heuristic §cell_idÙ$26c82f16-d294-11ef-0fe1-07326b56282f´downstream_cells_map€²upstream_cells_mapƒ§@md_str�¨getindex�¤HTML�Ù$87715fcd-c92e-4bfa-8b0a-15e469548f3d„´precedence_heuristic §cell_idÙ$87715fcd-c92e-4bfa-8b0a-15e469548f3d´downstream_cells_map€²upstream_cells_mapƒ§@md_str�¨getindex�ªkeyconcept�®last_save_timeËAÚ¹&–¹Þ«notebook_idÙ$1d8a00c4-d465-11f1-90f0-ed08555a41d9«in_temp_dir¨metadata�«frontmatter…¨language¥en-US¥titleÙ,Latent Variable Models and Variational Bayes«descriptionÙ^Introduction to latent variable models and variational inference via free energy minimization.¥image½https://imgur.com/oS96z4w.png¦author‘‚¤name¥BMLIP£url¸https://github.com/bmlip¥bonds€´cell_execution_orderÜjÙ$df171940-eb54-48e2-a2b8-1a8162cabf3eÙ$c90176ea-918b-4643-a10f-cef277c5ea75Ù$58bd0d43-743c-4745-b353-4a89b35e85baÙ$26c56fd8-d294-11ef-236d-81deef63f37cÙ$ce7d086b-ff20-4da1-a4e8-52b5b7dc9e2bÙ$26c58298-d294-11ef-2a53-2b42b48e0725Ù$2497529b-7703-4e3e-b9db-83f8dbf43fa8Ù$a663d6d1-2d73-40c6-8a4c-9e41df74bc84Ù$430a56c9-93ad-4513-b11c-2ac212109b12Ù$f8c8013a-3e87-4d01-a3ae-86b39cf1f002Ù$26c59b52-d294-11ef-1eba-d3f235f85eeeÙ$26c5a1f6-d294-11ef-3565-39d027843fbbÙ$26c5a93a-d294-11ef-23a1-cbcf0c370fc9Ù$26c5b896-d294-11ef-1d8e-0feb99d2d45bÙ$26c5c1ae-d294-11ef-15c6-13cae5bc0dc8Ù$dff0212b-f3e8-4592-8cd4-f52bcdb782fbÙ$26c5cfb4-d294-11ef-05bb-59d5e27cf37cÙ$c7351bf1-447e-475b-8965-d259c01bfd57Ù$3deadfd0-9fbb-476a-a7de-5dd694e55a65Ù$26c5d734-d294-11ef-20a3-afd2c3324323Ù$26c5f8d6-d294-11ef-3bcd-4d5e0391698dÙ$26c623f6-d294-11ef-13c0-19edd43592c0Ù$26c62ebe-d294-11ef-0cfb-ef186203e890Ù$26c6347c-d294-11ef-056f-7b78a9e22272Ù$26c64174-d294-11ef-2bbc-ab1a84532311Ù$26c65092-d294-11ef-39cc-1953a725f285Ù$f1f7407d-86a1-4f24-b78a-61a411d1f371Ù$26c67f04-d294-11ef-03a4-838ae255689dÙ$26c6e002-d294-11ef-15a4-33e30d0d76ecÙ$ae7ed1fc-fc36-4327-be55-a142477ca0adÙ$b4d965d1-91d8-43f8-84a5-b37ad5c6cafaÙ$18f5d694-8869-4265-98ac-9ef7ff451eafÙ$c4b23b39-e6e4-44ec-b204-0c7d7d5a4026Ù$670f83cb-66d6-40ab-9c42-50e022a9bd4cÙ$baec0494-9557-49d1-b4d8-a8030d3281b7Ù$87715fcd-c92e-4bfa-8b0a-15e469548f3dÙ$40ce0abb-a086-4977-9131-10f60ab44152Ù$26c6f63c-d294-11ef-1090-e9238dd6ad3fÙ$aea77d69-9ecd-4be0-b6fd-c944d27d68dfÙ$3654551d-5d08-4bb0-8a0d-c7d42225bc69Ù$edb179df-5cff-4e7b-8645-6da4818dceeeÙ$26c704f6-d294-11ef-1b3d-d52f0fb1c81dÙ$26c728f0-d294-11ef-0c01-6143abe8c3f0Ù$06512595-bdb7-4adf-88ae-62af20210891Ù$26c73cf0-d294-11ef-297b-354eb9c71f57Ù$3e897a59-e7b5-492c-8a8a-724248513a72Ù$93e7c7d5-a940-4764-8784-07af2f056e49Ù$26c74c9a-d294-11ef-2d31-67bd57d56d7cÙ$26c75b5e-d294-11ef-173e-b3f46a1df536Ù$95d47a10-f3f8-479b-afe0-21241104b758Ù$26c7696e-d294-11ef-25f2-dbc0946c0858Ù$26c796c8-d294-11ef-25be-17dcd4a9d315Ù$16d90f11-5933-4145-b219-19774eba25d6Ù$8b887c4a-273c-40fe-83e9-5c79ac6946f8Ù$666680b2-315a-4d95-8f7f-3ae50018e112Ù$4e0c025d-fa39-462d-8e7d-e66d220e9595Ù$de0c41a3-6319-4ae3-8a1a-ae6935910fa3Ù$f42a1a65-20ce-452f-9974-bc8146943574Ù$26c7b428-d294-11ef-150a-bb37e37f4b5dÙ$b3bb7349-1965-4734-83ed-ba6fef0ccc41Ù$06170e31-e865-4178-8af0-41d82df95d71Ù$bbdca8c2-022f-42be-bcf7-80d86f7f269cÙ$26c8068a-d294-11ef-3983-a1be55128b3fÙ$60a50f12-063c-4247-9c9c-bb41d5dc9811Ù$4ff85bda-22bb-408d-a50a-461834b7c0ffÙ$56bea391-b812-4fc4-8f27-fcb4cb984cf4Ù$5a94e2a4-7134-462e-9dc5-56083769049fÙ$747a7e1e-b921-4882-b00a-1b00bef8433dÙ$2d4adbf6-6de8-4e3a-ad6f-fa8bbfa5999eÙ$208ba1bb-a4bf-4b8c-93d2-0d6c6c8d16d4Ù$2f490e1f-e495-4f55-a3f8-60d6fd716d4eÙ$b91bc3b6-b815-4942-b297-c0e2b4b99654Ù$26c8160c-d294-11ef-2a74-6f7009a7c51eÙ$26c82f16-d294-11ef-0fe1-07326b56282fÙ$26c85a22-d294-11ef-3c8e-7b72a4313cedÙ$62868f61-95c7-4e07-854f-a171aadc667bÙ$26c867d8-d294-11ef-2372-d75ed0bcc02dÙ$64819124-865e-48b8-a916-2ce08dba0accÙ$87d94630-c90b-4379-91bd-88641ee7b508Ù$26c8b682-d294-11ef-1331-2bcf8baec73fÙ$26c8c7fa-d294-11ef-0444-6555ecf5c721Ù$f17c9d8a-9291-4110-bcf4-c582d23f986bÙ$90fbe618-fc81-480b-b685-69cd97e5b8edÙ$32f0bbb4-dfc7-431e-9a3d-80162439edacÙ$26c9121e-d294-11ef-18e6-ed8105503adcÙ$c563de07-0036-4dc4-87ee-e8363e9b6b1bÙ$55570464-89c8-4d9b-b667-dfa64ac62294Ù$c18b7c1b-8011-469b-ad92-7d50c23c46e3Ù$d208f60e-56ea-4767-bd18-f29a853b7536Ù$0e9e62ea-1b2f-4e80-b78b-2001ae46093fÙ$dd1242db-fb20-4732-ac55-a3e021bbd2b7Ù$489cbd24-1a69-4a00-a2e9-53c2c57cef65Ù$cc547bfa-a130-4382-af47-73de56e4741bÙ$0349720e-5de4-4b39-babd-c0881588f1deÙ$3948225e-90d8-4b78-ba9b-5f98e228285aÙ$8555aec9-4e80-49e7-8514-ef4a2236801bÙ$86c33a7c-135a-461f-a17e-b50bca418e13Ù$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2Ù$55a1c42b-20d8-47a3-aa00-7af905db537cÙ$4ee377c2-a126-4c40-8053-517d40c5ef9dÙ$663ac0ef-0577-43af-8df5-15e046ef875cÙ$cd7cf2d0-aff7-49dc-bb12-dc73c6433768Ù$7a3c0ff7-0b32-4954-ae28-b644f4d966efÙ$5af3ff1b-1655-4dd9-a089-91544fc85a0eÙ$fd233604-120a-4838-a660-d5021bccecd0Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413e®process_status¥readyªcell_orderÜjÙ$26c56fd8-d294-11ef-236d-81deef63f37cÙ$ce7d086b-ff20-4da1-a4e8-52b5b7dc9e2bÙ$26c58298-d294-11ef-2a53-2b42b48e0725Ù$2497529b-7703-4e3e-b9db-83f8dbf43fa8Ù$a663d6d1-2d73-40c6-8a4c-9e41df74bc84Ù$3948225e-90d8-4b78-ba9b-5f98e228285aÙ$0349720e-5de4-4b39-babd-c0881588f1deÙ$8555aec9-4e80-49e7-8514-ef4a2236801bÙ$430a56c9-93ad-4513-b11c-2ac212109b12Ù$f8c8013a-3e87-4d01-a3ae-86b39cf1f002Ù$26c59b52-d294-11ef-1eba-d3f235f85eeeÙ$26c5a1f6-d294-11ef-3565-39d027843fbbÙ$26c5a93a-d294-11ef-23a1-cbcf0c370fc9Ù$26c5b896-d294-11ef-1d8e-0feb99d2d45bÙ$26c5c1ae-d294-11ef-15c6-13cae5bc0dc8Ù$dff0212b-f3e8-4592-8cd4-f52bcdb782fbÙ$26c5cfb4-d294-11ef-05bb-59d5e27cf37cÙ$c7351bf1-447e-475b-8965-d259c01bfd57Ù$3deadfd0-9fbb-476a-a7de-5dd694e55a65Ù$26c5d734-d294-11ef-20a3-afd2c3324323Ù$26c5f8d6-d294-11ef-3bcd-4d5e0391698dÙ$26c623f6-d294-11ef-13c0-19edd43592c0Ù$26c62ebe-d294-11ef-0cfb-ef186203e890Ù$26c6347c-d294-11ef-056f-7b78a9e22272Ù$26c64174-d294-11ef-2bbc-ab1a84532311Ù$26c65092-d294-11ef-39cc-1953a725f285Ù$f1f7407d-86a1-4f24-b78a-61a411d1f371Ù$26c67f04-d294-11ef-03a4-838ae255689dÙ$26c6e002-d294-11ef-15a4-33e30d0d76ecÙ$ae7ed1fc-fc36-4327-be55-a142477ca0adÙ$b4d965d1-91d8-43f8-84a5-b37ad5c6cafaÙ$18f5d694-8869-4265-98ac-9ef7ff451eafÙ$c4b23b39-e6e4-44ec-b204-0c7d7d5a4026Ù$670f83cb-66d6-40ab-9c42-50e022a9bd4cÙ$baec0494-9557-49d1-b4d8-a8030d3281b7Ù$87715fcd-c92e-4bfa-8b0a-15e469548f3dÙ$40ce0abb-a086-4977-9131-10f60ab44152Ù$26c6f63c-d294-11ef-1090-e9238dd6ad3fÙ$aea77d69-9ecd-4be0-b6fd-c944d27d68dfÙ$3654551d-5d08-4bb0-8a0d-c7d42225bc69Ù$edb179df-5cff-4e7b-8645-6da4818dceeeÙ$26c704f6-d294-11ef-1b3d-d52f0fb1c81dÙ$26c728f0-d294-11ef-0c01-6143abe8c3f0Ù$06512595-bdb7-4adf-88ae-62af20210891Ù$26c73cf0-d294-11ef-297b-354eb9c71f57Ù$3e897a59-e7b5-492c-8a8a-724248513a72Ù$93e7c7d5-a940-4764-8784-07af2f056e49Ù$26c74c9a-d294-11ef-2d31-67bd57d56d7cÙ$26c75b5e-d294-11ef-173e-b3f46a1df536Ù$95d47a10-f3f8-479b-afe0-21241104b758Ù$26c7696e-d294-11ef-25f2-dbc0946c0858Ù$de0c41a3-6319-4ae3-8a1a-ae6935910fa3Ù$663ac0ef-0577-43af-8df5-15e046ef875cÙ$26c796c8-d294-11ef-25be-17dcd4a9d315Ù$cd7cf2d0-aff7-49dc-bb12-dc73c6433768Ù$16d90f11-5933-4145-b219-19774eba25d6Ù$8b887c4a-273c-40fe-83e9-5c79ac6946f8Ù$666680b2-315a-4d95-8f7f-3ae50018e112Ù$4e0c025d-fa39-462d-8e7d-e66d220e9595Ù$4ee377c2-a126-4c40-8053-517d40c5ef9dÙ$86c33a7c-135a-461f-a17e-b50bca418e13Ù$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2Ù$55a1c42b-20d8-47a3-aa00-7af905db537cÙ$f42a1a65-20ce-452f-9974-bc8146943574Ù$26c7b428-d294-11ef-150a-bb37e37f4b5dÙ$b3bb7349-1965-4734-83ed-ba6fef0ccc41Ù$06170e31-e865-4178-8af0-41d82df95d71Ù$bbdca8c2-022f-42be-bcf7-80d86f7f269cÙ$26c8068a-d294-11ef-3983-a1be55128b3fÙ$60a50f12-063c-4247-9c9c-bb41d5dc9811Ù$4ff85bda-22bb-408d-a50a-461834b7c0ffÙ$56bea391-b812-4fc4-8f27-fcb4cb984cf4Ù$5a94e2a4-7134-462e-9dc5-56083769049fÙ$747a7e1e-b921-4882-b00a-1b00bef8433dÙ$2d4adbf6-6de8-4e3a-ad6f-fa8bbfa5999eÙ$208ba1bb-a4bf-4b8c-93d2-0d6c6c8d16d4Ù$2f490e1f-e495-4f55-a3f8-60d6fd716d4eÙ$b91bc3b6-b815-4942-b297-c0e2b4b99654Ù$26c8160c-d294-11ef-2a74-6f7009a7c51eÙ$26c82f16-d294-11ef-0fe1-07326b56282fÙ$26c85a22-d294-11ef-3c8e-7b72a4313cedÙ$62868f61-95c7-4e07-854f-a171aadc667bÙ$26c867d8-d294-11ef-2372-d75ed0bcc02dÙ$5af3ff1b-1655-4dd9-a089-91544fc85a0eÙ$fd233604-120a-4838-a660-d5021bccecd0Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413eÙ$64819124-865e-48b8-a916-2ce08dba0accÙ$87d94630-c90b-4379-91bd-88641ee7b508Ù$7a3c0ff7-0b32-4954-ae28-b644f4d966efÙ$26c8b682-d294-11ef-1331-2bcf8baec73fÙ$26c8c7fa-d294-11ef-0444-6555ecf5c721Ù$f17c9d8a-9291-4110-bcf4-c582d23f986bÙ$90fbe618-fc81-480b-b685-69cd97e5b8edÙ$32f0bbb4-dfc7-431e-9a3d-80162439edacÙ$26c9121e-d294-11ef-18e6-ed8105503adcÙ$c563de07-0036-4dc4-87ee-e8363e9b6b1bÙ$55570464-89c8-4d9b-b667-dfa64ac62294Ù$df171940-eb54-48e2-a2b8-1a8162cabf3eÙ$c90176ea-918b-4643-a10f-cef277c5ea75Ù$58bd0d43-743c-4745-b353-4a89b35e85baÙ$489cbd24-1a69-4a00-a2e9-53c2c57cef65Ù$c18b7c1b-8011-469b-ad92-7d50c23c46e3Ù$d208f60e-56ea-4767-bd18-f29a853b7536Ù$0e9e62ea-1b2f-4e80-b78b-2001ae46093fÙ$dd1242db-fb20-4732-ac55-a3e021bbd2b7Ù$cc547bfa-a130-4382-af47-73de56e4741b«cell_inputsÞjÙ$26c74c9a-d294-11ef-2d31-67bd57d56d7c„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c74c9a-d294-11ef-2d31-67bd57d56d7c«code_foldedäcodeÚmd""" ##### Update Equations For this specific case (GMM model with factorization constraints), Bishop shows that the equations for the [optimal solutions (Eq. B-10.9)](#optimal-solutions) are analytically solvable, leading to the following variational update equations (for ``k=1,\ldots, K`` ): ```math \begin{align*} \alpha_k &= \alpha_0 + N_k \tag{B-10.58} \\ \beta_k &= \beta_0 + N_k \tag{B-10.60} \\ m_k &= \frac{1}{\beta_k} \left( \beta_0 m_0 + N_k \bar{x}_k \right) \tag{B-10.61} \\ W_k^{-1} &= W_0^{-1} + N_k S_k + \frac{\beta_0 N_k}{\beta_0 + N_k}\left( \bar{x}_k - m_0\right) \left( \bar{x}_k - m_0\right)^T \tag{B-10.62} \\ \nu_k &= \nu_0 + N_k \tag{B-10.63} \end{align*} ``` where we used ```math \begin{align*} \log \rho_{nk} &= \mathbb{E}\left[ \log \pi_k\right] + \frac{1}{2}\mathbb{E}\left[ \log | \Lambda_k | \right] - \frac{D}{2} \log(2\pi) \\ & \qquad - \frac{1}{2}\mathbb{E}\left[(x_k - \mu_k)^T \Lambda_k(x_k - \mu_k) \right] \tag{B-10.46} \\ r_{nk} &= \frac{\rho_{nk}}{\sum_{j=1}^K \rho_{nj}} \tag{B-10.49} \\ N_k &= \sum_{n=1}^N r_{nk} \tag{B-10.51} \\ \bar{x}_k &= \frac{1}{N_k} \sum_{n=1}^N r_{nk} x_n \tag{B-10.52} \\ S_k &= \frac{1}{N_k} \sum_{n=1}^N r_{nk} \left( x_n - \bar{x}_k\right) \left( x_n - \bar{x}_k\right)^T \tag{B-10.53} \end{align*} ``` """Ù$430a56c9-93ad-4513-b11c-2ac212109b12„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$430a56c9-93ad-4513-b11c-2ac212109b12«code_foldedäcodeÙtmd""" ##### Solution See [later in this lecture](#Challenge-Revisited:-Modeling-of-the-Old-Faithful-Data-Set). """Ù$26c6347c-d294-11ef-056f-7b78a9e22272„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c6347c-d294-11ef-056f-7b78a9e22272«code_foldedäcodeÙåmd""" However, for the Gaussian mixture model (same log-likelihood function with ``z_{nk}`` replacing ``y_{nk}``), the class labels ``\{z_{nk}\}`` are *unobserved* and they need to be estimated alongside with the parameters. """Ù$26c8c7fa-d294-11ef-0444-6555ecf5c721„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c8c7fa-d294-11ef-0444-6555ecf5c721«code_foldedäcodeÚjmd""" ## The Local Free Energy in a Factor Graph Consider an edge ``x_j`` in a Forney-style factor graph for a generative model ``p(x) = p(x_1,x_2,\ldots,x_N)``. Assume that the graph structure (factorization) is specified by ```math p(x) = \prod_{a=1}^M p_a(x_a) ``` where ``a`` is a set of indices. Also, we assume a mean-field approximation for the posterior: ```math q(x) = \prod_{i=1}^N q_i(x_i) ``` and consequently a corresponding free energy functional ```math \begin{align*} F[q] &= \sum_x q(x) \log \frac{q(x)}{p(x)} \\ &= \sum_i \sum_{x_i} \left(\prod_{i=1}^N q_i(x_i)\right) \log \frac{\prod_{i=1}^N q_i(x_i)}{\prod_{a=1}^M p_a(x_a)} \end{align*} ``` With these assumptions, it can be shown that the FE evaluates to (exercise) ```math F[q] = \sum_{a=1}^M \underbrace{\sum_{x_a} \left( \prod_{j\in N(a)} q_j(x_j)\cdot \left(-\log p_a(x_a)\right) \right) }_{\text{node energy }U[p_a]} - \sum_{i=1}^N \underbrace{\sum_{x_i} q_i(x_i) \log \frac{1}{q_i(x_i)}}_{\text{edge entropy }H[q_i]} ``` In words, the FE decomposes into a sum of (expected) energies for the nodes minus the entropies on the edges. """Ù$2497529b-7703-4e3e-b9db-83f8dbf43fa8„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$2497529b-7703-4e3e-b9db-83f8dbf43fa8«code_foldedäcodeÙcchallenge_statement("Density Modeling for the Old Faithful Data Set", color="red", header_level=1) Ù$5a94e2a4-7134-462e-9dc5-56083769049f„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$5a94e2a4-7134-462e-9dc5-56083769049f«code_foldedäcodeÚ(md""" #### Entropy and The Free Energy Functional (*) The Free energy functional ``\mathrm{F}[q] = -\sum_z q(z) \log p(x,z) - \sum_z q(z) \log \frac{1}{q(z)}`` decomposes into "Energy minus Entropy". So apparently the entropy of the posterior ``q(z)`` is maximized. This entropy maximization may seem puzzling at first because inference should intuitively lead to *more* informed posteriors, i.e., posterior distributions whose entropy is smaller than the entropy of the prior. Explain why entropy maximization is still a reasonable objective. """Ù$26c5c1ae-d294-11ef-15c6-13cae5bc0dc8„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c5c1ae-d294-11ef-15c6-13cae5bc0dc8«code_foldedäcodeÚZmd""" We consider the same model as we did in the [generative classification lesson](https://bmlip.github.io/course/lectures/Generative%20Classification.html#Model-Specification): the data for each class is distributed as a Gaussian: ```math \begin{align*} p(x_n | z_{nk}=1) &= \mathcal{N}\left( x_n | \mu_k, \Sigma_k\right)\\ p(z_{nk}=1) &= \pi_k \end{align*} ``` which can be summarized with the selection variables ``z_{nk}`` as ```math \begin{align*} p(x_n,z_n) &= \prod_{k=1}^K (\underbrace{\pi_k \cdot \mathcal{N}\left( x_n | \mu_k, \Sigma_k\right) }_{p(x_n,z_{nk}=1)})^{z_{nk}} \end{align*} ``` *Again*, this is the same model as we defined for the generative classification model: A Gaussian-Categorical model but now with unobserved classes. This model (with **unobserved class labels**) is known as a **Gaussian Mixture Model** (GMM). """Ù$dff0212b-f3e8-4592-8cd4-f52bcdb782fb„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$dff0212b-f3e8-4592-8cd4-f52bcdb782fb«code_foldedäcodeÚ�keyconcept("", md""" A **Gaussian Mixture Model** has the same form as the Gaussian-Categorical model, ```math \begin{align} p(x_n | z_{nk}=1) &= \mathcal{N}\left( x_n | \mu_k, \Sigma_k\right)\\ p(z_{nk}=1) &= \pi_k \end{align} ``` but now the class labels ``z_{nk}`` are *unobserved* in the data set. A model with unobserved ("latent") variables is referred to as a **latent variable model**. """)Ù$26c704f6-d294-11ef-1b3d-d52f0fb1c81d„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c704f6-d294-11ef-1b3d-d52f0fb1c81d«code_foldedäcodeÚ md""" ## Visualization of Constrained VFEM The following image by [David Blei](https://www.cs.columbia.edu/~blei/) illustrates the Variational Bayes approach: ![](https://github.com/bmlip/course/blob/v2/assets/figures/blei-variational-inference.png?raw=true) """Ù$c90176ea-918b-4643-a10f-cef277c5ea75„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$c90176ea-918b-4643-a10f-cef277c5ea75«code_folded¤codeÙ5using LinearAlgebra, PDMats, SpecialFunctions, RandomÙ$93e7c7d5-a940-4764-8784-07af2f056e49„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$93e7c7d5-a940-4764-8784-07af2f056e49«code_foldedäcodeÚFmd""" ##### Inference by Constrained VFEM Assume that we have observed ``D = \left\{x_1, x_2, \ldots, x_N\right\}`` and are interested to infer a posterior distribution for the parameters ``\pi``, ``\mu`` and ``\Lambda``. We will approximate Bayesian inference by VFE minimization. For the specified model, this leads to VFE minimization with respect to the hyperparameters, i.e., we need to minimize the function ```math F(\alpha_0, m_0, \beta_0, W_0, \nu_0) \,. ``` In general, this function can be optimized in various ways, e.g., by a gradient-descent procedure. It turns out that adding the following **factorization constraints** on the variational posterior makes the VFEM task analytically tractible: ```math \begin{equation} q(z,\pi,\mu,\Lambda) = q(z) \cdot q(\pi,\mu,\Lambda) \,. \tag{B-10.42} \end{equation} ``` """Ù$7a3c0ff7-0b32-4954-ae28-b644f4d966ef„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$7a3c0ff7-0b32-4954-ae28-b644f4d966ef«code_foldedäcodeÚ§begin # Initialize the GMM. We assume 2 clusters. clusters = [MvNormal([4.;60.], [.5 0;0 10^2]); MvNormal([2.;80.], [.5 0;0 10^2])]; Ï€_hat = [0.5; 0.5] # Mixing weights γ = fill!(Matrix{Float64}(undef,2,N), NaN) # Responsibilities (row per cluster) # Define functions for updating the parameters and responsibilities function updateResponsibilities!(γ, X, clusters, Ï€_hat) # Expectation step: update γ norm = [pdf(clusters[1], X) pdf(clusters[2], X)] * Ï€_hat γ[1,:] = (Ï€_hat[1] * pdf(clusters[1],X) ./ norm)' γ[2,:] = 1 .- γ[1,:] end function updateParameters!(clusters, Ï€_hat, X, γ) # Maximization step: update Ï€_hat and clusters using ML estimation m = sum(γ, dims=2) # [:] to update contents of Ï€_hat, not create a new local variable Ï€_hat[:] = m / N μ_hat = (X * γ') ./ m' for k=1:2 Z = (X .- μ_hat[:,k]) Σ_k = Symmetric(((Z .* (γ[k,:])') * Z') / m[k]) clusters[k] = MvNormal(μ_hat[:,k], convert(Matrix, Σ_k)) end end rec() = deepcopy((; clusters, γ)) em_result = [ (0, :initial) => rec(), ] # Execute the algorithm: iteratively update parameters and responsibilities for i in 1:10 updateResponsibilities!(γ, X, clusters, Ï€_hat) push!(em_result, (i, :E) => rec()) updateParameters!(clusters, Ï€_hat, X, γ) push!(em_result, (i, :M) => rec()) end Text("em_result") endÙ$26c5a93a-d294-11ef-23a1-cbcf0c370fc9„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c5a93a-d294-11ef-23a1-cbcf0c370fc9«code_foldedäcodeÙ¸md""" ## The Gaussian Mixture Model The spread of the data in the Old Faithful data set looks like it could be modeled by two Gaussians. Let's develop a model for this data set. """Ù$3e897a59-e7b5-492c-8a8a-724248513a72„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$3e897a59-e7b5-492c-8a8a-724248513a72«code_foldedäcodeÚÉmd""" ##### Model Specification We consider a Gaussian Mixture Model, specified by ```math \begin{align*} p(x,z|\theta) &= p(x|z,\mu,\Lambda)p(z|\pi) \\ &= \prod_{n=1}^N \prod_{k=1}^K \mathcal{N}\left( x_n | \mu_k, \Lambda_k^{-1}\right)^{z_{nk}} \cdot \prod_{n=1}^N \prod_{k=1}^K \pi_k^{z_{nk}} \\ &= \prod_{n=1}^N \prod_{k=1}^K \left(\pi_k \cdot \mathcal{N}\left( x_n | \mu_k, \Lambda_k^{-1}\right)\right)^{z_{nk}} \tag{B-10.37,38} \end{align*} ``` Let us introduce some priors for the parameters ``\pi``, ``\mu``, and ``\Lambda``. We factorize the prior and choose conjugate distributions by ```math p(\pi,\mu,\Lambda) = p(\pi) p(\mu|\Lambda) p(\Lambda) ``` with ```math \begin{align} p(\pi) &= \mathrm{Dir}(\pi|\alpha_0) = C(\alpha_0) \prod_k \pi_k^{\alpha_0-1} \tag{B-10.39} \\ p(\mu|\Lambda) &= \prod_k \mathcal{N}\left(\mu_k | m_0, \left( \beta_0 \Lambda_k\right)^{-1} \right) \tag{B-10.40} \\ p(\Lambda) &= \prod_k \mathcal{W}\left( \Lambda_k | W_0, \nu_0 \right) \tag{B-10.40} \end{align} ``` where ``\mathcal{W}\left( \cdot \right)`` is a [Wishart distribution](https://en.wikipedia.org/wiki/Wishart_distribution) (i.e., a multi-dimensional Gamma distribution). The full generative model is now specified by ```math p(x,z,\pi,\mu,\Lambda) = \underbrace{p(x|z,\mu,\Lambda) p(z|\pi)}_{\text{B-10.37-38}} \underbrace{p(\pi) p(\mu|\Lambda) p(\Lambda)}_{\text{B-10.39-40}} \tag{B-10.41} ``` with hyperparameters ``\{ \alpha_0, m_0, \beta_0, W_0, \nu_0\}``. """Ù$26c8068a-d294-11ef-3983-a1be55128b3f„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c8068a-d294-11ef-3983-a1be55128b3f«code_foldedäcodeÚ�md""" ## Variational Inference in Practice For most realistic models of complex real-world problems, Bayes rule is not tractable in closed form. As a result, the use of approximate variational Bayesian inference has seen rapid growth in practical applications. Toolboxes such as [RxInfer](http://rxinfer.com) enable users to define sophisticated probabilistic models and automate the inference process via constrained VFE minimization. Remarkably, specifying even complex models typically requires no more than a single page of code. In contrast to traditional algorithm design, where solving a problem might require implementing a custom solution in, say, ``40`` pages of code, automated inference in a probabilistic model offers a radically more efficient and modular approach. This shift has the potential to fundamentally change how we design and deploy information processing systems in the future. """Ù$ae7ed1fc-fc36-4327-be55-a142477ca0ad„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$ae7ed1fc-fc36-4327-be55-a142477ca0ad«code_foldedäcodeÚhide_proof( md""" ```math \begin{align*} F[q] &= \underbrace{ \int q(z) \log \frac{q(z)}{p(z)} \mathrm{d}z }_{\text{complexity}} - \underbrace{\int q(z) \log p(x|z) \mathrm{d}z}_{\text{accuracy}} \\ &= \int q(z) \log \frac{q(z)}{ p(x|z) p(z) }\mathrm{d}z \\ &= \int q(z) \log \frac{q(z)}{ p(z|x) p(x)}\mathrm{d}z \quad \text{( since } p(x|z) p(z) = p(z|x) p(x)\text{ )} \\ &= \underbrace{\int q(z) \log \frac{q(z)}{p(z|x)}\mathrm{d}z}_{\text{inference bound}\geq 0} - \underbrace{\log p(x)}_{\text{log-evidence}} \end{align*} ``` """)Ù$86c33a7c-135a-461f-a17e-b50bca418e13„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$86c33a7c-135a-461f-a17e-b50bca418e13«code_foldedäcodeÚfunction sufficientStatistics(X,r,k::Int) #function to compute sufficient statistics N_k = sum(r[k,:]) hat_x_k = sum([r[k,n]*X[:,n] for n in 1:N]) ./ N_k S_k = sum([r[k,n]*(X[:,n]-hat_x_k)*(X[:,n]-hat_x_k)' for n in 1:N]) ./ N_k return N_k, hat_x_k, S_k endÙ$26c8b682-d294-11ef-1331-2bcf8baec73f„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c8b682-d294-11ef-1331-2bcf8baec73f«code_foldedäcodeÚUmd""" ## Message Passing for Free Energy Minimization The Sum-Product (SP) update rule implements perfect Bayesian inference. Sometimes, the SP update rule is not analytically solvable. Fortunately, for many well-known Bayesian approximation methods, a message passing update rule can be created, e.g. [Variational Message Passing](https://en.wikipedia.org/wiki/Variational_message_passing) (VMP) for variational inference. In general, all of these message passing algorithms can be interpreted as minimization of a constrained free energy (e.g., see [Senoz et al. (2021)](https://research.tue.nl/nl/publications/variational-message-passing-and-local-constraint-manipulation-in-), and hence these message passing schemes comply with [Caticha's Method of Maximum Relative Entropy](https://arxiv.org/abs/1011.0723), which, as discussed in the [variational Bayes lesson](https://bmlip.github.io/course/lectures/Latent%20Variable%20Models%20and%20VB.html) is the proper way for updating beliefs. Different message passing updates rules can be combined to get a hybrid inference method in one model. """Ù$f42a1a65-20ce-452f-9974-bc8146943574„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$f42a1a65-20ce-452f-9974-bc8146943574«code_foldedäcodeÙ8md""" # Theoretical Underpinning of VFE Minimization """Ù$edb179df-5cff-4e7b-8645-6da4818dceee„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$edb179df-5cff-4e7b-8645-6da4818dceee«code_foldedäcodeÚ—md""" ##### 3. Other constraints, e.g., the Expectation-Maximization (EM) algorithm Beyond form and factorization constraints on ``q(z)``, several ad hoc algorithms have been developed to simplify VFE minimization for particular models. In particular, the [Expectation-Maximization (EM) algorithm](https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm) is a famous special case of constrained VFE minimization. The EM algorithm places some constraints on both the posterior ``q(z)`` and the prior ``p(z)`` (see the [OPTIONAL SLIDE](#EM-Algorithm) for more info) that essentially reduce VFE minimization to maximum likelihood estimation. """Ù$06512595-bdb7-4adf-88ae-62af20210891„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$06512595-bdb7-4adf-88ae-62af20210891«code_foldedäcodeÙKchallenge_solution("Modeling of the Old Faithful Data Set"; header_level=1)Ù$3deadfd0-9fbb-476a-a7de-5dd694e55a65„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$3deadfd0-9fbb-476a-a7de-5dd694e55a65«code_foldedäcodeÚemd""" Eq. B-9.12 reveals the link to the name Gaussian *mixture model*. The priors ``\pi_k`` for the ``k``-th class are also called **mixture coefficients**. Be aware that Eq. B-9.12 is not the generative model for the GMM! The generative model is the joint distribution ``p(x,z,\pi,\mu,\Sigma)`` over all variables, including the latent variables. """Ù$3654551d-5d08-4bb0-8a0d-c7d42225bc69„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$3654551d-5d08-4bb0-8a0d-c7d42225bc69«code_foldedäcodeÚÎmd""" ##### 2. Factorization constraints In addition to form constraints, it is also common to constrain the posterior ``q(z)`` by a specific factorization. For instance, in the *mean-field factorization* constraints, we constrain the variational posterior to factorize fully into a set of independent factors, i.e., ```math q(z) = \prod_{j=1}^m q_j(z_j)\,, \tag{B-10.5} ``` Variational inference with mean-field factorization has been worked out in detail as the **Coordinate Ascent Variational Inference** (CAVI) algorithm. See the [Optional Slide on CAVI](#CAVI) for details. Mean-field factorization is just an example of various _factorization constraints_ that have been successfully applied to VFEM. """Ù$670f83cb-66d6-40ab-9c42-50e022a9bd4c„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$670f83cb-66d6-40ab-9c42-50e022a9bd4c«code_foldedäcodeÙŽmd""" In other words, global minimization of ``F[q]`` recovers Bayes rule _exactly_, namely, both the posterior and evidence are revealed. """Ù$c563de07-0036-4dc4-87ee-e8363e9b6b1b„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$c563de07-0036-4dc4-87ee-e8363e9b6b1b«code_foldedäcodeÙ¨navigate_prev_next( "https://bmlip.github.io/course/lectures/Discriminative%20Classification.html", "https://bmlip.github.io/course/lectures/Dynamic%20Models.html", )Ù$90fbe618-fc81-480b-b685-69cd97e5b8ed„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$90fbe618-fc81-480b-b685-69cd97e5b8ed«code_foldedäcodeÙ‘Resource("https://github.com/bmlip/course/blob/v2/assets/figures/VMP-two-nodes.png?raw=true", :style => "background: white; border-radius: 1em;")Ù$f8c8013a-3e87-4d01-a3ae-86b39cf1f002„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$f8c8013a-3e87-4d01-a3ae-86b39cf1f002«code_foldedäcodeÙ&md""" # The Gaussian Mixture Model """Ù$4e0c025d-fa39-462d-8e7d-e66d220e9595„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$4e0c025d-fa39-462d-8e7d-e66d220e9595«code_folded¤codeµmax_iterations = 120;Ù$ce7d086b-ff20-4da1-a4e8-52b5b7dc9e2b„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$ce7d086b-ff20-4da1-a4e8-52b5b7dc9e2b«code_foldedäcode¹PlutoUI.TableOfContents()Ù$26c58298-d294-11ef-2a53-2b42b48e0725„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c58298-d294-11ef-2a53-2b42b48e0725«code_foldedäcodeÚ{md""" ## Preliminaries ##### Goal * Introduction to latent variable models and variational inference by Free energy minimization ##### Materials * Mandatory * These lecture notes * Optional * Bishop (2016), [PRML book](https://www.microsoft.com/en-us/research/wp-content/uploads/2006/01/Bishop-Pattern-Recognition-and-Machine-Learning-2006.pdf), pp. 461-486 (sections 10.1, 10.2 and 10.3) * Ariel Caticha (2010), [Entropic Inference](https://arxiv.org/abs/1011.0723) * tutorial on entropic inference, which is a generalization to Bayes rule and provides a foundation for variational inference. * references $(HTML("")) * Blei et al. (2017), [Variational Inference: A Review for Statisticians](https://doi.org/10.1080/01621459.2017.1285773) * Lanczos (1961), [The variational principles of mechanics](https://www.amazon.com/Variational-Principles-Mechanics-Dover-Physics/dp/0486650677) * Senoz et al. (2021), [Variational Message Passing and Local Constraint Manipulation in Factor Graphs](https://research.tue.nl/nl/publications/variational-message-passing-and-local-constraint-manipulation-in-) * Dauwels (2007), [On variational message passing on factor graphs](https://github.com/bmlip/course/blob/main/assets/files/Dauwels-2007-on-variational-message-passing-on-factor-graphs.pdf) * Shore and Johnson (1980), [Axiomatic Derivation of the Principle of Maximum Entropy and the Principle of Minimum Cross-Entropy](https://github.com/bmlip/course/blob/main/assets/files/ShoreJohnson-1980-Axiomatic-Derivation-of-the-Principle-of-Maximum-Entropy.pdf) """Ù$26c728f0-d294-11ef-0c01-6143abe8c3f0„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c728f0-d294-11ef-0c01-6143abe8c3f0«code_foldedäcodeÚìmd""" Figure caption: _The Bayesian posterior_ ``p(z|x)`` _(upper-right) is the posterior that would be obtained through executing Bayes rule, but unfortunately, Bayes rule is not tractable here. Instead, we propose a variational posterior_ ``q(z;\nu)``, _parameterized by_ ``\nu``. _The area inside the ellipsis represents the region reachable by choosing values for the parameter_ ``\nu``. _Note that_ ``p(z|x)`` _is not reachable. We start the FE minimization process by choosing an initial value_ ``\nu^{\text{init}}``, _which corresponds to the posterior_ ``q(z;\nu^{\text{init}})``, _as indicated in the figure. VFE minimization yields a final value_ ``\nu^{*}`` _that minimizes the KL divergence between_ ``q(z;\nu)`` _and_ ``p(z|x)``. """Ù$df171940-eb54-48e2-a2b8-1a8162cabf3e„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$df171940-eb54-48e2-a2b8-1a8162cabf3e«code_folded¤code¸using BmlipTeachingToolsÙ$489cbd24-1a69-4a00-a2e9-53c2c57cef65„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$489cbd24-1a69-4a00-a2e9-53c2c57cef65«code_folded¤codeÚªfunction plotGMM(X::Matrix, clusters::Vector, γ::Matrix; kwargs...) # Plot data set and (fitted) mixture model consisting of two Gaussian distributions # X contains a 2-d data set (every column holds a data point) # clusters holds the 2 Gaussian elements of the mixture model # γ contains p(cluster|X), and should contain NaN elements if not yet known # Plot contours of the element distributions K = length(clusters) result = plot(; plot_lims...) for k=1:K X1 = Matrix{Float64}(undef,50,50) X2 = Matrix{Float64}(undef,50,50) d = Matrix{Float64}(undef,50,50) # Create bounding box for thse contour plot lims = [-2*sqrt(cov(clusters[k])[1,1]) 2*sqrt(cov(clusters[k])[1,1]); -2*sqrt(cov(clusters[k])[2,2]) 2*sqrt(cov(clusters[k])[2,2])] + repeat(mean(clusters[k]), 1, 2) X1 = LinRange(lims[1,1], lims[1,2], 50) X2 = LinRange(lims[2,1], lims[2,2], 50) alpha = sum(γ[k,:])/sum(γ) covellipse!(clusters[k].μ, clusters[k].Σ; label="", n_std=2, alpha=max(0.0, alpha), color=cluster_colors[k]) end # Plot data points scatter!( X[1,:], X[2,:]; label="observations", data_plot_kwargs..., color=get_color.(eachcol(γ)), kwargs... ) return result endÙ$26c7b428-d294-11ef-150a-bb37e37f4b5d„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c7b428-d294-11ef-150a-bb37e37f4b5d«code_foldedäcodeÚ$md""" ## Observations as Variational Constraints We derived variational inference by substituting a variational posterior ``q(z)`` for the Bayesian posterior ``p(z|x)`` in the CA decomposition of (negative log) Bayesian evidence for a model. This led to a straightforward derivation of the VFE functional, but revealed nothing about the foundations of variational inference. Is variational inference any good? To approach this question, let us first recognize that, in the context of a given model ``p(x,z)``, new observations ``x`` can generally be formulated as a constraint on a posterior distribution ``q``. For instance, observing a new data point ``x_1 = 5`` can be formalized as a constraint ``q(x_1) = \delta(x_1 - 5)``, where ``\delta(\cdot)`` is the Dirac delta function. Viewing observations as delta-function constraints enables us to interpret them as a specific instance of variational constraints, on par with form and factorization (and other) constraints, all of which shape the variational posterior in constrained VFE minimization. """Ù$8b887c4a-273c-40fe-83e9-5c79ac6946f8„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$8b887c4a-273c-40fe-83e9-5c79ac6946f8«code_foldedäcodeÙ—md""" ### Implementation _Reading this lecture online? Click **"View code"** in the top right to read the implementation of this visualisation._ """Ù$26c5f8d6-d294-11ef-3bcd-4d5e0391698d„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c5f8d6-d294-11ef-3bcd-4d5e0391698d«code_foldedäcodeÚlmd""" ## Latent Variable Models A GMM contains both **observed** variables ``\{x_n\}``, and **unobserved** variables, namely unobserved (synonym: latent, hidden) parameters ``\theta= \{\pi_k,\mu_k, \Sigma_k\}`` and unobserved class labels ``\{z_{nk}\}``. From a Bayesian viewpoint, both the class labels ``\{z_{nk}\}`` and the parameters ``\theta`` are just unobserved variables for which we can set a prior and compute a posterior by Bayes rule. Note that ``z_{nk}`` carries a subscript ``n``, indicating that its value depends not only on the class index ``k``, but also on the specific observation ``n``. This contrasts with global model parameters ``\theta``, which are shared across all data points. Observation-specific latent variables can be a powerful modeling tool for capturing additional structure in the data, particularly information about the hidden causes of individual observations. In the case of the Gaussian Mixture Model (GMM), the latent variables ``z_{nk}`` represent unobserved class memberships, specifying which component generated each data point. Models that incorporate unobserved variables, often specific to each observation, are broadly known as **Latent Variable Models** (LVMs). These latent variables help explain the hidden structure or generative process underlying the observed data. By adding model structure through (equations among) observation-dependent latent variables, we can often build more accurate models for very complex processes. Unfortunately, adding structure through observation-dependent latent variables in models is also often accompanied by a more complex inference task. """Ù$663ac0ef-0577-43af-8df5-15e046ef875c„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$663ac0ef-0577-43af-8df5-15e046ef875c«code_foldedäcodeÙõlet i = iteration_vfem + 1 plotGMM( X, vfem_result.clusters_vb[:,i], vfem_result.R[:,:,i]; title=i == 1 ? "Initial situation" : "After $(iteration_vfem) iteration$(iteration_vfem > 1 ? "s" : "")", legend=nothing, size=(600,300), ) endÙ$baec0494-9557-49d1-b4d8-a8030d3281b7„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$baec0494-9557-49d1-b4d8-a8030d3281b7«code_foldedäcodeÚzmd""" ## Approximate Bayesian Inference by VFE Minimization In practice, even if we cannot attain the global minimum of VFE, we can still use a local minimum, ```math \hat{q}(z) \approx \arg\min_q F[q] ``` to accomplish **approximate Bayesian inference** by: ```math \begin{align*} \hat{q}(z) &\approx p(z|x) \\ F[\hat{q}] &\approx -\log p(x) \end{align*} ``` Executing inference by minimizing the VFE functional is called **Variational Bayes** (VB) or **Variational Inference** (VI). (As an aside), note that Bishop introduces in Eq. B-10.3 an *Evidence Lower BOund* (in modern machine learning literature abbreviated as **ELBO**) ``\mathcal{L}[q]`` that equals the *negative* VFE (``\mathcal{L}[q]=-F[q]``). In this class, we prefer to discuss inference in terms of minimizing VFE rather than maximizing ELBO, but note that these two concepts are equivalent. (We prefer the Free Energy formulation because of the terminology in the Free Energy Principle, which we introduce in the [Intelligent Agents and active Inference lesson](https://bmlip.github.io/course/lectures/Intelligent%20Agents%20and%20Active%20Inference.html)). """Ù$18f5d694-8869-4265-98ac-9ef7ff451eaf„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$18f5d694-8869-4265-98ac-9ef7ff451eaf«code_foldedäcodeÙINotebookCard("https://bmlip.github.io/course/minis/KL%20Divergence.html")Ù$c7351bf1-447e-475b-8965-d259c01bfd57„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$c7351bf1-447e-475b-8965-d259c01bfd57«code_foldedäcodeÚhide_proof( md""" ```math \begin{align} p(x_n) &= \sum_{z_n} p(x_n,z_n) \\ &= \sum_{z_n} \prod_{k=1}^K \left(\pi_k \cdot \mathcal{N}\left( x_n | \mu_k, \Sigma_k\right) \right)^{z_{nk}} \\ &= \sum_{j=1}^K \prod_{k=1}^K \left( \pi_k \cdot \mathcal{N}\left( x_n | \mu_k, \Sigma_k\right) \right)^{I_{kj}} \;\; \text{(use }z_n \text{ is one-hot coded)}\\ &= \sum_{j=1}^K \pi_j \cdot \mathcal{N}\left( x_n | \mu_j, \Sigma_j\right) \end{align} ``` where ``I_{kj} = 1`` if ``k=j`` and ``0`` otherwise. """)Ù$55a1c42b-20d8-47a3-aa00-7af905db537c„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$55a1c42b-20d8-47a3-aa00-7af905db537c«code_foldedäcodeÚtfunction updateR(Λ,m,α,ν,β) #variational expectation function r = Array{Float64}(undef,K,N) #responsibilities hat_Ï€ = Array{Float64}(undef,K) hat_Λ = Array{Float64}(undef,K) for k=1:K hat_Λ[k] = 1/2*(2*log(2)+logdet(Λ[:,:,k])+digamma(ν[k]/2)+digamma((ν[k]-1)/2)) hat_Ï€[k] = exp(digamma(α[k])-digamma(sum(α))) for n=1:N r[k,n] = hat_Ï€[k]*exp(hat_Λ[k]-1/β[k] - (ν[k]/2)*(X[:,n]-m[:,k])'*Λ[:,:,k]*(X[:,n]-m[:,k])) end end for n=1:N r[:,n] = r[:,n] ./ sum(r[:,n]) #normalize to ensure r represents probabilities end return r endÙ$747a7e1e-b921-4882-b00a-1b00bef8433d„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$747a7e1e-b921-4882-b00a-1b00bef8433d«code_foldedäcodeÚ3hide_solution( md""" Note that Free Energy minimization is a balancing act: FE minimization implies entropy maximization *and at the same time* energy minimization. Minimizing the energy term leads to aligning ``q(z)`` with ``\log p(x,z)``, ie, it tries to move the bulk of the function ``q(z)`` to areas in ``z``-space where ``p(x,z)`` is large (``p(x,z)`` is here just a function of ``z``, since x is observed). However, aside from aligning with ``p(x,z)``, we want ``q(z)`` to be as uninformative as possible. Everything that can be inferred should be represented in ``p(x,z)`` (which is prior times likelihood). We don't want to learn anything that is not in either the prior or the likelihood. The entropy term balances the energy term by favoring distributions that are as uninformative as possible. """)Ù$b3bb7349-1965-4734-83ed-ba6fef0ccc41„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$b3bb7349-1965-4734-83ed-ba6fef0ccc41«code_foldedäcodeÚ (md""" ## Variational Inference and The Maximum Entropy Principle In [Caticha (2010)](https://arxiv.org/abs/1011.0723) (based on earlier work by [Shore and Johnson (1980)](https://github.com/bmlip/course/blob/main/assets/files/ShoreJohnson-1980-Axiomatic-Derivation-of-the-Principle-of-Maximum-Entropy.pdf)), the [Principle of Maximum (Relative) Entropy](https://en.wikipedia.org/wiki/Principle_of_maximum_entropy) is developed as a method for rational updating of priors to posteriors when faced with new information in the form of constraints. Caticha's argumentation is as follows: * Consider prior beliefs (i.e., a generative model) ``p(x,z)`` about observed and latent variables ``x`` and ``z``. Assume that new information in the form of constraints is obtained, and we are interested in the "best update" to posterior beliefs ``q(x,z)``. * In order to define what "best update" means, Caticha assumed a ranking function ``S[q]`` that generates a preference score for each candidate posterior ``q`` for a given prior ``p``. The best update from ``p`` to ``q`` is then identified as ```math q^* = \arg\max_q S[q]\,, \quad \text{subject to all constraints.} ``` Similarly to [Cox' method](https://en.wikipedia.org/wiki/Cox%27s_theorem) for deriving Probability Theory from a set of sensical axioms, Caticha then introduced the following axioms, based on a rational principle (the **principle of minimal updating**, see [Caticha 2010](https://arxiv.org/abs/1011.0723)), that the ranking function needs to adhere to: 1. *Locality*: local information has local effects. 2. *Coordinate invariance*: the system of coordinates carries no information. 3. *Independence*: When systems are known to be independent, it should not matter whether they are treated separately or jointly. It turns out that these three criteria **uniquely identify the Relative Entropy** as the proper ranking function: ```math \begin{align*} S[q] = - \sum_z q(x,z) \log \frac{q(x,z)}{p(x,z)} \end{align*} ``` This procedure for finding the variational posterior ``q`` is called the **Principle of Maximum (Relative) Entropy** (PME). Note that, since ``S[q]=-F[q]``, constrained Relative Entropy maximization is equivalent to constrained VFE minimization! Therefore, when information is supplied in the form of constraints on the posterior (such as form/factorization constraints and new observations as data constraints), we *should* select the posterior that minimizes the constrained Variational Free Energy. **Constrained FE minimization is the proper method for inference!** Bayes rule is the global solution of constrained VFEM when all constraints are data constraints, ie, delta distributions on ``q(x)``. Hence, Bayes rule is a special case of constrained VFEM. Bayes rule only applies to updating beliefs on the basis of new observations. """Ù$26c6e002-d294-11ef-15a4-33e30d0d76ec„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c6e002-d294-11ef-15a4-33e30d0d76ec«code_foldedäcodeÚômd""" ## The Global VFE Minimum Recovers Bayes Rule It turns out that we can perform (approximate) Bayesian inference by minimizing the Variational Free Energy (VFE) with respect to the variational distribution ``q``. To explain inference by VFE minimization (abbreviated as VFEM), we first rewrite the VFE in terms of "inference bound" minus "log-evidence" terms (the bound-evidence (BE) decomposition): ```math \begin{align*} F[q] &= \underbrace{ \int q(z) \log \frac{q(z)}{p(z)} \mathrm{d}z }_{\text{complexity}} - \underbrace{\int q(z) \log p(x|z) \mathrm{d}z}_{\text{accuracy}} \\ &= \underbrace{\int q(z) \log \frac{q(z)}{p(z|x)}\mathrm{d}z}_{\text{inference bound}\geq 0} - \underbrace{\log p(x)}_{\text{log-evidence}} \end{align*} ``` """Ù$60a50f12-063c-4247-9c9c-bb41d5dc9811„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$60a50f12-063c-4247-9c9c-bb41d5dc9811«code_foldedäcode³md""" # Summary """Ù$0e9e62ea-1b2f-4e80-b78b-2001ae46093f„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$0e9e62ea-1b2f-4e80-b78b-2001ae46093f«code_folded¤codeÙŽfunction get_color(xs; colors=cluster_colors) if any(isnan, xs) mean(cluster_colors) else sum(x*c for (x,c) in zip(xs, colors)) end endÙ$40ce0abb-a086-4977-9131-10f60ab44152„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$40ce0abb-a086-4977-9131-10f60ab44152«code_foldedäcodeÙØkeyconcept("", md"VFE minimization transforms a Bayesian inference problem (that involves integration) into an optimization problem! Generally, optimization problems are easier to solve than integration problems.") Ù$4ff85bda-22bb-408d-a50a-461834b7c0ff„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$4ff85bda-22bb-408d-a50a-461834b7c0ff«code_foldedäcode³keyconceptsummary()Ù$26c75b5e-d294-11ef-173e-b3f46a1df536„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c75b5e-d294-11ef-173e-b3f46a1df536«code_foldedäcodeÚòmd""" Exam guide: Working out VFE minimization for the GMM to these update equations (eqs B-10.58 through B-10.63) is not something that you need to reproduce without assistance at the exam. Rather, the essence is that *it is possible* to arrive at closed-form variational update equations for the GMM. You should understand though how FEM works conceptually and in principle be able to derive variational update equations for very simple models that do not involve clever mathematical tricks. """Ù$fd233604-120a-4838-a660-d5021bccecd0„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$fd233604-120a-4838-a660-d5021bccecd0«code_foldedäcodeÙÎlet (i, step), res = em_result[iteration_em] plotGMM( X, res.clusters, res.γ; title=i == 0 ? "Initial situation" : "Iteration $(i), $(step)-step", legend=nothing, size=(600,300), ) endÙ$c18b7c1b-8011-469b-ad92-7d50c23c46e3„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$c18b7c1b-8011-469b-ad92-7d50c23c46e3«code_folded¤codeÙ7const plot_lims = ( xlim=(1.3, 5.5), ylim=(41, 99), )Ù$bbdca8c2-022f-42be-bcf7-80d86f7f269c„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$bbdca8c2-022f-42be-bcf7-80d86f7f269c«code_foldedäcodeÚÇmd""" ## Model Performance Evaluation, Revisited Let us reconsider the Bound-Evidence decomposition of the VFE for a model ``p(x,z)`` with variational posterior ``q(z)``, ```math \begin{align} \mathrm{F}[q] = \underbrace{\sum_z q(z) \log \frac{q(z)}{p(z|x)}}_{\text{inference bound}\geq 0} \underbrace{- \log p(x)}_{\text{surprise}} \tag{BE} \end{align} ``` The VFE comprises two cost terms: - The **surprise** (or negative log-evidence), ``-\log p(x)``, reflects the cost of predicting the data ``x`` using a model ``p(x, z)``, assuming that (ideal) Bayesian inference can be performed. Specifically, the evidence ``p(x)`` is obtained from the joint model ``p(x, z)`` by marginalizing over the latent variables: ```math p(x) = \sum_z p(x,z) \,. ``` - The **inference bound**, given by the Kullback–Leibler divergence ```math \sum_z q(z) \log \frac{q(z)}{p(z |x)} \geq 0 \,, ``` quantifies the cost of imperfect inference, i.e., the discrepancy between the variational posterior ``q(z)`` and the true Bayesian posterior ``p(z | x)``. In any practical setting, using a model *implies* performing inference within that model. Therefore, the effective cost of applying a model is not merely the surprise but also must include the cost of inference. Put more bluntly: a model with very high Bayesian evidence ``p(x)`` may still be practically unusable due to exorbitant inference costs. In the literature, the VFE is typically interpreted as an approximation (more precisely, an upper-bound) to the surprise, ``-\log p(x)``, which is often regarded as the “trueâ€� measure of model performance. However, we argue that this perspective should be reversed: the VFE should be considered the true performance metric in practice, as it accounts for both model fit and the tractability of inference. The surprise can be viewed as a special case of the VFE, corresponding to a zero inference bound, that only applies when ideal Bayesian inference is computationally feasible. """Ù$cc547bfa-a130-4382-af47-73de56e4741b„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$cc547bfa-a130-4382-af47-73de56e4741b«code_foldedäcodeÚüold_faithful = # CSV.read(download("https://github.com/bmlip/course/blob/v2/assets/datasets/old_faithful.csv?raw=true"), DataFrame); # inlining the dataset is the most reliable :)s [ 3.600000 79.000000 1.800000 54.000000 3.333000 74.000000 2.283000 62.000000 4.533000 85.000000 2.883000 55.000000 4.700000 88.000000 3.600000 85.000000 1.950000 51.000000 4.350000 85.000000 1.833000 54.000000 3.917000 84.000000 4.200000 78.000000 1.750000 47.000000 4.700000 83.000000 2.167000 52.000000 1.750000 62.000000 4.800000 84.000000 1.600000 52.000000 4.250000 79.000000 1.800000 51.000000 1.750000 47.000000 3.450000 78.000000 3.067000 69.000000 4.533000 74.000000 3.600000 83.000000 1.967000 55.000000 4.083000 76.000000 3.850000 78.000000 4.433000 79.000000 4.300000 73.000000 4.467000 77.000000 3.367000 66.000000 4.033000 80.000000 3.833000 74.000000 2.017000 52.000000 1.867000 48.000000 4.833000 80.000000 1.833000 59.000000 4.783000 90.000000 4.350000 80.000000 1.883000 58.000000 4.567000 84.000000 1.750000 58.000000 4.533000 73.000000 3.317000 83.000000 3.833000 64.000000 2.100000 53.000000 4.633000 82.000000 2.000000 59.000000 4.800000 75.000000 4.716000 90.000000 1.833000 54.000000 4.833000 80.000000 1.733000 54.000000 4.883000 83.000000 3.717000 71.000000 1.667000 64.000000 4.567000 77.000000 4.317000 81.000000 2.233000 59.000000 4.500000 84.000000 1.750000 48.000000 4.800000 82.000000 1.817000 60.000000 4.400000 92.000000 4.167000 78.000000 4.700000 78.000000 2.067000 65.000000 4.700000 73.000000 4.033000 82.000000 1.967000 56.000000 4.500000 79.000000 4.000000 71.000000 1.983000 62.000000 5.067000 76.000000 2.017000 60.000000 4.567000 78.000000 3.883000 76.000000 3.600000 83.000000 4.133000 75.000000 4.333000 82.000000 4.100000 70.000000 2.633000 65.000000 4.067000 73.000000 4.933000 88.000000 3.950000 76.000000 4.517000 80.000000 2.167000 48.000000 4.000000 86.000000 2.200000 60.000000 4.333000 90.000000 1.867000 50.000000 4.817000 78.000000 1.833000 63.000000 4.300000 72.000000 4.667000 84.000000 3.750000 75.000000 1.867000 51.000000 4.900000 82.000000 2.483000 62.000000 4.367000 88.000000 2.100000 49.000000 4.500000 83.000000 4.050000 81.000000 1.867000 47.000000 4.700000 84.000000 1.783000 52.000000 4.850000 86.000000 3.683000 81.000000 4.733000 75.000000 2.300000 59.000000 4.900000 89.000000 4.417000 79.000000 1.700000 59.000000 4.633000 81.000000 2.317000 50.000000 4.600000 85.000000 1.817000 59.000000 4.417000 87.000000 2.617000 53.000000 4.067000 69.000000 4.250000 77.000000 1.967000 56.000000 4.600000 88.000000 3.767000 81.000000 1.917000 45.000000 4.500000 82.000000 2.267000 55.000000 4.650000 90.000000 1.867000 45.000000 4.167000 83.000000 2.800000 56.000000 4.333000 89.000000 1.833000 46.000000 4.383000 82.000000 1.883000 51.000000 4.933000 86.000000 2.033000 53.000000 3.733000 79.000000 4.233000 81.000000 2.233000 60.000000 4.533000 82.000000 4.817000 77.000000 4.333000 76.000000 1.983000 59.000000 4.633000 80.000000 2.017000 49.000000 5.100000 96.000000 1.800000 53.000000 5.033000 77.000000 4.000000 77.000000 2.400000 65.000000 4.600000 81.000000 3.567000 71.000000 4.000000 70.000000 4.500000 81.000000 4.083000 93.000000 1.800000 53.000000 3.967000 89.000000 2.200000 45.000000 4.150000 86.000000 2.000000 58.000000 3.833000 78.000000 3.500000 66.000000 4.583000 76.000000 2.367000 63.000000 5.000000 88.000000 1.933000 52.000000 4.617000 93.000000 1.917000 49.000000 2.083000 57.000000 4.583000 77.000000 3.333000 68.000000 4.167000 81.000000 4.333000 81.000000 4.500000 73.000000 2.417000 50.000000 4.000000 85.000000 4.167000 74.000000 1.883000 55.000000 4.583000 77.000000 4.250000 83.000000 3.767000 83.000000 2.033000 51.000000 4.433000 78.000000 4.083000 84.000000 1.833000 46.000000 4.417000 83.000000 2.183000 55.000000 4.800000 81.000000 1.833000 57.000000 4.800000 76.000000 4.100000 84.000000 3.966000 77.000000 4.233000 81.000000 3.500000 87.000000 4.366000 77.000000 2.250000 51.000000 4.667000 78.000000 2.100000 60.000000 4.350000 82.000000 4.133000 91.000000 1.867000 53.000000 4.600000 78.000000 1.783000 46.000000 4.367000 77.000000 3.850000 84.000000 1.933000 49.000000 4.500000 83.000000 2.383000 71.000000 4.700000 80.000000 1.867000 49.000000 3.833000 75.000000 3.417000 64.000000 4.233000 76.000000 2.400000 53.000000 4.800000 94.000000 2.000000 55.000000 4.150000 76.000000 1.867000 50.000000 4.267000 82.000000 1.750000 54.000000 4.483000 75.000000 4.000000 78.000000 4.117000 79.000000 4.083000 78.000000 4.267000 78.000000 3.917000 70.000000 4.550000 79.000000 4.083000 70.000000 2.417000 54.000000 4.183000 86.000000 2.217000 50.000000 4.450000 90.000000 1.883000 54.000000 1.850000 54.000000 4.283000 77.000000 3.950000 79.000000 2.333000 64.000000 4.150000 75.000000 2.350000 47.000000 4.933000 86.000000 2.900000 63.000000 4.583000 85.000000 3.833000 82.000000 2.083000 57.000000 4.367000 82.000000 2.133000 67.000000 4.350000 74.000000 2.200000 54.000000 4.450000 83.000000 3.567000 73.000000 4.500000 73.000000 4.150000 88.000000 3.817000 80.000000 3.917000 71.000000 4.450000 83.000000 2.000000 56.000000 4.283000 79.000000 4.767000 78.000000 4.533000 84.000000 1.850000 58.000000 4.250000 83.000000 1.983000 43.000000 2.250000 60.000000 4.750000 75.000000 4.117000 81.000000 2.150000 46.000000 4.417000 90.000000 1.817000 46.000000 4.467000 74.000000 ]Ù$62868f61-95c7-4e07-854f-a171aadc667b„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$62868f61-95c7-4e07-854f-a171aadc667b«code_foldedäcodeÙEcode_example("EM-algorithm for the GMM on the Old-Faithful data set")Ù$26c5d734-d294-11ef-20a3-afd2c3324323„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c5d734-d294-11ef-20a3-afd2c3324323«code_foldedäcodeÚmd""" ## GMM is a Flexible Model GMMs are very popular models. They have decent computational properties and are **universal approximators of densities** (as long as there are enough Gaussians, of course). ![](https://github.com/bmlip/course/blob/v2/assets/figures/fig-ZoubinG-GMM-universal-approximation.png?raw=true) (In the above figure, the Gaussian components are shown in $(html"red") and the pdf of the mixture models in $(html"blue")). """Ù$26c9121e-d294-11ef-18e6-ed8105503adc„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c9121e-d294-11ef-18e6-ed8105503adc«code_foldedäcodeÚkmd""" ## The Bethe Free Energy and Belief Propagation We showed that, under mean field assumptions, the FE can be decomposed into a sum of local FE contributions for the nodes (``a``) and edges (``i``): ```math \begin{align*} F[q] = \sum_{a=1}^M \underbrace{\sum_{x_a} \left( \prod_{j\in N(a)} q_j(x_j)\cdot \left(-\log p_a(x_a)\right) \right) }_{\text{node energy }U[p_a]} - \sum_{i=1}^N \underbrace{\sum_{x_i} q_i(x_i) \log \frac{1}{q_i(x_i)}}_{\text{edge entropy }H[q_i]} \end{align*} ``` The mean field assumption is very strong and may lead to large inference costs (``\mathrm{KL}(q(x),p(x|\text{data}))``). A more relaxed assumption is to allow joint posterior beliefs over the variables that attach to a node. This idea is expressed by the Bethe Free Energy: ```math \begin{align*} F_B[q] = \sum_{a=1}^M \left( \sum_{x_a} q_a(x_a) \log \frac{q_a(x_a)}{p_a(x_a)} \right) - \sum_{i=1}^N (d_i - 1) \sum_{x_i} q_i(x_i) \log {q_i(x_i)} \end{align*} ``` where ``q_a(x_a)`` is the posterior joint belief over the variables ``x_a`` (i.e., the set of variables that attach to node ``a``), ``q_i(x_i)`` is the posterior marginal belief over the variable ``x_i`` and ``d_i`` is the number of factor nodes that link to edge ``i``. Moreover, ``q_a(x_a)`` and ``q_i(x_i)`` are constrained to obey the following equalities: ```math \begin{align*} \sum_{x_a \backslash x_i} q_a(x_a) &= q_i(x_i), ~~~ \forall i, \forall a \\ \sum_{x_i} q_i(x_i) &= 1, ~~~ \forall i \\ \sum_{x_a} q_a(x_a) &= 1, ~~~ \forall a \\ \end{align*} ``` We form the Lagrangian by augmenting the Bethe Free Energy functional with the constraints: ```math \begin{align*} L[q] = F_B[q] + \sum_i\sum_{a \in N(i)} \lambda_{ai}(x_i) \left(q_i(x_i) - \sum_{x_a\backslash x_i} q(x_a) \right) + \sum_{i} \gamma_i \left( \sum_{x_i}q_i(x_i) - 1\right) + \sum_{a}\gamma_a \left( \sum_{x_a}q_a(x_a) -1\right) \end{align*} ``` The stationary solutions for this Lagrangian are given by ```math \begin{align*} q_a(x_a) &= f_a(x_a) \exp\left(\gamma_a -1 + \sum_{i \in N(a)} \lambda_{ai}(x_i)\right) \\ q_i(x_i) &= \exp\left(1- \gamma_i + \sum_{a \in N(i)} \lambda_{ai}(x_i)\right) ^{\frac{1}{d_i - 1}} \end{align*} ``` where ``N(i)`` denotes the factor nodes that have ``x_i`` in their arguments and ``N(a)`` denotes the set of variables in the argument of ``f_a``. Stationary solutions are functions of Lagrange multipliers. This means that Lagrange multipliers need to be determined. Lagrange multipliers can be determined by plugging the stationary solutions back into the constraint specification and solving for the multipliers which ensure that the constraint is satisfied. The first constraint we consider is normalization, which yields the following identification: ```math \begin{align*} \gamma_a &= 1 - \log \Bigg(\sum_{x_a}f_a(x_a)\exp\left(\sum_{i \in N(a)}\lambda_{ai}(x_i)\right)\Bigg)\\ \gamma_i &= 1 + (d_i-1) \log\Bigg(\sum_{x_i}\exp\left( \frac{1}{d_i-1}\sum_{a \in N(i)} \lambda_{ai}(x_i)\right)\Bigg). \end{align*} ``` The functional form of the Lagrange multipliers that corresponds to the normalization constraint enforces us to obtain the Lagrange multipliers that correspond to the marginalization constraint. To do so we solve for ```math \begin{align*} \sum_{x_a \backslash x_i} f_a(x_a) \exp\left(\sum_{i \in N(a)} \lambda_{ai}(x_i)\right) &= \exp\left(\sum_{a \in N(i)} \lambda_{ai}(x_i)\right) ^{\frac{1}{d_i - 1}} \exp\left(\lambda_{ai}(x_i)\right)\sum_{x_a \backslash x_i} f_a(x_a) \exp\Bigg(\sum_{\substack{{j \in N(a)} j \neq i}}\lambda_{aj}(x_j)\Bigg) \\ &= \exp\left(\sum_{a \in N(i)} \lambda_{ai}(x_i)\right) ^{\frac{1}{d_i - 1}} \exp\left(\lambda_{ai}(x_i) + \lambda_{ia}(x_i)\right) \\ &= \exp\left(\sum_{a \in N(i)} \lambda_{ai}(x_i)\right) ^{\frac{1}{d_i - 1}}\, , \end{align*} ``` where we defined an auxilary function ```math \begin{align*} \exp(\lambda_{ia}(x_i)) \triangleq \sum_{x_a \backslash x_i} f_a(x_a) \exp\Bigg(\sum_{\substack{{j \in N(a)} j \neq i}}\lambda_{aj}(x_j)\Bigg) \,. \end{align*} ``` This definition is valid since it can be inverted by the relation ```math \begin{align*} \lambda_{ia}(x_i) = \frac{2-d_i}{d_i - 1}\lambda_{ai}(x_i) + \frac{1}{d_i -1}\sum_{\substack{c \in N(i)\\c \neq a}}\lambda_{ci}(x_i) \end{align*} ``` In general it is not possible to solve for the Lagrange multipliers analytically and we resort to iteratively obtaining the solutions. This leads to the **Belief Propagation algorithm** where the exponentiated Lagrange multipliers (messages) are updated iteratively via ```math \begin{align*} \mu_{ia}^{(k+1)}(x_i) &= \sum_{x_a \backslash x_i} f_a(x_a) \prod_{\substack{{j \in N(a)} j \neq i}}\mu^{(k)}_{aj}(x_j) \mu_{ai}^{(k)}(x_i) \\ &= \prod_{\substack{c \in N(i) c \neq a}}\mu^{(k)}_{ic}(x_i)\,, \end{align*} ``` where ``k`` denotes iteration number and the messages are defined as ```math \begin{align*} \mu_{ia}(x_i) &\triangleq \exp(\lambda_{ia}(x_i))\\ \mu_{ai}(x_i) &\triangleq \exp(\lambda_{ai}(x_i))\,. \end{align*} ``` For a more complete overview of message passing as Bethe Free Energy minimization, see [Senoz et al. (2021)](https://research.tue.nl/nl/publications/variational-message-passing-and-local-constraint-manipulation-in-). """Ù$26c67f04-d294-11ef-03a4-838ae255689d„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c67f04-d294-11ef-03a4-838ae255689d«code_foldedäcodeÚ "md""" ## The Variational Free Energy Functional We'll start from scratch. Consider a model ``p(x,z) = p(x|z) p(z)``, where ``x`` and ``z`` are observed and latent variables, respectively. ``z`` may include parameters but also observation-dependent latent variables. The goal of Bayesian inference is to transform the (known) *likelihood-times-prior* factorization of the full model to a *posterior-times-evidence* decomposition: ```math \underbrace{p(x|z) p(z)}_{\text{what we know}} \rightarrow \underbrace{p(z|x) p(x)}_{\text{what we want}} ``` Remember from the [Bayesian machine learning lesson](https://bmlip.github.io/course/lectures/Bayesian%20Machine%20Learning.html#Bayesian-model-evidence) that negative log-evidence can be decomposed as "complexity" minus "accuracy" terms (the CA decomposition): ```math -\log p(x) = \underbrace{ \int p(z|x) \log \frac{p(z|x)}{p(z)} \mathrm{d}z }_{\text{complexity}} - \underbrace{\int p(z|x) \log p(x|z) \mathrm{d}z}_{\text{accuracy}} ``` The CA decomposition cannot be evaluated because it depends on the posterior ``p(z|x)``, which cannot be evaluated since it is the objective of the inference process. Let's now introduce a distribution ``q(z)`` (called the "variational" or "approximate" posterior distribution) that we will use to *approximate* the posterior ``p(z|x)``. Since we propose the distribution ``q(z)`` ourselves, we will assume that ``q(z)`` can be evaluated. If we substitute ``q(z)`` for ``p(z|x)`` in the CA decomposition, then we obtain ```math F[q] \triangleq \underbrace{ \int q(z) \log \frac{q(z)}{p(z)} \mathrm{d}z }_{\text{complexity}} - \underbrace{\int q(z) \log p(x|z) \mathrm{d}z}_{\text{accuracy}} ``` This expression is called the **Variational Free Energy** (VFE), represented by the symbol ``F``. We treat ``F`` as a function of the posterior ``q(z)``. Technically, a function of a function is called a functional, and we write square brackets (e.g., ``F[q]``) to differentiate functionals from functions (e.g., ``q(z)``). Note that all factors in the CA decomposition of VFE (i.e., ``q(z)``, ``p(z)``, and ``p(x|z)``) can be evaluated as a function of ``z`` (and ``x`` is observed), and therefore the VFE can be evaluated. This is important: log-evidence ``\log p(x)`` cannot be evaluated, but ``F[q]`` *can* be evaluated! """Ù$4ee377c2-a126-4c40-8053-517d40c5ef9d„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$4ee377c2-a126-4c40-8053-517d40c5ef9d«code_foldedäcodeÚ·vfem_result = let #store the inference results in these vectors ν = fill(3.0, K, max_iterations) β = fill(1.0, K, max_iterations) α = fill(0.01, K, max_iterations) R = Array{Float64}(undef,K,N,max_iterations) M = Array{Float64}(undef,2,K,max_iterations) Λ = Array{Float64}(undef,2,2,K,max_iterations) clusters_vb = Array{Distribution}(undef,K,max_iterations) #clusters to be plotted #initialize prior distribution parameters M[:,:,1] = rand(MersenneTwister(43), 2, K) .* [4, 50] .+ [1, 50] for k in 1:K Λ[:,:,k,1] = [1.0 0;0 0.01] R[k,:,1] = 1/(K)*ones(N) clusters_vb[k,1] = MvNormal(M[:,k,1],PDMats.PDMat(convert(Matrix,Hermitian(inv(ν[1,1].*Λ[:,:,k,1]))))) end #variational inference for i in 1:max_iterations-1 #variational expectation R[:,:,i+1] = updateR(Λ[:,:,:,i],M[:,:,i],α[:,i],ν[:,i],β[:,i]) #variational minimisation M[:,:,i+1],β[:,i+1],Λ[:,:,:,i+1],ν[:,i+1],α[:,i+1] = updateMeanPrecisionPi(M[:,:,i],β[:,i],Λ[:,:,:,i],ν[:,i],α[:,i],R[:,:,i+1]) for k in 1:K clusters_vb[k,i+1] = MvNormal(M[:,k,i+1],PDMats.PDMat(convert(Matrix,Hermitian(inv(ν[k,i+1].*Λ[:,:,k,i+1]))))) end end (; clusters_vb, R) endÙ$26c5cfb4-d294-11ef-05bb-59d5e27cf37c„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c5cfb4-d294-11ef-05bb-59d5e27cf37c«code_foldedäcodeÚZmd""" ## The Marginal Distribution for the GMM In the literature, the GMM is often introduced by the marginal distribution for an *observed* data point ``x_n``, given by ```math \begin{align*}{} p(x_n) &= \sum_{z_n} p(x_n,z_n) \\ &= \sum_{k=1}^K \pi_k \cdot \mathcal{N}\left( x_n | \mu_k, \Sigma_k \right) \tag{B-9.12} \end{align*} ``` """Ù$a7fb83cb-1f40-4c8a-9fda-2165f91e413e„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$a7fb83cb-1f40-4c8a-9fda-2165f91e413e«code_foldedäcodeÚ¢let (i, step), res = em_result[iteration_em] # Get the current iteration's parameters current_clusters = res.clusters current_responsibilities = res.γ # Compute mixture weights (Ï€) from responsibilities Ï€ = vec(mean(current_responsibilities, dims=2)) if any(isnan, Ï€) Ï€ = ones(size(Ï€)) end Ï€ = Ï€ ./ sum(Ï€) # Normalize to ensure they sum to 1 # Generate synthetic data of the same size as original N_synthetic = size(X, 2) # Same number of points as original data X_synthetic = Matrix{Float64}(undef, 2, N_synthetic) # Sample from the mixture model Random.seed!(42) # For reproducibility components = rand(Categorical(Ï€), N_synthetic) for n in 1:N_synthetic # Sample which component to use # Sample from that component X_synthetic[:, n] = rand(current_clusters[components[n]]) end # Create the plot scatter( X_synthetic[1,:], X_synthetic[2,:]; title="Synthetic data from this model", size=(600,300), legend=nothing, plot_lims..., data_plot_kwargs..., color=show_em_synthetic_labels ? cluster_colors[components] : :purple, ) endÙ$64819124-865e-48b8-a916-2ce08dba0acc„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$64819124-865e-48b8-a916-2ce08dba0acc«code_foldedäcodeÙh@htl """ """Ù$16d90f11-5933-4145-b219-19774eba25d6„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$16d90f11-5933-4145-b219-19774eba25d6«code_foldedäcodeÙt@htl """ """Ù$06170e31-e865-4178-8af0-41d82df95d71„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$06170e31-e865-4178-8af0-41d82df95d71«code_foldedäcodeÚ`keyconcept("","Constrained VFE minimization is consistent with the **Maximum Entropy Principle**, which prescribes how to rationally update beliefs when new information becomes available. In this framework, the updated posterior is the distribution that minimizes VFE (or equivalently, KL divergence to the prior) subject to the imposed constraints. ")Ù$f1f7407d-86a1-4f24-b78a-61a411d1f371„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$f1f7407d-86a1-4f24-b78a-61a411d1f371«code_foldedäcodeÙ!md""" # Variational Inference """Ù$5af3ff1b-1655-4dd9-a089-91544fc85a0e„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$5af3ff1b-1655-4dd9-a089-91544fc85a0e«code_foldedäcodeÙh@bindname iteration_em Slider(eachindex(em_result); default=2, show_value=i->join(em_result[i][1], "-"))Ù$8555aec9-4e80-49e7-8514-ef4a2236801b„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$8555aec9-4e80-49e7-8514-ef4a2236801b«code_folded¤code®N = size(X, 2)Ù$26c65092-d294-11ef-39cc-1953a725f285„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c65092-d294-11ef-39cc-1953a725f285«code_foldedäcodeÚZmd""" Can we still compute an approximate posterior? In this lesson, we introduce an approximate Bayesian inference method known as **Variational Bayes** (VB) (also known as **Variational Inference**) that can be used for Bayesian inference in models with latent variables. Later in this lesson, we will use VB to do inference in the GMM. """Ù$3948225e-90d8-4b78-ba9b-5f98e228285a„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$3948225e-90d8-4b78-ba9b-5f98e228285a«code_foldedäcodeÙBscatter(X[1,:], X[2,:]; label="observations", data_plot_kwargs...)Ù$95d47a10-f3f8-479b-afe0-21241104b758„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$95d47a10-f3f8-479b-afe0-21241104b758«code_foldedäcodeÙ7code_example("VFEM for GMM on Old Faithfull data set") Ù$26c62ebe-d294-11ef-0cfb-ef186203e890„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c62ebe-d294-11ef-0cfb-ef186203e890«code_foldedäcodeÙàmd""" Since the class labels ``y_{nk} \in \{0,1\}`` were assumed to be given by the data set, maximization of this expression decomposed into a set of simple update rules for the Gaussian and multinomial distributions. """Ù$c4b23b39-e6e4-44ec-b204-0c7d7d5a4026„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$c4b23b39-e6e4-44ec-b204-0c7d7d5a4026«code_foldedäcodeÚ]md""" Since the second term (log-evidence) does not involve ``q(z)``, VFEM over ``q`` will bring ``q(z)`` closer to the Bayesian posterior ``p(z|x)``. Since ``D_{\text{KL}}[q(z),p(z|x)]\geq 0`` for any ``q(z)``, and ``D_{\text{KL}}[q(z),p(z|x)]= 0`` only if ``q(z) = p(z|x)``, the VFE is always an upper bound on (minus) log-evidence, i.e., ```math F[q] \geq -\log p(x) \,. ``` As a result, global minimization of VFE leads to ```math q^*(z) = \arg\min_q F[q] ``` where ```math \begin{align} q^*(z) &= p(z|x) \tag{= posterior}\\ F[q^*] &= -\log p(x) \tag{= -log evidence} \end{align} ``` """Ù$26c5b896-d294-11ef-1d8e-0feb99d2d45b„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c5b896-d294-11ef-1d8e-0feb99d2d45b«code_foldedäcodeÚ"md""" We associate a one-hot coded hidden class label ``z_n`` with each observation ``x_n``: ```math \begin{equation*} z_{nk} = \begin{cases} 1 & \text{if } x_n \in \mathcal{C}_k \text{ (the $k$-th class)}\\ 0 & \text{otherwise} \end{cases} \end{equation*} ``` """Ù$26c623f6-d294-11ef-13c0-19edd43592c0„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c623f6-d294-11ef-13c0-19edd43592c0«code_foldedäcodeÚ„md""" ## Inference for GMM is Difficult Indeed, the fact that the observation-dependent class labels are *unobserved* for the GMM, leads to a problem for processing new data by Bayes rule in a GMM. Consider a given data set ``D = \{x_1,x_2,\ldots,x_N\}``. We recall here the log-likelihood for the Gaussian-Categorial Model, see the [generative classification lesson](https://bmlip.github.io/course/lectures/Generative%20Classification.html): ```math \log\, p(D|\theta) = \sum_{n,k} y_{nk} \underbrace{ \log\mathcal{N}(x_n|\mu_k,\Sigma) }_{ \text{Gaussian} } + \underbrace{ \sum_{n,k} y_{nk} \log \pi_k }_{ \text{multinomial} } \,. ``` """Ù$55570464-89c8-4d9b-b667-dfa64ac62294„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$55570464-89c8-4d9b-b667-dfa64ac62294«code_foldedäcode°md""" # Code """Ù$26c59b52-d294-11ef-1eba-d3f235f85eee„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c59b52-d294-11ef-1eba-d3f235f85eee«code_foldedäcodeÚímd""" ## Unobserved Classes Consider again a set of observed data ``D=\{x_1,\dotsc,x_N\}``. This time, we suspect that there are *unobserved* class labels that would help explain (or predict) the data, e.g., * the observed data are the color of living things; the unobserved classes are animals and plants. * observed are wheel sizes; unobserved categories are trucks and personal cars. * observed is an audio signal; unobserved classes include speech, music, traffic noise, etc. """Ù$f17c9d8a-9291-4110-bcf4-c582d23f986b„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$f17c9d8a-9291-4110-bcf4-c582d23f986b«code_foldedäcodeÙŒmd""" ## Variational Message Passing Let us now consider the local free energy that is associated with edge corresponding to ``x_j``. """Ù$dd1242db-fb20-4732-ac55-a3e021bbd2b7„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$dd1242db-fb20-4732-ac55-a3e021bbd2b7«code_folded¤codeÙ^const data_plot_kwargs = ( markersize=4, markerstrokewidth=0, color=:red4, opacity=.8, )Ù$26c73cf0-d294-11ef-297b-354eb9c71f57„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c73cf0-d294-11ef-297b-354eb9c71f57«code_foldedäcodeÙÓmd""" ## Derivation of VFEM Update Equations Let's get back to the illustrative challenge at the beginning of this lesson: we want to do [density modeling for the Old Faithful data set](#challenge_hello). """Ù$2d4adbf6-6de8-4e3a-ad6f-fa8bbfa5999e„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$2d4adbf6-6de8-4e3a-ad6f-fa8bbfa5999e«code_foldedäcodeÙþmd""" #### Mean Updating (*) Explain the following update rule for the [mean of the Gaussian cluster-conditional data distribution](##Update-Equations): ```math m_k = \frac{1}{\beta_k} \left( \beta_0 m_0 + N_k \bar{x}_k \right) \tag{B-10.61} ``` """Ù$26c56fd8-d294-11ef-236d-81deef63f37c„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c56fd8-d294-11ef-236d-81deef63f37c«code_foldedäcodeÙ5title("Latent Variable Models and Variational Bayes")Ù$666680b2-315a-4d95-8f7f-3ae50018e112„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$666680b2-315a-4d95-8f7f-3ae50018e112«code_folded¤code¦K = 6;Ù$0349720e-5de4-4b39-babd-c0881588f1de„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$0349720e-5de4-4b39-babd-c0881588f1de«code_foldedäcodeÙ)X = Array(Matrix{Float64}(old_faithful)')Ù$cd7cf2d0-aff7-49dc-bb12-dc73c6433768„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$cd7cf2d0-aff7-49dc-bb12-dc73c6433768«code_foldedäcodeÚˆlet i = iteration_vfem + 1 # Get the current iteration's parameters current_clusters = vfem_result.clusters_vb[:, i] current_responsibilities = vfem_result.R[:, :, i] # Compute mixture weights (Ï€) from responsibilities Ï€ = vec(mean(current_responsibilities, dims=2)) Ï€ = Ï€ ./ sum(Ï€) # Normalize to ensure they sum to 1 # Generate synthetic data of the same size as original N_synthetic = size(X, 2) # Same number of points as original data X_synthetic = Matrix{Float64}(undef, 2, N_synthetic) # Sample from the mixture model Random.seed!(42) # For reproducibility components = rand(Categorical(Ï€), N_synthetic) for n in 1:N_synthetic # Sample which component to use # Sample from that component X_synthetic[:, n] = rand(current_clusters[components[n]]) end # Create the plot scatter( X_synthetic[1,:], X_synthetic[2,:]; title="Synthetic data from this model", size=(600,300), legend=nothing, plot_lims..., data_plot_kwargs..., color=show_vfem_synthetic_labels ? cluster_colors[components] : :purple, ) endÙ$b4d965d1-91d8-43f8-84a5-b37ad5c6cafa„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$b4d965d1-91d8-43f8-84a5-b37ad5c6cafa«code_foldedäcodeÙÿmd""" Note that the inference bound is a [Kullback-Leibler (KL) divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) between an (approximate) posterior ``q(z)`` and the (perfect) Bayesian posterior ``p(z|x)``. To learn more: """Ù$32f0bbb4-dfc7-431e-9a3d-80162439edac„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$32f0bbb4-dfc7-431e-9a3d-80162439edac«code_foldedäcodeÚ ¨md""" Apparently (see previous slide), there are three contributions to the free energy for ``x_j``: * one entropy term for the edge ``x_j`` * two energy terms: one for each node that attaches to ``x_j`` (in the figure: nodes ``p_a`` and ``p_b``) The local free energy for ``x_j`` can be written as (exercise) ```math F[q_j] \propto \sum_{x_j} q(x_j) \log \frac{q_j(x_j)}{\nu_a(x_j)\cdot \nu_b(x_j)} ``` where ```math \begin{align*} \nu_a(x_j) &\propto \exp\left( \mathbb{E}_{q_{k}}\left[ \log p_a(x_a)\right]\right) \\ \nu_b(x_j) &\propto \exp\left( \mathbb{E}_{q_{l}}\left[ \log p_b(x_b)\right]\right) \end{align*} ``` and ``\mathbb{E}_{q_{k}}\left[\cdot\right]`` is an expectation w.r.t. all ``q(x_k)`` with ``k \in N(a)\setminus {j}``. ``\nu_a(x_j)`` and ``\nu_b(x_j)`` can be locally computed in nodes ``a`` and ``b`` respectively and can be interpreted as colliding messages over edge ``x_j``. Local free energy minimization is achieved by setting ```math q_j(x_j) \propto \nu_a(x_j) \cdot \nu_b(x_j) ``` Note that message ``\nu_a(x_j)`` depends on posterior beliefs over incoming edges (``k``) for node ``a``, and in turn, the message from node ``a`` towards edge ``x_k`` depends on the belief ``q_j(x_j)``. I.o.w., direct mutual dependencies exist between posterior beliefs over edges that attach to the same node. These considerations lead to the [Variational Message Passing](https://en.wikipedia.org/wiki/Variational_message_passing) procedure, which is an iterative free energy minimization procedure that can be executed completely through locally computable messages. Procedure VMP, see [Dauwels (2007), section 3](https://github.com/bmlip/course/blob/main/assets/files/Dauwels-2007-on-variational-message-passing-on-factor-graphs.pdf) > 1. Initialize all messages ``q`` and ``ν``, e.g., ``q(\cdot) \propto 1`` and ``\nu(\cdot) \propto 1``.
> 2. Select an edge ``z_k`` in the factor graph of ``f(z_1,\ldots,z_m)``.
> 3. Compute the two messages ``\overrightarrow{\nu}(z_k)`` and ``\overleftarrow{\nu}(z_k)`` by applying the following generic rule: > ```math > \overrightarrow{\nu}(y) \propto \exp\left( \mathbb{E}_{q}\left[ \log g(x_1,\dots,x_n,y)\right] \right) > ``` > 4. Compute the marginal ``q(z_k)`` > ```math > q(z_k) \propto \overrightarrow{\nu}(z_k) \overleftarrow{\nu}(z_k) > ``` > and send it to the two nodes connected to the edge ``x_k``. > > 5. Iterate 2–4 until convergence. """Ù$26c85a22-d294-11ef-3c8e-7b72a4313ced„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c85a22-d294-11ef-3c8e-7b72a4313ced«code_foldedäcodeÚ md""" ## $(HTML("FE Minimization by the Expectation-Maximization (EM) Algorithm")) The EM algorithm is a special case of VFE minimization that focuses on Maximum-Likelihood estimation for models with latent variables. Consider a model ```math p(x,z,\theta) ``` with observations ``x = \{x_n\}``, latent variables ``z=\{z_n\}`` and parameters ``\theta``. We can write the following VFE functional for this model: ```math \begin{align*} F[q] = \sum_z \sum_\theta q(z,\theta) \log \frac{q(z,\theta)}{p(x,z,\theta)} \end{align*} ``` The EM algorithm makes the following simplifying assumptions: 1. The prior for the parameters is uninformative (uniform). This implies that ```math p(x,z,\theta) = p(x,z|\theta) p(\theta) \propto p(x,z|\theta) ``` 2. A factorization constraint ```math q(z,\theta) = q(z) q(\theta) ``` 3. The posterior for the parameters is a delta function: ```math q(\theta) = \delta(\theta - \hat{\theta}) ``` Basically, these three assumptions turn VFE minimization into maximum likelihood estimation for the parameters ``\theta`` and the VFE simplifies to ```math \begin{align*} F[q,\theta] = \sum_z q(z) \log \frac{q(z)}{p(x,z|\theta)} \end{align*} ``` The EM algorithm minimizes this FE by iterating (iteration counter: ``i``) over ```math \begin{align} \mathcal{L}^{(i)}(\theta) &= \sum_z \overbrace{p(z|x,\theta^{(i-1)})}^{q^{(i)}(z)} \log p(x,z|\theta) \tag{the E-step} \\ \theta^{(i)} &= \arg\max_\theta \mathcal{L}^{(i)}(\theta) \tag{the M-step} \end{align} ``` These choices are optimal for the given FE functional. In order to see this, consider the two decompositions ```math \begin{align*} F[q,\theta] &= \underbrace{-\sum_z q(z) \log p(x,z|\theta)}_{\text{energy}} - \underbrace{\sum_z q(z) \log \frac{1}{q(z)}}_{\text{entropy}} \qquad &&\text{(EE)}\\ &= \underbrace{\sum_z q(z) \log \frac{q(z)}{p(z|x,\theta)}}_{\text{divergence}} - \underbrace{\log p(x|\theta)}_{\text{log-likelihood}} \qquad &&\text{(DE)} \end{align*} ``` The DE decomposition shows that the FE is minimized for the choice ``q(z) := p(z|x,\theta)``. Also, for this choice, the FE equals the (negative) log-evidence (, which is this case simplifies to the log-likelihood). The EE decomposition shows that the FE is minimized wrt ``\theta`` by minimizing the energy term. The energy term is computed in the E-step and optimized in the M-step. * Note that in the EM literature, the energy term is often called the *expected complete-data log-likelihood*.) In order to execute the EM algorithm, it is assumed that we can analytically execute the E- and M-steps. For a large set of models (including models whose distributions belong to the exponential family of distributions), this is indeed the case and hence the large popularity of the EM algorithm. The EM algorihm imposes rather severe assumptions on the FE (basically approximating Bayesian inference by maximum likelihood estimation). Over the past few years, the rise of Probabilistic Programming languages has dramatically increased the range of models for which the parameters can by estimated autmatically by (approximate) Bayesian inference, so the popularity of EM is slowly waning. (More on this in the Probabilistic Programming lessons). Bishop (2006) works out EM for the GMM in section 9.2. """Ù$d208f60e-56ea-4767-bd18-f29a853b7536„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$d208f60e-56ea-4767-bd18-f29a853b7536«code_folded¤codeÙ3const cluster_colors = color_list(:seaborn_bright6)Ù$26c7696e-d294-11ef-25f2-dbc0946c0858„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c7696e-d294-11ef-25f2-dbc0946c0858«code_foldedäcodeÙ¡md""" Below we exemplify training of a Gaussian Mixture Model on the Old Faithful data set by VFE minimization, with the constraints as specified above. """Ù$58bd0d43-743c-4745-b353-4a89b35e85ba„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$58bd0d43-743c-4745-b353-4a89b35e85ba«code_folded¤codeÙ&using Distributions, Plots, StatsPlotsÙ$b91bc3b6-b815-4942-b297-c0e2b4b99654„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$b91bc3b6-b815-4942-b297-c0e2b4b99654«code_foldedäcodeÚQhide_solution( md""" Let's start with a prior estimate ``\theta^{(i-1)}`` and we want to minimize the free energy functional wrt ``q``. This leads to ```math \begin{align*} q^{(i)}(z) &= \arg\min_q F[q](\theta^{(i-1)}) \\ &= \arg\min_q \sum_z q(z) \log \frac{q(z)}{p(D,z|\theta^{(i-1)})} \\ &= \arg\min_q \sum_z q(z) \log \frac{q(z)}{p(z|D,\theta^{(i-1)}) \cdot p(D|\theta^{(i-1)})} \\ &= p(z|D,\theta^{(i-1)}) \end{align*} ``` Next, we use ``q^{(i)}(z)=p(z|D,\theta^{(i-1)})`` and minimize the free energy w.r.t. ``\theta``, leading to ```math \begin{align*} \theta^{(i)} &= \arg\min_\theta F[q^{(i)}](\theta) \\ &= \arg\min_\theta \sum_z p(z|D,\theta^{(i-1)}) \log \frac{p(z|D,\theta^{(i-1)})}{p(D,z|\theta)} \\ &= \arg\max_\theta \sum_z \underbrace{p(z|D,\theta^{(i-1)})}_{q^{(i)}(z)} \log p(D,z|\theta) \end{align*} ``` """)Ù$87d94630-c90b-4379-91bd-88641ee7b508„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$87d94630-c90b-4379-91bd-88641ee7b508«code_foldedäcodeÙ—md""" ### Implementation _Reading this lecture online? Click **"View code"** in the top right to read the implementation of this visualisation._ """Ù$56bea391-b812-4fc4-8f27-fcb4cb984cf4„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$56bea391-b812-4fc4-8f27-fcb4cb984cf4«code_foldedäcode¹exercises(header_level=1)Ù$de0c41a3-6319-4ae3-8a1a-ae6935910fa3„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$de0c41a3-6319-4ae3-8a1a-ae6935910fa3«code_foldedäcodeÙa@bindname iteration_vfem Slider([0:10..., 10:10:max_iterations-1...]; default=2, show_value=true)Ù$a663d6d1-2d73-40c6-8a4c-9e41df74bc84„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$a663d6d1-2d73-40c6-8a4c-9e41df74bc84«code_foldedäcodeÙÓmd""" ##### Problem You are asked to build a density model for a data set ([Old Faithful](https://en.wikipedia.org/wiki/Old_Faithful), Bishop pg. 681) that clearly is not distributed as a single Gaussian: """Ù$26c5a1f6-d294-11ef-3565-39d027843fbb„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c5a1f6-d294-11ef-3565-39d027843fbb«code_foldedäcodeÙÐmd""" Classification problems with unobserved classes are called **Clustering** problems. In clustering problems, the learning algorithm needs to *discover the underlying classes from the observed data*. """Ù$2f490e1f-e495-4f55-a3f8-60d6fd716d4e„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$2f490e1f-e495-4f55-a3f8-60d6fd716d4e«code_foldedäcodeÚ®md""" #### The Expectation-Maximization (EM) algorithm (**) Consider a model ``p(x,z|\theta)``, where ``D=\{x_1,x_2,\ldots,x_N\}`` is observed, ``z`` are unobserved variables, and ``\theta`` are parameters. The **Expectation-Maximization** (EM) algorithm estimates the parameters by iterating over the following two equations (``i`` is the iteration index): ```math \begin{align*} q^{(i)}(z) &= p(z|D,\theta^{(i-1)}) \\ \theta^{(i)} &= \arg\max_\theta \sum_z q^{(i)}(z) \cdot \log p(D,z|\theta) \end{align*} ``` Prove that this algorithm minimizes the Free Energy functional ```math \begin{align*} F[q](\theta) = \sum_z q(z) \log \frac{q(z)}{p(D,z|\theta)} \end{align*} ``` """Ù$26c796c8-d294-11ef-25be-17dcd4a9d315„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c796c8-d294-11ef-25be-17dcd4a9d315«code_foldedäcodeÚTmd""" The generated figure resembles Figure 10.6 in Bishop. The plots show VFEM results for a GMM of ``K = 6`` Gaussians applied to the Old Faithful data set. The ellipses denote the two standard-deviation density contours for each of the components, and the color coding of the data points reflects the "soft" class label assignments. """Ù$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$98a0ed70-a627-48d6-a1f8-3dec7aba2bb2«code_foldedäcodeÚ@function updateMeanPrecisionPi(m_0,β_0,W_0,ν_0,α_0,r) #variational maximisation function m = Array{Float64}(undef,2,K) #mean of the clusters β = Array{Float64}(undef,K) #precision scaling for Gausian distribution W = Array{Float64}(undef,2,2,K) #precision prior for Wishart distributions ν = Array{Float64}(undef,K) #degrees of freedom parameter for Wishart distribution α = Array{Float64}(undef,K) #Dirichlet distribution parameter for k=1:K sst = sufficientStatistics(X,r,k) α[k] = α_0[k] + sst[1]; β[k] = β_0[k] + sst[1]; ν[k] = ν_0[k] .+ sst[1] m[:,k] = (1/β[k])*(β_0[k].*m_0[:,k] + sst[1].*sst[2]) W[:,:,k] = inv(inv(W_0[:,:,k])+sst[3]*sst[1] + ((β_0[k]*sst[1])/(β_0[k]+sst[1])).*(sst[2]-m_0[:,k])*(sst[2]-m_0[:,k])') end return m,β,W,ν,α endÙ$26c867d8-d294-11ef-2372-d75ed0bcc02d„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c867d8-d294-11ef-2372-d75ed0bcc02d«code_foldedäcodeÙ¡md""" We'll perform clustering on the data set from the [challenge](#challenge_hello) by fitting a GMM consisting of two Gaussians using the EM algorithm. """Ù$26c8160c-d294-11ef-2a74-6f7009a7c51e„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c8160c-d294-11ef-2a74-6f7009a7c51e«code_foldedäcode¼md""" # Optional Slides """Ù$26c64174-d294-11ef-2bbc-ab1a84532311„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c64174-d294-11ef-2bbc-ab1a84532311«code_foldedäcodeÚðmd""" There is no known conjugate prior for the latent variables in the GMM likelihood. Therefore, Bayes rule does not yield a closed-form expression for the posterior over the latent variables: ```math \underbrace{p(\{z_{nk}\},\{\mu_k,\Sigma_k,\pi_k\} | D)}_{\text{posterior (no analytical solution)}} \propto \underbrace{p(D\,|\,\{z_{nk}\},\{\mu_k,\Sigma_k,\pi_k\})}_{\text{likelihood}} \cdot \underbrace{p( \{z_{nk}\},\{\mu_k,\Sigma_k,\pi_k\} )}_{\text{prior (no known conjugate)}} ``` """Ù$208ba1bb-a4bf-4b8c-93d2-0d6c6c8d16d4„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$208ba1bb-a4bf-4b8c-93d2-0d6c6c8d16d4«code_foldedäcodeÚ„hide_solution( md""" We see here an example of "precision-weighted means add" when two sources of information are fused, just like precision-weighted means add when two Gaussians are multiplied, eg a prior and likelihood. In this case, the prior is ``m_0`` and the likelihood estimate is ``\bar{x}``. ``\beta_0`` can be interpreted as the number of pseudo-observations in the prior. """)Ù$26c6f63c-d294-11ef-1090-e9238dd6ad3f„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c6f63c-d294-11ef-1090-e9238dd6ad3f«code_foldedäcodeÚmd""" ## Constrained VFE Minimization It is common to add simplifying constraints to an optimization problem to make a difficult optimization task tractible. This is also standard practice when approximating Bayesian inference by FE minimization. There are three important cases of adding constraints to the VFE functional that often alleviate the VFE minimization task: - form constraints on ``q(z)`` - factorization constraints on ``q(z)`` - other (ad hoc) constraints We will shortly discuss these simplifications below. """Ù$aea77d69-9ecd-4be0-b6fd-c944d27d68df„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$aea77d69-9ecd-4be0-b6fd-c944d27d68df«code_foldedäcodeÚ»md""" ##### 1. Form constraints For almost every practical setting, we constrain the posterior ``q(z)`` to belong to a **specific parameterized family** of probability distributions, e.g., ```math q(z) = \mathcal{N}\left( z | \mu, \Sigma \right)\,. ``` In this case, the *functional* minimization problem for ``F[q]`` simplifies to the minimization of an ordinary *function* ```math F(\mu,\Sigma) = \int \mathcal{N}\left( z | \mu, \Sigma \right) \log \frac{\mathcal{N}\left( z | \mu, \Sigma \right)}{p(x,z)}\mathrm{d}z ``` with respect to the parameters ``\mu`` and ``\Sigma``. We can often use standard gradient-based optimization methods to minimize the function ``F(\mu,\Sigma)\,.`` """Ù$26c82f16-d294-11ef-0fe1-07326b56282f„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$26c82f16-d294-11ef-0fe1-07326b56282f«code_foldedäcodeÚ nmd""" ## VFE Minimization with Mean-field Factorization Constraints: $(HTML("the CAVI Approach")) Let's work out VFE minimization with additional mean-field constraints (=full factorization) constraints: ```math q(z) = \prod_{j=1}^m q_j(z_j)\,. ``` In other words, the posteriors for ``z_j`` are all considered independent. This is a strong constraint but often leads to good solutions. Given the mean-field constraints, it is possible to derive the following expression for the $(HTML("optimal solutions")) ``q_j^*(z_j)``, for ``j=1,\ldots,m``: ```math \begin{align} \log q_j^*(z_j) &\propto \mathrm{E}_{q_{-j}^*}\left[ \log p(x,z) \right] \\ &= \underbrace{\sum_{z_{-j}} q_{-j}^*(z_{-j}) \underbrace{\log p(x,z)}_{\text{"field"}}}_{\text{"mean field"}} \end{align} ``` where we defined ``q_{-j}^*(z_{-j}) \triangleq q_1^*(z_1)q_2^*(z_2)\cdots q_{j-1}^*(z_{j-1})q_{j+1}^*(z_{j+1})\cdots q_m^*(z_m)``. **Proof** (from [Blei, 2017](https://doi.org/10.1080/01621459.2017.1285773)): We first rewrite the FE as a function of ``q_j(z_j)`` only: ```math F[q_j] = \mathbb{E}_{q_{j}}\left[ \mathbb{E}_{q_{-j}}\left[ \log p(x,z_j,z_{-j})\right]\right] - \mathbb{E}_{q_j}\left[ \log q_j(z_j)\right] + \mathtt{const.}\,, ``` where the constant holds all terms that do not depend on ``z_j``. This expression can be written as ```math F[q_j] = \sum_{z_j} q_j(z_j) \log \frac{q_j(z_j)}{\exp\left( \mathbb{E}_{q_{-j}}\left[ \log p(x,z_j,z_{-j})\right]\right)} ``` which is a KL-divergence that is minimized by Eq. B-10.9. (end proof) This is not yet a full solution to the FE minimization task since the solution ``q_j^*(z_j)`` depends on expectations that involve other solutions ``q_{i\neq j}^*(z_{i \neq j})``, and each of these other solutions ``q_{i\neq j}^*(z_{i \neq j})`` depends on an expection that involves ``q_j^*(z_j)``. In practice, we solve this chicken-and-egg problem by an iterative approach: we first initialize all ``q_j(z_j)`` (for ``j=1,\ldots,m``) to an appropriate initial distribution and then cycle through the factors in turn by solving eq.B-10.9 and update ``q_{-j}^*(z_{-j})`` with the latest estimates. (See [Blei, 2017](https://doi.org/10.1080/01621459.2017.1285773), Algorithm 1, p864). This algorithm for approximating Bayesian inference is known **Coordinate Ascent Variational Inference** (CAVI). """Ù$87715fcd-c92e-4bfa-8b0a-15e469548f3d„¨metadataƒ¨disabled©show_logsîskip_as_script§cell_idÙ$87715fcd-c92e-4bfa-8b0a-15e469548f3d«code_foldedäcodeÚ$keyconcept("", md""" For a model ``p(x,z) = p(x|z) p(x)``, the **variational free energy** functional ```math F[q] = \underbrace{ \int q(z) \log \frac{q(z)}{p(z)} \mathrm{d}z }_{\text{complexity}} - \underbrace{\int q(z) \log p(x|z) \mathrm{d}z}_{\text{accuracy}} ``` is considered a functional of a variational posterior ``q(z)`` over the latent variables ``z``. Minimizing ``F[q]`` accomplishes **approximate Bayesian inference** by ```math \begin{align*} \hat{q}(z) &\approx p(z|x) \\ F[\hat{q}] &\approx -\log p(x) \end{align*} ``` """)´last_hot_reload_timeË©shortpathÙ Latent Variable Models and VB.jl¥nbpkgŠ­busy_packages�Ù,waiting_for_permission_but_probably_disabled§enabledðterminal_outputs‰­LinearAlgebraÚp Waiting for other notebooks to finish Pkg operations... === Resolving... ===  Project No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Project.toml`  Manifest No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Manifest.toml` Instantiating... === Precompiling... === Waiting for notebook process to start... Done. Starting precompilation...¦PDMatsÚp Waiting for other notebooks to finish Pkg operations... === Resolving... ===  Project No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Project.toml`  Manifest No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Manifest.toml` Instantiating... === Precompiling... === Waiting for notebook process to start... Done. Starting precompilation...¦RandomÚp Waiting for other notebooks to finish Pkg operations... === Resolving... ===  Project No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Project.toml`  Manifest No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Manifest.toml` Instantiating... === Precompiling... === Waiting for notebook process to start... Done. Starting precompilation...°SpecialFunctionsÚp Waiting for other notebooks to finish Pkg operations... === Resolving... ===  Project No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Project.toml`  Manifest No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Manifest.toml` Instantiating... === Precompiling... === Waiting for notebook process to start... Done. Starting precompilation...ªnbpkg_syncÚp Waiting for other notebooks to finish Pkg operations... === Resolving... ===  Project No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Project.toml`  Manifest No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Manifest.toml` Instantiating... === Precompiling... === Waiting for notebook process to start... Done. Starting precompilation...²BmlipTeachingToolsÚp Waiting for other notebooks to finish Pkg operations... === Resolving... ===  Project No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Project.toml`  Manifest No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Manifest.toml` Instantiating... === Precompiling... === Waiting for notebook process to start... Done. Starting precompilation...­DistributionsÚp Waiting for other notebooks to finish Pkg operations... === Resolving... ===  Project No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Project.toml`  Manifest No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Manifest.toml` Instantiating... === Precompiling... === Waiting for notebook process to start... Done. Starting precompilation...¥PlotsÚp Waiting for other notebooks to finish Pkg operations... === Resolving... ===  Project No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Project.toml`  Manifest No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Manifest.toml` Instantiating... === Precompiling... === Waiting for notebook process to start... Done. Starting precompilation...ªStatsPlotsÚp Waiting for other notebooks to finish Pkg operations... === Resolving... ===  Project No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Project.toml`  Manifest No packages added to or removed from `~/.julia/scratchspaces/c3e4b0f8-55cb-11ea-2926-15256bba5781/pkg_envs/env_zgtbzjsicr/Manifest.toml` Instantiating... === Precompiling... === Waiting for notebook process to start... Done. Starting precompilation...¶waiting_for_permission·restart_recommended_msgÀ´restart_required_msgÀ²installed_versionsŠ­LinearAlgebra¦stdlib¦PDMats§0.11.41¸__internal_julia_version¦1.13.3¦Random¦stdlib°SpecialFunctions¥2.9.1²BmlipTeachingTools¥1.4.1­Distributions¨0.25.132¥Plots¦1.41.7ªStatsPlots¦0.15.8Ù!__internal_julia_manifest_version¦1.13.3¯install_time_nsÎX•u:¬instantiatedípluto_version¦v1.1.0