<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.2">Jekyll</generator><link href="http://bllguo.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="http://bllguo.github.io/" rel="alternate" type="text/html" /><updated>2022-05-17T21:45:41+00:00</updated><id>http://bllguo.github.io/feed.xml</id><title type="html">Yet Another ML Blog</title><subtitle>data science and ML theory</subtitle><entry><title type="html">Neural Network Basics</title><link href="http://bllguo.github.io/Neural-network-basics/" rel="alternate" type="text/html" title="Neural Network Basics" /><published>2019-10-26T00:00:00+00:00</published><updated>2019-10-26T00:00:00+00:00</updated><id>http://bllguo.github.io/Neural-network-basics</id><content type="html" xml:base="http://bllguo.github.io/Neural-network-basics/">&lt;p&gt;These days there are too many deep learning resources and tutorials out there to count! Regardless, it would be remiss to gloss over the basics in a blog such as this. Let us quickly run through the fundamental ideas behind artificial neural networks.&lt;/p&gt;

&lt;h2 id=&quot;1-setup&quot;&gt;1. Setup&lt;/h2&gt;

&lt;p&gt;Recall that linear regression and classification models can be expressed as:&lt;/p&gt;

\[y(x, w) = f(\sum_{j=1}^M w_j\phi_j(x))\]

&lt;p&gt;In the linear regression case, $f(.)$ is merely the identity. In classification, it is a nonlinear activation function, such as the sigmoid $\sigma(.)$ in logistic regression (for instance, in binary classification, we set $p(C_1|x) = y(\phi) = \sigma(w^T\phi(x)))$). What if we extend this model such that the basis functions $\phi_j(x)$ themselves are parameterized, alongside the existing coefficients $w_j$? In neural networks, we will do just that, using a series of functional transformations that we organize into “layers.”&lt;/p&gt;

&lt;p&gt;Suppose we have $D$-dimensional data $X$. We start with the first layer by defining $M^{(1)}$ linear combinations of the components of $X$ as follows:&lt;/p&gt;

\[a_j = \sum_{i=0}^D w_{ji}^{(1)}x_i\]

&lt;p&gt;where $j = 1, …, M^{(1)}$. These $a_j$ are the activations. The $w_{ji}^{(1)}$ are the weights, with the $w_{j0}^{(1)}$ being the biases (we roll it in by adding a corresponding $x_0 = 1$). The layer number is denoted by superscript. Take note that $M^{(1)}$ is a hyperparameter we have chosen for the number of activations - linear combinations of the inputs $X$ - in the first layer. Now, we apply a &lt;em&gt;differentiable&lt;/em&gt; and nonlinear activation function $h(.)$ to the activations:&lt;/p&gt;

\[z_j = h(a_j)\]

&lt;p&gt;Think of the $z_j$ as the outputs of the nonlinear basis functions $\phi_j(x)$ in normal linear models. They are known as the hidden units, because we do not typically have visibility into their values - they are directly fed into the next layer.&lt;/p&gt;

&lt;p&gt;Let’s take stock again. We fed the original data $x_0=1, x_1, …, x_D$ into the first layer. They were linearly combined into $M^{(1)}$ activations $a_j$ according to the weights $w_{ji}^{(1)}$, then passed through a nonlinear activation function $h(.)$. So the first layer spat out $z_j$, $M^{(1)}$ values in total.&lt;/p&gt;

&lt;p&gt;On to the next layer. We simply repeat the process with our hidden units. Now the inputs to the layer are our $z_j$:&lt;/p&gt;

\[a_k = \sum_{j=0}^{M^{(1)}} w_{kj}^{(2)}z_j\]

&lt;p&gt;where $k = 1, …, M^{(2)}$. $M^{(2)}$ is a hyperparameter we have chosen for the number of activations in the &lt;em&gt;second&lt;/em&gt; layer.&lt;/p&gt;

&lt;p&gt;As you may have guessed, we can continue in this way ad infinitum. But let us stick to two layers for now. The output layer, layer 2 in this case, needs to be treated differently compared to the inner, hidden layers. Whereas there were no real restrictions on choosing $M^{(1)}$ other than practical considerations, the choice of $M^{(2)}$ matters depending on the output we are expecting. For instance, in a regression task with a single target, we want a single value from the neural network. So $M^{(2)} = 1$. And we would simply use the identity for the activation function such that $y_k = a_k$. In multiclass classification, we would want to output a $p$-dimensional vector where $p$ is the number of classes. Then we can use a softmax for the activation function $\sigma_i(z) = \frac{exp(z_i)}{\sum_j^p exp(z_j)}$ to squash it into class probabilities.&lt;/p&gt;

&lt;p&gt;So overall, this two-layer network looks like:&lt;/p&gt;

\[y(x, w) = \sigma(\sum_{j=0}^{M^{(1)}}w_{kj}^{(2)}h(\sum_{i=0}^D w_{ji}^{(1)}x_i))\]

&lt;p&gt;Notice that if all the activation functions of all the hidden units are linear, we simply have a composition of linear transformations. This defeats the purpose; in this case we can always simply represent the network as a linear transformation without the intermediate transformations. So the nonlinearity of the activation functions is crucial.&lt;/p&gt;

&lt;p&gt;We call these &lt;em&gt;feed-forward&lt;/em&gt; networks because evaluation and computation of the network propagates strictly forward. There must be no closed directed cycles, ensuring that the outputs are deterministically determined vis-à-vis the inputs. This latter point also marks the distinction between neural networks and probabilistic graphical models, as the nodes, or neurons, are deterministic rather than probabilistic.&lt;/p&gt;

&lt;p&gt;Finally - it has been shown that neural networks with at least one hidden layer are universal approximators. That is, they can approximate any continuous function. Of course, the difficulty is in finding the appropriate set of parameters; in practice deeper networks have a much easier time representing complex nonlinearities.&lt;/p&gt;

&lt;h2 id=&quot;2-training&quot;&gt;2. Training&lt;/h2&gt;

&lt;p&gt;Now, how can we find the weight vector $w$ that minimizes $E(w)$? If we take a step from $w$ to $w+\delta w$, the change in $E(w)$ is $\delta E \approx \delta w^T\nabla E(w)$. Clearly at the minimum of the error function, $\nabla E(w) = 0$. Of course in general we cannot hope to find an analytical solution to $\nabla E(w) = 0$, so we will use numeric methods. These generally take the form of:&lt;/p&gt;

\[w^{(\tau + 1)} = w^{(\tau)} - \eta\Delta E(w^{(\tau)})\]

&lt;p&gt;$\tau$ is the iteration number. Optimization methods differ in specification of $\Delta w^{(\tau)}$, but many use the gradient $\nabla E(w)$.&lt;/p&gt;

&lt;p&gt;The simplest method is gradient descent, where at every iteration we take a small step in the negative gradient direction - the direction of greatest rate of decrease of the error function. In &lt;em&gt;batch&lt;/em&gt; gradient descent, we compute $\nabla E$ over the entire training set in every iteration. There are actually more efficient methods than gradient descent, such as conjugate gradient descent, in which the gradient vectors are orthogonalized against each other (using Gram-Schmidt). That is, instead of stepping in the direction of the gradient, we take a step in a direction such that we avoid having to step in the same direction in future iterations. Quasi-Newton methods are also more robust than simple batch gradient descent. They make use of Newton’s method, but come with the drawback of having to compute the inverse Hessian.&lt;/p&gt;

&lt;p&gt;Many error functions can be represented as a sum over individual observations, such as in situations minimizing the negative log likelihood over i.i.d. data. Stochastic gradient descent, otherwise known as online gradient descent, exploits this to update the weights one observation at a time:&lt;/p&gt;

\[E(w) = \sum_n E_n(w)\]

\[w^{(\tau + 1)} = w^{(\tau)} - \eta\Delta E_n(w^{(\tau)})\]

&lt;p&gt;This has the benefit of being able to be used in online situations, as well as being less prone to being trapped in local minima. A minima for the entire dataset will not be a minima for each observation.&lt;/p&gt;

&lt;h2 id=&quot;3-evaluating-ew-via-backpropagation&quot;&gt;3. Evaluating $E(w)$ via Backpropagation&lt;/h2&gt;

&lt;p&gt;How can we efficiently compute $E(w)$? This is done via the process of error backpropagation.&lt;/p&gt;

&lt;p&gt;Consider a simple linear model, where the outputs $y_k$ are linear combinations of the inputs $x_i$:&lt;/p&gt;

\[y_k = \sum_i w_{ki}x_i\]

&lt;p&gt;Let the error function be:&lt;/p&gt;

\[E_n = \frac{1}{2}\sum_k (y_{nk} - t_{nk})^2\]

&lt;p&gt;where $y_{nk} = y_k(x_n, w)$. The partial with respect to weight $w_{ji}$:&lt;/p&gt;

\[\frac{\partial E_n}{\partial w_{ji}} = \frac{\partial E_n}{\partial y_{nj}}\frac{\partial y_{nj}}{\partial w_{ji}}\]

\[\frac{\partial E_n}{\partial w_{ji}} = (y_{nj} - t_{nj})x_{ni}\]

&lt;p&gt;In a neural network, each neuron computes:&lt;/p&gt;

\[a_j = \sum_i w_{ji}z_i\]

\[z_j = h(a_j)\]

&lt;p&gt;where $h(.)$ is some nonlinearity. Successive application of these equations is &lt;em&gt;forward&lt;/em&gt; propagation of information through the network. Now consider evaluating $\frac{\partial E_n}{\partial w_{ji}}$. $E_n$ depends on $w_{ji}$ through the activation $a_j$:&lt;/p&gt;

\[\frac{\partial E_n}{\partial w_{ji}} = \frac{\partial E_n}{\partial a_{nj}}\frac{\partial a_{nj}}{\partial w_{ji}}\]

&lt;p&gt;Going forward we will omit the $n$-subscripts.&lt;/p&gt;

&lt;p&gt;Let the errors $\delta$ be defined as:&lt;/p&gt;

\[\delta_j = \frac{\partial E_n}{\partial a_{j}}\]

&lt;p&gt;We also know that:&lt;/p&gt;

\[\frac{\partial a_{j}}{\partial w_{ji}} = z_i\]

&lt;p&gt;since $a_j = \sum_i w_{ji}z_i$. So the partial of the untransformed activation w.r.t the weights is the input from the previous layer.&lt;/p&gt;

&lt;p&gt;Thus:&lt;/p&gt;

\[\frac{\partial E_n}{\partial w_{ji}} = \delta_jz_i\]

&lt;p&gt;Expanding to multiple layers:&lt;/p&gt;

&lt;p&gt;For the output layer’s neurons, we know that:&lt;/p&gt;

\[\delta_k = \frac{\partial E_n}{\partial w_{ki}} = y_k - t_k\]

&lt;p&gt;For the hidden layers, we simply need to apply the chain rule successively:&lt;/p&gt;

\[\delta_j = \frac{\partial E_n}{\partial w_{ji}} = \sum_k \frac{\partial E_n}{\partial a_{k}}\frac{\partial a_{k}}{\partial a_{j}}\]

\[\delta_j = \sum_k \delta_k\frac{\partial a_{k}}{\partial a_{j}}\]

&lt;p&gt;It is then easy to show:&lt;/p&gt;

\[\delta_j = h'(a_j)\sum_k w_{kj}\delta_k\]

&lt;p&gt;That is, $\delta_j$ for a hidden unit can be obtained by using the $\delta$’s of the neurons in the following layer (figure from &lt;a href=&quot;https://www.microsoft.com/en-us/research/people/cmbishop/prml-book/&quot;&gt;Bishop&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/backprop.png&quot; alt=&quot;backprop&quot; /&gt;&lt;/p&gt;

&lt;p&gt;From here, with all the $\delta$s computed, we can use whichever update rule we wish in order to update the corresponding weights $w$.&lt;/p&gt;</content><author><name></name></author><summary type="html">These days there are too many deep learning resources and tutorials out there to count! Regardless, it would be remiss to gloss over the basics in a blog such as this. Let us quickly run through the fundamental ideas behind artificial neural networks.</summary></entry><entry><title type="html">Classification</title><link href="http://bllguo.github.io/Classification/" rel="alternate" type="text/html" title="Classification" /><published>2019-10-22T00:00:00+00:00</published><updated>2019-10-22T00:00:00+00:00</updated><id>http://bllguo.github.io/Classification</id><content type="html" xml:base="http://bllguo.github.io/Classification/">&lt;p&gt;I realize that the order of posts here seems without rhyme or reason. I have no justification to offer. But these posts are better late than never! Here we proceed to lay another block of the foundation by discussing classification, logistic regression, and finally, generalized linear models.&lt;/p&gt;

&lt;h2 id=&quot;1-the-classification-problem&quot;&gt;1. The Classification Problem&lt;/h2&gt;

&lt;p&gt;In classification, we wish to assign one of several classes $C_k$ to input data $x$.&lt;/p&gt;

&lt;p&gt;The classification problem can be broken down into two stages, inference and decision.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Inference stage: use the training data to learn the conditional posterior probabilities $p(C_k|x)$. Here we are considering the priors as $p(C_k)$. Thus, by Bayes’ theorem:&lt;/p&gt;

\[p(C_k|x) = \frac{p(x|C_k)p(C_k)}{p(x)}\]
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Decision stage: use these posterior probabilities to assign classes.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There are three general approaches to classification, based on how they approach these stages.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Generative&lt;/p&gt;

    &lt;p&gt;Determine the class-conditional probability densities $p(x|C_k)$ for each class, as well as the priors $p(C_k)$. From there, use Bayes’ theorem to compute $p(C_k|x)$:&lt;/p&gt;

\[p(C_k|x) = \frac{p(x|C_k)p(C_k)}{p(x)} = \frac{p(x|C_k)p(C_k)}{\sum_k p(x|C_k)p(C_k)}\]

    &lt;p&gt;It is generative in the sense that we are also modeling the distribution of the inputs $x$, which allows us to generate synthetic $x$. This is demanding since we need to find the joint distribution over $x, C_k$ (the class priors are easy since we can estimate simply from the class proportions in the training set). When $x$ is of high dimensionality, we may need a large dataset to do this. Having the marginal density $p(x)$ can also be useful for outlier detection, where we identify points that are low probability under the model and thus have poor predictions from the model.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Discriminative&lt;/p&gt;

    &lt;p&gt;Determine the posteriors $p(C_k|x)$ directly, then use decision theory to assign classes. Discriminative approaches require less computational power, less parameters, and less data, and we still get to have the posteriors $p(C_k|x)$.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Discriminant&lt;/p&gt;

    &lt;p&gt;Determine a discriminat function $f(x)$ which directly maps $x$ to a class label. Discriminant approaches lose the probabilistic outputs entirely.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We will be skipping over discriminants in the following discussion.&lt;/p&gt;

&lt;h2 id=&quot;2-the-generative-approach&quot;&gt;2. The Generative Approach&lt;/h2&gt;

&lt;p&gt;Let us start with the simplest case, binary classification. Recall we want to model the class-conditional densities $p(x|C_k)$ as well as the priors $p(C_k)$ in order to compute the posteriors $p(C_k|x)$ via Bayes’ theorem.&lt;/p&gt;

\[p(C_1|x) = \frac{p(x|C_1)p(C_1)}{p(x|C_1)p(C_1) + p(x|C_2)p(C_2)}\]

&lt;p&gt;Now generalizing to multiclass:&lt;/p&gt;

\[p(C_k|x) = \frac{p(x|C_k)p(C_k)}{\sum_j p(x|C_j)p(C_j)}\]

\[p(C_k|x) = \frac{\exp(a_k)}{\sum_j\exp(a_j)}\]

&lt;p&gt;where $a_k = \ln{p(x|C_k)p(C_k)}$. The form of the posterior is the softmax function applied to $a_k$.&lt;/p&gt;

&lt;p&gt;We can now throw in assumptions about the class-conditional densities $p(x|C_k)$ and solve for the posteriors.&lt;/p&gt;

&lt;p&gt;For example, suppose all of our features are binary and discrete. If there are $m$ features, and $K$ classes, we have $K \times 2^m$ possible values of $(x, y)$ to enumerate in order to describe the discrete distribution. This is clearly infeasible at high dimensionality. This only gets worse if we relax the binary condition.&lt;/p&gt;

&lt;p&gt;A simplified representation can be attained by assuming conditional independence of the features given the class $C_k$:&lt;/p&gt;

\[p(x|C_k) = \prod_j P(x_j|C_k)\]

&lt;p&gt;Then we can compute the posterior class probabilities like so:&lt;/p&gt;

\[\text{arg max}_c\text{ }p(C_k=c|x) = P(C_k=c)\prod_j P(x_j|C_k=c)\]

&lt;p&gt;This is called the naive Bayes assumption.&lt;/p&gt;

&lt;h2 id=&quot;3-discriminative-models-and-logistic-regression&quot;&gt;3. Discriminative Models and Logistic Regression&lt;/h2&gt;

&lt;p&gt;In the generative approach, we can use maximum likelihood to estimate the parameters of the class-conditional densities as well as the class priors, under specific assumptions over the class-conditional densities. From there we can apply Bayes’ theorem to find the posterior probabilities.&lt;/p&gt;

&lt;p&gt;We can also exploit the functional form of our model for the posterior probabilities, and use maximum likelihood to determine its parameters directly, without needing the class-conditionals or priors. Logistic regression is one example.&lt;/p&gt;

&lt;h3 id=&quot;31-binary&quot;&gt;3.1 Binary&lt;/h3&gt;

&lt;p&gt;Let’s start with the binary case once more.&lt;/p&gt;

&lt;p&gt;Recall the general formulation of the posterior:&lt;/p&gt;

\[p(C_1|x) = \frac{p(x|C_1)p(C_1)}{p(x|C_1)p(C_1) + p(x|C_2)p(C_2)}\]

&lt;p&gt;Notice that this can be expressed as:&lt;/p&gt;

\[p(C_1|x) = \sigma(a)\]

\[a = \ln{\frac{p(x|C_1)p(C_1)}{p(x|C_2)p(C_2)}}\]

&lt;p&gt;$\sigma$ is the sigmoid function:&lt;/p&gt;

\[\sigma(x) = \frac{1}{1 + e^{-x}}\]

&lt;p&gt;So instead of looking at the class-conditional density or the prior density, we roll that all up into the sigmoid. Let:&lt;/p&gt;

\[a = w^Tx\]

\[p(C_1|x) = \sigma(a) = \sigma(w^Tx)\]

&lt;p&gt;Then, the likelihood function can be expressed in terms of $p(C_1|x)$ (let $y \in [0, 1]$):&lt;/p&gt;

\[p(y|w) = \prod_n \sigma(w^Tx_n)^{y_n}(1-\sigma(w^Tx_n))^{1-y_n}\]

&lt;p&gt;Why can we assume this linear form for $a$? This is in fact a key point - this assumption implies a deeper assumption, that the target $y$ has a distribution in the exponential family.&lt;/p&gt;

&lt;p&gt;Taking the negative logarithm, we get the cross-entropy error function:&lt;/p&gt;

\[E(w) = -\log{(p(y|w))} = -\sum_n y_n\log{(\sigma(w^Tx_n))} + (1-y_n)\log{(1-\sigma(w^Tx_n))}\]

&lt;p&gt;Taking the gradient w.r.t $w$:&lt;/p&gt;

\[\nabla E(w) = \sum_n (\sigma(w^Tx_n) - y_n)x_n\]

&lt;p&gt;There is no closed-form solution here, but we can simply use gradient descent.&lt;/p&gt;

&lt;h3 id=&quot;32-multiclass&quot;&gt;3.2 Multiclass&lt;/h3&gt;

&lt;p&gt;To generalize to multiclass, let:&lt;/p&gt;

\[p(C_k|x) = f_k(x) = \frac{\exp(w^T_kx_k)}{\sum_j \exp(w^T_jx_j)}\]

&lt;p&gt;This is the softmax transformation.&lt;/p&gt;

&lt;p&gt;We use a 1-of-k coding scheme where $y_n$ for a feature vector $x_n$ is a vector with all elements equal to 0, except for element $k$.&lt;/p&gt;

&lt;p&gt;The likelihood takes the form:&lt;/p&gt;

\[p(Y|w_1, ..., w_K) = \prod_n\prod_kp(C_k|x_n)^{y_{n, k}} = \prod_n\prod_kf_k(x_n)^{y_{n, k}}\]

&lt;p&gt;$Y$ is a $N\times K$ matrix of target variables.&lt;/p&gt;

&lt;p&gt;The negative log gives us the cross-entropy error function:&lt;/p&gt;

\[E(w_1, ..., w_K) = -\log{p(Y|w_1, ..., w_K)} = \sum_n\sum_ky_{n, k}\log{f_k(x_n)}\]

&lt;p&gt;Keep in mind the constraint $\sum_ky_{n, k} = 1$ and take the gradient with respect to each $w_k$ to obtain the cross-entropy error function:&lt;/p&gt;

\[\nabla_{w_k} E(w_1, ..., w_K) = \sum_{n=1}^N(f_{n,k} - y_{n, k})x_n\]

&lt;h2 id=&quot;4-generalized-linear-models&quot;&gt;4. Generalized Linear Models&lt;/h2&gt;

&lt;p&gt;A generalized linear model is a model of the form:&lt;/p&gt;

\[y = f(w^T\phi)\]

&lt;p&gt;$f(.)$ is the activation function, and $f^{-1}(.)$ is the link function. In the GLM, $y$ is a nonlinear function of a linear combination of the inputs. Notice that linear and logistic regression satisfy this definition.&lt;/p&gt;

&lt;p&gt;The link function describes the association between the mean of the target, $y$, and the linear term $w^T\phi$. It &lt;em&gt;links&lt;/em&gt; them in such a way that the range of the transformed mean, $f^{-1}(y)$, is $(-\infty, \infty)$, which allows us to form the linear equation $y = f(w^T\phi)$ and solve using MLE. Take classification as an example - the target is $\in [0, 1]$ and so the untransformed $y$ is in the range $[0, 1]$.&lt;/p&gt;

&lt;h3 id=&quot;41-linear-regression-recap&quot;&gt;4.1 Linear Regression Recap&lt;/h3&gt;

&lt;p&gt;Now, let’s take a quick review of linear regression:&lt;/p&gt;

&lt;p&gt;Recall that for a linear regression model with Gaussian noise, the likelihood function is:&lt;/p&gt;

\[p(y|x, w, \sigma^2) = \prod_{i=1}^{N} N(y_i| w^Tx_i, \sigma^2)\]

&lt;p&gt;And the log likelihood is:&lt;/p&gt;

\[ln(p(y|x, w, \sigma^2)) = \sum_{i=1}^{N} ln(N(y_i| w^Tx_i, \sigma^2))\]

\[ln(p(y|x, w, \sigma^2)) = \frac{N}{2}ln\frac{1}{\sigma^2} - \frac{N}{2}ln(2\pi) - \frac{1}{2\sigma^2}E(w)\]

&lt;p&gt;where:&lt;/p&gt;

\[E(w) = \sum_{i=1}^{N} (y-w^Tx)^2\]

&lt;p&gt;which is the sum-of-squares error function.&lt;/p&gt;

&lt;p&gt;Take the partial derivative w.r.t $w$:&lt;/p&gt;

\[\nabla ln(p(y|x, w, \sigma^2)) = \frac{1}{\sigma^2}\sum_{i=1}^N (y_i - w^Tx_i)x_i^T\]

&lt;p&gt;Have you noticed something? In linear regression, binary logistic regression, &lt;em&gt;and&lt;/em&gt; multiclass logistic regression, the partial w.r.t $w$ of the error function takes the form $(y_i - \hat{y}_i)x_i$.&lt;/p&gt;

&lt;p&gt;This is no coincidence - this is a consequence of 1. assuming the target has a distribution from the exponential family, and 2. our choice of activation function.&lt;/p&gt;

&lt;h3 id=&quot;42-the-exponential-family&quot;&gt;4.2 The Exponential Family&lt;/h3&gt;

&lt;p&gt;The exponential family of distributions over $x$ given parameters $\eta$ is defined as:&lt;/p&gt;

\[p(x|\eta) = h(x)g(\eta)exp(\eta^Tu(x))\]

&lt;p&gt;Where $\eta$ are the &lt;em&gt;natural parameters&lt;/em&gt; and $u(x)$ is some function of $x$. $g(\eta)$ is a normalizing coefficient that ensures:&lt;/p&gt;

\[g(\eta)\int h(x)exp(\eta^Tu(x))dx = 1\]

&lt;p&gt;For simplicity, consider a restricted subclass of exponential family distributions, where $u(x)$ is the identity, and where we have introduced a scale parameter $s$ such that:&lt;/p&gt;

\[p(x|\eta, s) = \frac{1}{s}h(\frac{x}{s})g(\eta)exp(\frac{\eta x}{s})\]

&lt;h3 id=&quot;43-canonical-link-functions&quot;&gt;4.3 Canonical Link Functions&lt;/h3&gt;

&lt;p&gt;Now, let us assume that our target variable $t$ is in the exponential family. Then,&lt;/p&gt;

\[p(t|\eta, s) = \frac{1}{s}h(\frac{t}{s})g(\eta)exp(\frac{\eta t}{s})\]

&lt;p&gt;Consider taking the gradient of both sides with respect to $\eta$ and simplifying. We will arrive at:&lt;/p&gt;

\[E(t|\eta) = y = -s\frac{d}{d\eta}\ln g(\eta)\]

&lt;p&gt;Which shows us that $y$ and $\eta$ are related. Let this relationship be $\eta = \psi(y)$.&lt;/p&gt;

&lt;p&gt;Now go back and consider the log-likelihood for the model on $t$, assuming all observations have the same scale parameter.&lt;/p&gt;

\[\ln p(t|\eta, s) = \sum_{n=1}^N \ln p(t_n|\eta, s) = \sum_{n=1}^N (\ln g(\eta_n) _ \frac{\eta_nt_n}{s}) + \text{const}\]

&lt;p&gt;Take the derivative with respect to $w$:&lt;/p&gt;

\[\nabla_w \ln p(t|\eta, s) = \sum_{n=1}{N}(\frac{d}{d\eta_n}\ln g(\eta_n) + \frac{t_n}{s})\frac{d\eta_n}{dy_n}\frac{dy_n}{da_n}\nabla a_n\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;where $a_n = w^T\phi_n$. Now using $y = E(t&lt;/td&gt;
      &lt;td&gt;\eta)$, $\eta = \psi(y)$, and our earlier GLM definition $y_n = f(a_n)$:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[\nabla_w \ln p(t|\eta, s) = \sum_{n=1}{N}\frac{1}{s}(t_n-y_n)\psi'(y_n)f'(a_n)\phi_n)\]

&lt;p&gt;If we choose the link function $f^{-1}(y) = \psi(y)$, then $f(\psi(y)) = y$. Consequently:&lt;/p&gt;

\[f'(\psi)\psi'(y) = \frac{df}{d\psi}\frac{d\psi}{dy} = \frac{dy}{d\psi}\frac{d\psi}{dy} = 1\]

&lt;p&gt;Notice $a = f^{-1}(y)$, hence $a = \psi$, and therefore from the above:&lt;/p&gt;

\[\psi'(y_n)f'(a_n) = 1\]

&lt;p&gt;And the error function has reduced to a familiar form:&lt;/p&gt;

\[\nabla E(w) = \frac{1}{s}\sum_{n=1}^N(y_n-t_n)\phi_n\]

&lt;p&gt;The proper choice of link function - the canonical link function - takes our error function to this simple form, and also enforces $\eta = E(t)$. There are a number of other desirable statistical properties associated with the canonical link function.&lt;/p&gt;</content><author><name></name></author><summary type="html">I realize that the order of posts here seems without rhyme or reason. I have no justification to offer. But these posts are better late than never! Here we proceed to lay another block of the foundation by discussing classification, logistic regression, and finally, generalized linear models.</summary></entry><entry><title type="html">Regression</title><link href="http://bllguo.github.io/Regression/" rel="alternate" type="text/html" title="Regression" /><published>2019-10-19T00:00:00+00:00</published><updated>2019-10-19T00:00:00+00:00</updated><id>http://bllguo.github.io/Regression</id><content type="html" xml:base="http://bllguo.github.io/Regression/">&lt;p&gt;Let’s do a quick review of basic regression, to lay the framework for future posts. The goal of regression, one of the principal problems in supervised learning, is to predict the value(s) of one or more &lt;em&gt;continuous&lt;/em&gt; target variables $y$, given a corresponding vector of input variables $x$.&lt;/p&gt;

&lt;h2 id=&quot;1-setup&quot;&gt;1. Setup&lt;/h2&gt;

&lt;p&gt;Suppose we have a training dataset consisting of $n$ observations. The $i$-th observation is a ${x_i, y_i}$ pair, where $x_i$ is a $D$-dimensional vector of input variables and $y_i$ the target variable (we shall assume one target, going forward). We would like to be able to predict $y$ when given some new value of $x$.&lt;/p&gt;

&lt;p&gt;The simple linear model involves a linear combination of the input variables $x$. Consider a single observation $x$; its vector components denoted $x_1, x_2, …, x_D$. Then we can imagine a function:&lt;/p&gt;

\[y(x, w) = w_0 + w_1x_1 + ... + w_Dx_D\]

&lt;p&gt;It takes in our inputs $x$ and a set of parameters $w$, and spits out a predicted target value. This is the simple linear regression model. Linear, in the sense that it is a linear combination of the &lt;em&gt;parameters&lt;/em&gt; $w$! While it also happens to be linear in the data $x$, do not be deceived. We can also consider linear combinations of nonlinear functions of the data like so:&lt;/p&gt;

\[y(x, w) = w_0 + \sum_{j=1}^{M-1} w_j\phi_j(x)\]

&lt;p&gt;where the $\phi_j$ &lt;em&gt;basis functions&lt;/em&gt;. Notice the indices - there are $M$ parameters in total, one for each $w$ (including $w_0$), and most importantly $M$ does not necessarily equal $D$. In practical terms, we can think of these basis functions as feature transformations on our original data $x$. The key is that by using nonlinear basis functions, we can turn $y(x, w)$ into a nonlinear function w.r.t the data $x$. A simple example is polynomial regression - consider an input $x$ and the basis functions as successive powers, s.t. $\phi_j(x) = x^j$. For our discussion, however, the choice of basis function has no effect on our analysis. We will choose the trivial identity function $\phi(x) = x$ and omit $\phi$ to simplify the notation.&lt;/p&gt;

&lt;h2 id=&quot;2-least-squares&quot;&gt;2. Least Squares&lt;/h2&gt;

&lt;p&gt;Let us assume that our target data is of the form:&lt;/p&gt;

\[y_i = w^Tx_i + \epsilon\]

&lt;p&gt;where $\epsilon \sim N(0, \sigma^2)$. That is, the target has mean given by $y(x,w) = w^Tx$ but is normally distributed around that value with a given variance $\sigma^2$:&lt;/p&gt;

\[p(y_i|x, w, \sigma^2) = N(y_i|w^Tx_i, \sigma^2)\]

&lt;p&gt;Then, across all observations, the likelihood function $P(D|W)$ becomes:&lt;/p&gt;

\[p(y|x, w, \sigma^2) = \prod_{i=1}^{N} N(y_i| w^Tx_i, \sigma^2)\]

&lt;p&gt;Now we can do maximum likelihood estimation to obtain the parameters $w$ and $\sigma^2$:&lt;/p&gt;

\[\ln(p(y|x, w, \sigma^2)) = \sum_{i=1}^{N} \ln(N(y_i| w^Tx_i, \sigma^2))\]

\[\ln(p(y|x, w, \sigma^2)) = \frac{N}{2}\ln\frac{1}{\sigma^2} - \frac{N}{2}ln(2\pi) - \frac{1}{2\sigma^2}E(w)\]

&lt;p&gt;where:&lt;/p&gt;

\[E(w) = \sum_{i=1}^{N} (y-w^Tx)^2\]

&lt;p&gt;which is the sum-of-squares error function.&lt;/p&gt;

&lt;h3 id=&quot;21-solving-for-w&quot;&gt;2.1 Solving for $w$&lt;/h3&gt;

&lt;p&gt;Consider the maximization w.r.t $w$. Notice the first two terms in the log-likelihood are constant. So the MLE solution for $w$ reduces to minimizing the residual squared error.&lt;/p&gt;

&lt;p&gt;Taking the gradient of the log-likelihood w.r.t $w$ and setting it equal to 0, we can solve for $w_{MLE}$:&lt;/p&gt;

\[w_{MLE} = (x^Tx)^{-1}x^Ty\]

&lt;p&gt;This should be a familiar result! Wrack your brain for a moment - we will return to this shortly.&lt;/p&gt;

&lt;p&gt;Notice that we must compute $(x^Tx)^{-1}$. This can be very tricky in practice when the matrix is singular or close to singular.&lt;/p&gt;

&lt;p&gt;Here we can gain a greater understanding of the bias parameter $w_0$. We can make the bias parameter $w_0$ explicit and do MLE to see that:&lt;/p&gt;

\[w_{0, MLE} = \bar{y} - \sum w_i\bar{x_i}\]

&lt;p&gt;That is, it addresses the difference between the sample mean of the target, and the weighted sum of the sample means of the data. In other words - it is compensating for the bias, hence the name. More on bias later.&lt;/p&gt;

&lt;h3 id=&quot;22-solving-for-sigma2&quot;&gt;2.2 Solving for $\sigma^2$&lt;/h3&gt;

&lt;p&gt;Consider the maximization w.r.t $\sigma^2$. Taking the gradient of the log-likelihood w.r.t $\sigma^2$ and setting it equal to 0, we can solve for $\sigma^2_{MLE}$:&lt;/p&gt;

\[\sigma^2_{MLE} = \frac{1}{N}\sum_{i=1}^N (y_i-w_{MLE}^Tx_i)^2\]

&lt;p&gt;This is actually the variance of the true target values around the regression values from the regression model.&lt;/p&gt;

&lt;h3 id=&quot;23-geometric-interpretation&quot;&gt;2.3 Geometric interpretation&lt;/h3&gt;

&lt;p&gt;Have you seen it? $w_{MLE}$ is actually the projection of $y$ onto $x$!&lt;/p&gt;

&lt;p&gt;Let us take a perspective informed by linear algebra. Consider the classic linear algebra problem - solving $Ax=b$. In this case, $Xw=y$.&lt;/p&gt;

&lt;p&gt;Sometimes, this cannot be solved. When $X$ has more rows than columns ($m &amp;gt; n$ where $m$ is the number of rows, $n$ the number of columns) there are more equations than unknowns. Make the connection between $X$ and the real world meaning - our dataset. This translates to: more observations than variables. Then there are infinitely many solutions, as the $n$ columns span a small part of $m$-space, and hence, $y$ is probably outside of the column space of $X$.&lt;/p&gt;

&lt;p&gt;Framed differently, $e = b - Ax = y - Xw$, the error, is not always 0. If it were, we can obtain an exact solution for $w$. But in the case of $m &amp;gt; n$, $e$ cannot be taken to 0. But we can still find an approximate solution for $w$. One way to determine the optimal $\hat{w}$ that minimizes $e$ is the least squares solution, which minimizes Euclidean distance. Multiply both sides by $X^T$:&lt;/p&gt;

\[X^TX\hat{w} = X^Ty\]

&lt;p&gt;The closest point to $y$ in $Xw$ is the projection of $y$ onto $X$.&lt;/p&gt;

&lt;p&gt;So we have shown that this is equivalent to the MLE result when assuming Gaussian noise!&lt;/p&gt;

&lt;h2 id=&quot;3-regularized-least-squares&quot;&gt;3. Regularized least-squares&lt;/h2&gt;

&lt;p&gt;We can control overfitting by introducing a regularization term to the error function. Recall our data-dependent error for $w$:&lt;/p&gt;

\[E_D(w) = \sum_{i=1}^{N} (y-w^Tx)^2\]

&lt;p&gt;We can add a regularization term and minimize this total error function instead:&lt;/p&gt;

\[E(w) = E_D(w) + \lambda E_W(w)\]

&lt;p&gt;From a probabilistic Bayesian point of view, we can interpret this regularization as assuming a prior on the parameters $w$. For example:&lt;/p&gt;

&lt;p&gt;A simple choice is a Gaussian. We don’t know much a priori - let’s say $w_j \sim N(0, \lambda^2)$.&lt;/p&gt;

\[\text{arg max}_w log P(w|D,\sigma,\lambda) = \text{arg max}_w (log P(D|w, \sigma) + log P(w|\lambda))\]

&lt;p&gt;The regularization term will be $\frac{1}{2\lambda^2}w^Tw$ - the sum of squares of the weights. This regularizer is known as weight decay as it heavily penalizes high weights due to the squaring. It is also known as ridge regression.&lt;/p&gt;

&lt;p&gt;The exact solution can be found in closed form:&lt;/p&gt;

\[w_{MAP} = (X^TX + \frac{\sigma^2}{\lambda^2}I)^{-1}X^Ty\]

&lt;p&gt;As $\lambda \rightarrow \infty$, our prior becomes broader, and MAP reduces to MLE! As $n$ increases, the entries of $X^TX$ grow linearly but the prior’s effect is fixed, so the effect of the prior also vanishes. Also notice that this avoids the problem of $X^TX$ being noninvertible.&lt;/p&gt;

&lt;p&gt;A general regularizer can be used, for which the error looks like:&lt;/p&gt;

\[\frac{1}{2}\sum (y-w^Tx)^2 + \frac{\lambda}{2}\sum |w|^q\]

&lt;p&gt;When $q=1$ we have lasso regression, which corresponds to a Laplace prior. It has the property of feature selection, as it can drive the parameters to 0.&lt;/p&gt;

&lt;h2 id=&quot;4-bias-variance-decomposition-of-loss&quot;&gt;4. Bias-variance decomposition of loss&lt;/h2&gt;

&lt;p&gt;Let’s take a step back and engage in a frequentist thought experiment related to model complexity.&lt;/p&gt;

&lt;p&gt;We have a model that takes a dataset $D$ and predicts $y$ given $x$. Call it $h(x, D)$. A linear regression model, for example, would be $h(x, D)=w^T_Dx$.&lt;/p&gt;

&lt;p&gt;Using a typical squared error loss function, we can calculate the expected loss on a new observation $(x, y)$:&lt;/p&gt;

\[E(L) = E((h(x, D)-y)^2) = \int_x\int_y(h(x, D)-y)^2p(x, y)dxdy\]

&lt;p&gt;Of course, we can’t compute this without knowing $p(x, y)$, and we indeed do not know it. However, suppose we had a large number of datasets drawn i.i.d from $p(x, y)$. For any given dataset we can run our algorithm to obtain a prediction function $h(x, D)$. Clearly, different $D$ produce different predictors. The performance of the model as a whole can be evaluated by averaging over this ensemble of all possible datasets.&lt;/p&gt;

\[\bar{h}(x) = E_D(h(x, D))\]

&lt;p&gt;We want to know the expected loss (squared error) over all datasets, which will be the best way to evaluate the performance of the algorithm.&lt;/p&gt;

\[E(L) = E_{x, y, D}((h(x, D)-y)^2)\]

\[E(L) = \int_D\int_x\int_y(h(x, D)-y)^2p(x, y)p(D)dxdydD\]

&lt;p&gt;Add and subtract $\bar{h}(x)$ in the first term:&lt;/p&gt;

\[E_{x, y, D}((h(x, D)-y)^2) = E_{x, y, D}((h(x, D) - \bar{h}(x) + \bar{h}(x) - y)^2)\]

\[E_{x, y, D}((h(x, D)-y)^2) = E_{x, y, D}((h(x, D) - \bar{h}(x))^2 + (\bar{h}(x) - y)^2 + 2(h(x, D) - \bar{h}(x))(\bar{h}(x) - y))\]

&lt;p&gt;But the cross term vanishes since $E_D(h(x, D) - \bar{h}(x))=0$, and the other part doesn’t depend on $D$. So ultimately:&lt;/p&gt;

\[E_{x, y, D}((h(x, D)-y)^2) = E_{x, y, D}((h(x, D) - \bar{h}(x))^2) + E_{x, y}((\bar{h}(x) - y)^2)\]

&lt;p&gt;The first term is the variance of the model. The second term can be further decomposed. Following the same trick and defining $\bar{y}(x) = E_{y|x}(y)$ - the average $y$ at every $x$:&lt;/p&gt;

\[E_{x, y}((\bar{h}(x) - y)^2) = E_{x, y}((\bar{h}(x) - \bar{y}(x) + \bar{y}(x) - y)^2\]

\[E_{x, y}((\bar{h}(x) - y)^2) = E_{x, y}((\bar{h}(x) - \bar{y}(x))^2 + (\bar{y}(x) - y)^2 + 2(\bar{h}(x) - \bar{y}(x))(\bar{y}(x) - y))\]

&lt;p&gt;Again the cross term vanishes as $E(\bar{y}(x) - y) = 0$.&lt;/p&gt;

\[E_{x, y}((\bar{h}(x) - y)^2) = E_{x}((\bar{h}(x) - \bar{y}(x))^2) + E_{x, y}((\bar{y}(x) - y)^2)\]

&lt;p&gt;Which are bias squared and noise terms, respectively.&lt;/p&gt;

&lt;p&gt;So the expected loss is variance + bias squared + noise.&lt;/p&gt;

\[E_{x, y, D}((h(x, D) - \bar{h}(x))^2) = E_{x, y, D}((h(x, D) - \bar{h}(x))^2) + E_{x}((\bar{h}(x) - \bar{y}(x))^2) + E_{x, y}((\bar{y}(x) - y)^2)\]</content><author><name></name></author><summary type="html">Let’s do a quick review of basic regression, to lay the framework for future posts. The goal of regression, one of the principal problems in supervised learning, is to predict the value(s) of one or more continuous target variables $y$, given a corresponding vector of input variables $x$.</summary></entry><entry><title type="html">Probabilistic PCA</title><link href="http://bllguo.github.io/Probabilistic-principal-component-analysis/" rel="alternate" type="text/html" title="Probabilistic PCA" /><published>2019-07-17T00:00:00+00:00</published><updated>2019-07-17T00:00:00+00:00</updated><id>http://bllguo.github.io/Probabilistic-principal-component-analysis</id><content type="html" xml:base="http://bllguo.github.io/Probabilistic-principal-component-analysis/">&lt;p&gt;Today let’s return to &lt;a href=&quot;https://bllguo.github.io/Principal-component-analysis/&quot;&gt;principal component analysis&lt;/a&gt; (PCA). Previously we had seen how PCA can be expressed as a variance-maximizing projection of the data onto a lower-dimension space, and how that was equivalent to a reconstruction-error-minimizing projection. Now we will show how PCA is &lt;em&gt;also&lt;/em&gt; a maximum likelihood solution to a continuous latent variable model, which provides us several useful benefits, some of which include:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Solvable using &lt;a href=&quot;https://bllguo.github.io/Expectation-maximization/&quot;&gt;expectation-maximization&lt;/a&gt; (EM) in an efficient manner, where we avoid having to explicitly construct the covariance matrix. Of course, we can also alleviate this issue in regular PCA by using singular value decomposition (SVD).&lt;/li&gt;
  &lt;li&gt;Handles missing values in the dataset&lt;/li&gt;
  &lt;li&gt;Permits a Bayesian treatment of PCA&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;1-setup&quot;&gt;1. Setup&lt;/h2&gt;

&lt;p&gt;Suppose we have $n$ observations of data $x$, with dimensionality $D$. Recall that our goal in PCA is to reduce this data by projecting $X$ onto a $M$-dimensional subspace where $M &amp;lt; D$.&lt;/p&gt;

&lt;p&gt;First let’s introduce a latent variable $z$ for the lower-dimensional principal component subspace. We assume a Gaussian prior distribution for $z$, $p(z)$ with zero mean and unit covariance.&lt;/p&gt;

\[p(z) = N(z|0, I)\]

&lt;p&gt;Let us also choose the conditional distribution $p(x|z)$ to be Gaussian:&lt;/p&gt;

\[p(x|z) = N(x|Wz + \mu, \sigma^2I)\]

&lt;p&gt;Here the mean is described as a linear function of $z$ with a $D\times M$ matrix $W$ and $D$-dimensional $\mu$.&lt;/p&gt;

&lt;p&gt;From a generative viewpoint, we can describe our $D$-dimensional data as a linear transformation of the $M$-dimensional latent $z$ with some Gaussian noise:&lt;/p&gt;

\[x = Wz + \mu + \epsilon\]

&lt;p&gt;where $\epsilon$ is $D$-dimensional Gaussian noise with zero mean and covariance $\sigma^2I$. So generating $x$ can be done by fixing some $z$ and then sampling from the distribution conditioned on $z$.&lt;/p&gt;

&lt;h2 id=&quot;2-specifying-the-likelihood-and-prior&quot;&gt;2. Specifying the likelihood and prior&lt;/h2&gt;

&lt;p&gt;Now we want to determine the parameters $W, \mu, \sigma^2$ using maximum likelihood. We need to specify the likelihood function $p(x|W, \mu, \sigma^2)$ first.&lt;/p&gt;

\[p(x) = \int p(x|z)p(z)dz\]

&lt;p&gt;By the properties of the Gaussian and of linear-Gaussian models, this marginal distribution $p(x)$ is also Gaussian:&lt;/p&gt;

\[p(x) = N(x|\mu, C)\]

\[C = WW^T + \sigma^2I\]

&lt;p&gt;where $C$ is the $D\times D$ covariance matrix.&lt;/p&gt;

&lt;p&gt;This can be noticed from $x = Wz + \mu + \epsilon$:&lt;/p&gt;

\[E(x) = E(Wz+\mu+\epsilon) = \mu\]

\[cov(x) = E((Wz+\epsilon)(Wz+\epsilon)^T)\]

\[cov(x) = E(Wzz^TW^T) + E(\epsilon\epsilon^T) = WW^T + \sigma^2I\]

&lt;p&gt;Remember $z$ was defined to have zero mean and unit variance, and that $\epsilon$ was defined to have covariance $\sigma^2I$. The cross terms vanish because $z, \epsilon$ are uncorrelated.&lt;/p&gt;

&lt;p&gt;Next we compute the posterior $p(z|x)$. We will be handwavy about the mathematical details here, as we have not yet covered linear-Gaussian models, but nevertheless the final result is presented for completeness. (In any case the mathematics here is not the critical point.)&lt;/p&gt;

&lt;p&gt;It can be shown that&lt;/p&gt;

\[C^{-1} = \sigma^{-2}I - \sigma^{-2}WM^{-1}W^T\]

&lt;p&gt;where&lt;/p&gt;

\[M = W^TW + \sigma^2I\]

&lt;p&gt;which is $M\times M$.&lt;/p&gt;

&lt;p&gt;From here we can use linear-Gaussian results:&lt;/p&gt;

\[p(z|x) = N(z|M^{-1}W^T(x-\mu), \sigma^2M^{-1})\]

&lt;h2 id=&quot;3-maximum-likelihood-solution&quot;&gt;3. Maximum likelihood solution&lt;/h2&gt;

&lt;p&gt;Now we can use maximum likelihood to obtain the parameters. We will skip over the derivations, but the parameters all have closed form solutions:&lt;/p&gt;

\[\mu_{\text{MLE}} = \bar{x}\]

\[W_{\text{MLE}} = U_M(L_M - \sigma^2I)^{1/2}R\]

\[\sigma^2_{\text{MLE}} = \frac{1}{D-M}\sigma_{i=M+1}^D \lambda_i\]

&lt;h3 id=&quot;31-w_textmle&quot;&gt;3.1 $W_{\text{MLE}}$&lt;/h3&gt;

&lt;p&gt;Let $S$ be the covariance matrix of the data $x$:&lt;/p&gt;

\[S = \frac{1}{n}\sum_n(x_i-\bar{x}(x_i-\bar{x})^T)\]

&lt;p&gt;Then $U_M$ is a $D\times M$ matrix whose columns are the eigenvectors of $S$.&lt;/p&gt;

&lt;p&gt;$L_M$ is $M\times M$ and contains the corresponding eigenvalues.&lt;/p&gt;

&lt;p&gt;$R$ is an arbitrary $M\times M$ orthogonal (orthonormal) matrix. This can be confusing - just substitute in $I$ if so, which is perfectly valid! $R$ can be thought of as a rotation matrix in latent $M$-space. If we substitute $W_{\text{MLE}}$ into $C$, it can be shown that $C$ is independent of $R$. The point is that the predictive density is unaffected by rotations in latent space.&lt;/p&gt;

&lt;h3 id=&quot;32-sigma2_textmle&quot;&gt;3.2 $\sigma^2_{\text{MLE}}$&lt;/h3&gt;

&lt;p&gt;We have assumed that the eigenvectors were arranged in decreasing order of the eigenvalues. Then $W$ is the principal subspace, and $\sigma^2_{\text{MLE}}$ is just the average variance of the remaining components.&lt;/p&gt;

&lt;h2 id=&quot;4-m-space-and-d-space&quot;&gt;4. $M$-space and $D$-space&lt;/h2&gt;

&lt;p&gt;Probabilistic PCA can be thought of as mapping points in $D$-space to $M$-space, and vice-versa. We can show that:&lt;/p&gt;

\[E(z|x) = M^{-1}W^T_{\text{MLE}}(x-\bar{x})\]

&lt;p&gt;Which is $x$’s posterior mean in latent space. Of course, in data space this is:&lt;/p&gt;

\[WE(z|x) + \mu\]

&lt;p&gt;The posterior covariance in latent space is:&lt;/p&gt;

\[\sigma^2M^{-1}\]

&lt;p&gt;which is actually independent of $x$.&lt;/p&gt;

&lt;p&gt;Notice that as $\sigma^2 \rightarrow 0$, the posterior mean simplifies to a familiar result:&lt;/p&gt;

\[(W^T_{\text{MLE}}W_{\text{MLE}})^{-1}W^T_{\text{MLE}}(x-\bar x)\]

&lt;p&gt;which is the orthogonal projection of $x$ onto $W$ - the standard PCA result!&lt;/p&gt;

&lt;h2 id=&quot;5-em-for-pca&quot;&gt;5. EM for PCA&lt;/h2&gt;

&lt;p&gt;We have just shown that probabilistic PCA can be solved using maximum likelihood with closed-form solutions. Why, then, would we want to use EM?&lt;/p&gt;

&lt;p&gt;Typical PCA requires us to evaluate the covariance matrix, which is $O(ND^2)$. In EM, we do not need the explicit covariance matrix. The costliest operations are sums over the data, which are $O(NDM)$. If $M \ll D$ then EM can be much more efficient despite having to go through multiple EM cycles.&lt;/p&gt;

&lt;p&gt;Second, if memory is a concern, or if the data is being streamed, the iterative nature of EM is useful as it can be used in an online learning fashion.&lt;/p&gt;

&lt;p&gt;Finally, thanks to our probabilistic model, we can deal with missing data in a principled way. We can marginalize over the distribution of the missing data in a generalized $E$-step (&lt;a href=&quot;https://core.ac.uk/download/pdf/397806.pdf&quot;&gt;Chen et al., 2009&lt;/a&gt;).&lt;/p&gt;

&lt;h2 id=&quot;6-bayesian-pca&quot;&gt;6. Bayesian PCA&lt;/h2&gt;

&lt;p&gt;Probabilistic PCA also allows us to take a Bayesian approach for selecting $M$. One example is by choosing a prior over $W$ that performs selection on relevant dimensions. This is an example of automatic relevance determination (ARD). We define a Gaussian prior for each component, or column of $W$, with respective precision hyperparameters $\alpha_i$:&lt;/p&gt;

\[p(W|\alpha) = \prod_{i=1}^M (\frac{\alpha_i}{2\pi})^{D/2}\exp{(-\frac{1}{2}\alpha_iw_i^Tw_i)}\]

&lt;p&gt;During the EM process, by maximizing the marginal likelihood after marginalizing out $W$, we can find the optimal $\alpha_i$. Some $\alpha_i$ will be driven to infinity, consequently pushing $w_i$ to 0. Then the finite $\alpha_i$ determine the relevant components $w_i$!&lt;/p&gt;

&lt;p&gt;We can also do a fully Bayesian treatment with priors over all parameters $\mu, \sigma^2, W$.&lt;/p&gt;</content><author><name></name></author><summary type="html">Today let’s return to principal component analysis (PCA). Previously we had seen how PCA can be expressed as a variance-maximizing projection of the data onto a lower-dimension space, and how that was equivalent to a reconstruction-error-minimizing projection. Now we will show how PCA is also a maximum likelihood solution to a continuous latent variable model, which provides us several useful benefits, some of which include: Solvable using expectation-maximization (EM) in an efficient manner, where we avoid having to explicitly construct the covariance matrix. Of course, we can also alleviate this issue in regular PCA by using singular value decomposition (SVD). Handles missing values in the dataset Permits a Bayesian treatment of PCA</summary></entry><entry><title type="html">Latent Dirichlet Allocation</title><link href="http://bllguo.github.io/Latent-dirichlet-allocation/" rel="alternate" type="text/html" title="Latent Dirichlet Allocation" /><published>2019-06-30T00:00:00+00:00</published><updated>2019-06-30T00:00:00+00:00</updated><id>http://bllguo.github.io/Latent-dirichlet-allocation</id><content type="html" xml:base="http://bllguo.github.io/Latent-dirichlet-allocation/">&lt;p&gt;Latent Dirichlet allocation (LDA) is a generative probabilistic model for discrete data. The objective is to find a lower dimensionality representation of the data while preserving the salient statistical structure - a complex way to describe clustering. It is commonly used in NLP applications as a topic model, where we are interested in discovering common topics in a set of documents.&lt;/p&gt;

&lt;h2 id=&quot;1-probability-distributions-in-lda&quot;&gt;1. Probability Distributions in LDA&lt;/h2&gt;

&lt;p&gt;First let us review some relevant probability distributions.&lt;/p&gt;

&lt;h3 id=&quot;11-poisson&quot;&gt;1.1 Poisson&lt;/h3&gt;

&lt;p&gt;Recall the Poisson distribution. It is a discrete distribution that models the probability of an event occuring $k$ times in an interval, assuming that they occur at a constant rate and are independent (the occurrence of one event does not effect the probability of another occurring).&lt;/p&gt;

&lt;p&gt;The PMF is given by:&lt;/p&gt;

\[p(k) = e^{-\lambda}\frac{\lambda^k}{k!}\]

&lt;p&gt;where $\lambda$ is the average number of events per interval. Notice that the length of the interval is baked into $\lambda$. We can explicitly define the interval length $t$ if we know the rate of events per unit interval $r$, and thus $\lambda=rt$.$\lambda$ is the expected value and the variance of the Poisson distribution.&lt;/p&gt;

&lt;h3 id=&quot;12-multinomial&quot;&gt;1.2 Multinomial&lt;/h3&gt;

&lt;p&gt;Next we have the multinomial distribution, a generalization of the binomial distribution. Whereas the binomial distribution can be viewed as a sequence of Bernoulli trials, i.e. coin flips, the multinomial can be viewed as a sequence of categorical trials, i.e. $k$-sided dice rolls.&lt;/p&gt;

&lt;p&gt;Given $k$ categories and $n$ trials, with the probabilities $p_i$ of a trial resulting in category $i$ of $k$, and $X_i$ the number of trials resulting in category $i$, the PMF is given by:&lt;/p&gt;

\[p(X_1=x_1, ..., X_k=x_k) = \frac{n!}{\prod_i^k x_i!}\prod_i^k p_i^{x_i}\]

&lt;p&gt;where $\sum_i^k x_i = n$. This can also be expressed with gamma functions:&lt;/p&gt;

\[p(X_1=x_1, ..., X_k=x_k) = \frac{\Gamma(n+1)}{\prod_i^k \Gamma(x_i+1)}\prod_i^k p_i^{x_i}\]

&lt;p&gt;Recall the gamma function is defined for positive integers $n$ as:&lt;/p&gt;

\[\Gamma(n) = (n-1)!\]

&lt;p&gt;and otherwise as:&lt;/p&gt;

\[\Gamma(z) = \int_0^{\infty} x^{z-1}e^{-x}dx\]

&lt;p&gt;The expected number of trials with outcome $i$ and the variance are:&lt;/p&gt;

\[E(X_i) = np_i\]

\[Var(X_i) = np_i(1-p_i)\]

\[Cov(X_i, X_j) = -np_ip_j\]

&lt;h3 id=&quot;13-dirichlet&quot;&gt;1.3 Dirichlet&lt;/h3&gt;

&lt;p&gt;Finally, the Dirichlet distribution is a multivariate generalization of the beta distribution. A $k$-dimensional Dirichlet random variable $\theta$ takes values in the $(k-1)$-simplex ($\theta$ lies in the $(k-1)$-simplex if $\theta_i\geq 0, \sum_{i=1}^k\theta_i = 1$) with the following pdf:&lt;/p&gt;

\[p(\theta|\alpha) = \frac{1}{B(\alpha)}\prod_{i=1}^k\theta_i^{\alpha_i-1}\]

\[p(\theta|\alpha) = \frac{\Gamma(\sum_{i=1}^k\alpha_i)}{\prod_{i=1}^k\Gamma(\alpha_i)}\prod_{i=1}^k\theta_i^{\alpha_i-1}\]

&lt;p&gt;where $\alpha$ is a $k$-dimensional parameter with positive elements. Note this looks very similar to the form of the multinomial! Recall the beta is the conjugate prior to the binomial; similarly the Dirichlet is the conjugate prior to the multinomial. So if our likelihood is multinomial with a Dirichlet prior, the posterior is also Dirichlet! This gives us some intuition for $\alpha_i$ as the prior proportion of the $i$th class.&lt;/p&gt;

&lt;p&gt;The expected value and variance:&lt;/p&gt;

\[E(X_j) = \frac{\alpha_j}{\sum_{i=1}^k \alpha_i} = \frac{\alpha_j}{\alpha_0}\]

\[Var(X_j) = \frac{\alpha_j(\alpha_0 - \alpha_j)}{\alpha_0^2(\alpha_0+1)}\]

&lt;h2 id=&quot;2-lda&quot;&gt;2. LDA&lt;/h2&gt;

&lt;p&gt;LDA is a three-level Bayesian model where every item is modeled as a finite mixture over a set of latent topics, and the topics are in turn modeled as infinite mixtures over underlying topic probabilities.&lt;/p&gt;

&lt;p&gt;It is helpful to discuss LDA in the context of NLP, in terms of guiding intuition. Do note that LDA can absolutely be applied to other problem spaces. We define:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Word: basic unit of discrete data. Given a vocabulary of size $V$, the $v$th word can be represented by a one-hot vector with a 1 in the $v$th index and 0 in all others.&lt;/li&gt;
  &lt;li&gt;Document: sequence of $N$ words $w = (w_1, …, w_N)$&lt;/li&gt;
  &lt;li&gt;Corpus: collection of $M$ documents $D = {w_1, … w_M}$&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;21-formulating-lda&quot;&gt;2.1 Formulating LDA&lt;/h3&gt;

&lt;p&gt;We want to find a probabilistic model for our corpus that assigns high probability to the members $d_1, …, d_M$ but also similar documents outside of our training set.&lt;/p&gt;

&lt;p&gt;We will represent a document as a random mixture over latent topic variables, and the topics will themselves be described using distributions over words. That is, every document can consist of many topics, and words within the document belong to topics according to the distribution of words conditional on topics.&lt;/p&gt;

&lt;p&gt;LDA models the generative process for each document in the corpus as:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;$N \sim \text{Poisson}(\xi)$&lt;/li&gt;
  &lt;li&gt;$\theta \sim \text{Dir}(\alpha)$&lt;/li&gt;
  &lt;li&gt;For each of the $N$ words $w_n$:
    &lt;ol&gt;
      &lt;li&gt;Sample a topic $z_n \sim \text{Multinomial}(\theta)$&lt;/li&gt;
      &lt;li&gt;Sample a word $w_n$ from a multinomial conditioned on $z_n$, $w_n \sim \text{Multinomial(\beta_{z_n})}$, where each topic corresponds to its own $\beta_{z_n}$. This can also be written as $p(w_n | z_n, \beta)$ where $\beta$ is a $k\times V$ matrix with $\beta_{ij} = p(w^j=1|z^i=1)$.&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Note that we have predetermined and fixed $k$. Secondly, note that the Poisson assumption is not relevant to the rest of the process and can be discarded for more realistic document length assumptions.&lt;/p&gt;

&lt;p&gt;Given the parameters $\alpha, \beta$, the joint distribution of the topic mixture $\theta$, the latent topic variables $z$, and the set of $N$ words $w$:&lt;/p&gt;

\[p(\theta, z, w|\alpha, \beta) = p(\theta|\alpha)\prod_{n=1}^Np(z_n|\theta)p(w_n|z_n,\beta)\]

&lt;p&gt;We can marginalize out the latent variables $\theta, z$ to get the marginal distribution of a document:&lt;/p&gt;

\[p(w|\alpha, \beta) = \int p(\theta|\alpha)(\prod_{n=1}^N\sum_{z_n} p(z_n|\theta)p(w_n|z_n, \beta))d\theta\]

&lt;p&gt;Then the probability of a corpus - $p(D|\alpha, \beta)$, the likelihood - is the product of these marginal probabilities over all documents.&lt;/p&gt;

&lt;h3 id=&quot;22-comparisons&quot;&gt;2.2 Comparisons&lt;/h3&gt;

&lt;p&gt;Take careful note of the hierarchy. LDA is not simply Dirichlet-multinomial clustering! There, we would sample a Dirichlet once for the corpus to describe the topic mixture, then sample a multinomial once for each document to describe a topic, then select words conditional on the topic (clustering)variable. A document would be associated with a single topic. In LDA, topics are repeatedly sampled within each document.&lt;/p&gt;

&lt;p&gt;Indeed, what we have just described is the mixture of unigrams model. Each document is generated by choosing a topic $z$, then generating $N$ words from the multinomial $p(w|z)$:&lt;/p&gt;

\[p(w) = \sum_z p(z)\prod_{n=1}^Np(w_n|z)\]

&lt;p&gt;A unigram model would be even more simplistic, with the words of every document being drawn independently from one multinomial:&lt;/p&gt;

\[p(w) = \prod_{n=1}^Np(w_n)\]

&lt;h3 id=&quot;23-estimation-em-and-variational-inference&quot;&gt;2.3 Estimation, EM, and Variational Inference&lt;/h3&gt;

&lt;p&gt;We need to find the parameters $\alpha, \beta$ that maximize the likelihood of the data, marginalizing over latent $\theta, z$. Of course, whenever we have to find maximum-likelihood solutions for models with latent variables, we turn to EM. At a high level:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;E-step: compute the posterior of the latent variables $p(\theta, z|w, \alpha, \beta)$ given the document $w$ and the parameters&lt;/p&gt;

\[p(\theta, z|w, \alpha, \beta) = \frac{p(\theta, z, w|\alpha, \beta)}{p(w|\alpha, \beta)}\]
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;M-step: estimate $\alpha, \beta$ given the revised latent variable estimates&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In practice, the posterior of the latent variables is analytically intractable in general. In such situations we turn to approximations to the posterior distribution. The most common method, and the one discussed in the original LDA paper, is variational inference. We will leave the details of variational EM for a future time.&lt;/p&gt;</content><author><name></name></author><summary type="html">Latent Dirichlet allocation (LDA) is a generative probabilistic model for discrete data. The objective is to find a lower dimensionality representation of the data while preserving the salient statistical structure - a complex way to describe clustering. It is commonly used in NLP applications as a topic model, where we are interested in discovering common topics in a set of documents.</summary></entry><entry><title type="html">Minimum Description Length</title><link href="http://bllguo.github.io/Minimum-description-length/" rel="alternate" type="text/html" title="Minimum Description Length" /><published>2019-06-24T00:00:00+00:00</published><updated>2019-06-24T00:00:00+00:00</updated><id>http://bllguo.github.io/Minimum-description-length</id><content type="html" xml:base="http://bllguo.github.io/Minimum-description-length/">&lt;p&gt;The minimum description length principle is an approach for the model selection problem. It is underpinned by the beautifully simple concept of learning as compression. Any pattern or regularity in the data can be exploited to compress the data. Hence we can equate the two concepts - the more we can compress, the more we know about the data!&lt;/p&gt;

&lt;p&gt;Before we begin, I would like to give thanks to &lt;a href=&quot;https://mitpress.mit.edu/books/minimum-description-length-principle&quot;&gt;Peter D. Grünwald and his text, &lt;em&gt;The Minimum Description Length Principle&lt;/em&gt;&lt;/a&gt;, whose first chapter serves as the basis for this post.&lt;/p&gt;

&lt;h2 id=&quot;1-learning-as-compression&quot;&gt;1. Learning as Compression&lt;/h2&gt;

&lt;p&gt;Consider the following sequences as datasets $D$:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/mdl_sequences.png&quot; alt=&quot;sequences&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The first sequence is just a repetition of $0001$ - clearly extremely regular. The second is randomly generated, with no regularity. The third contains 4 times more 0s than 1s, and is a middle ground - less regular than the first, but more regular than the second.&lt;/p&gt;

&lt;p&gt;To formalize the concept of MDL, we will need a description method which maps descriptions to datasets and vice-versa. One example is a computer language, where a corresponding description would then be a program that outputs the dataset $D$.&lt;/p&gt;

&lt;p&gt;The first sequence, for example, can be easily expressed as a loop printing $0001$, which can be shown is a compression on the order of $O(\log n)$ bits. On the other hand, with a high probability, the shortest program that can output sequence 2 will be a print statement. Due to its random nature, the sequence cannot be compressed at all. The third sequence can be shown to be compressible to $O(n)$.&lt;/p&gt;

&lt;p&gt;If we continue with computer languages as our description method, the minimum description length will be given by the length of the shortest program that can output the sequence and halt. This is the Kolmogorov complexity of the sequence. One might think that this would vary based on the hcoice of language, but according to the invariance theorem, for long enough sequences $D$, the lengths of the shortest programs in different languages will differ by a constant factor independent of $D$.&lt;/p&gt;

&lt;p&gt;However, this idealized MDL we have arrived at using computer languages is not computable. It can be shown that no program exists that can take $D$ and return the shortest program that outputs $D$.&lt;/p&gt;

&lt;p&gt;We are thus forced to use a more practical version of MDL, where we rely on more restrictive description methods, denoted $C$. We need to be able to compute the minimum description length of data $D$ when using said description method $C$.&lt;/p&gt;

&lt;h2 id=&quot;2-model-selection&quot;&gt;2. Model Selection&lt;/h2&gt;

&lt;p&gt;To further motivate our study of MDL, consider the following example of choosing a polynomial fit, again courtesy of Grünwald:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/mdl_tradeoff.png&quot; alt=&quot;tradeoff&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The first polynomial, which is linear, seems to suffer from high bias. It is overly simplistic. On the other hand, the second polynomial seems to suffer high variance - it is overly complex and has likely fit to the noise in the data. The third appears to generalize the best between bias and variance. MDL will provide a way to make this decision, without handwavy arguments.&lt;/p&gt;

&lt;p&gt;Let a &lt;em&gt;hypothesis&lt;/em&gt; refer to a single probability distribution or function, and a &lt;em&gt;model&lt;/em&gt; refer to a family of probability distributions/functions with the same form. 
For example, in a polynomial fitting problem, hypothesis selection is the problem of selecting the degree of a polynomial and the corresponding parameters, whereas model selection is strictly choosing the degree.&lt;/p&gt;

&lt;h3 id=&quot;21-crude-mdl&quot;&gt;2.1 Crude MDL&lt;/h3&gt;

&lt;p&gt;Crudely:
Let $M^1, M^2, …$ be a set of candidate models. The best hypothesis $H \in M^1\cup M^2\cup …$ to compress data $D$ minimizes:&lt;/p&gt;

\[L(H) + L(D|H)\]

&lt;p&gt;$L(H)$ is the length in bits of the description of $H$
$L(D|H)$ is the length in bits of the description of $D$ encoded using $H$&lt;/p&gt;

&lt;p&gt;Then the best model is the smallest model containing $H$.&lt;/p&gt;

&lt;p&gt;For probabilistic hypotheses, a straightforward choice for the description method is given by $L(D|H)=-\log{P(D|H)}$, the Shannon-Fano code. Finding a code for $L(H)$, however, is hard, because the description length of a hypothesis $H$ can be very large in one model but short in another.&lt;/p&gt;

&lt;h3 id=&quot;22-refined-mdl&quot;&gt;2.2 Refined MDL&lt;/h3&gt;

&lt;p&gt;In what is known as refined MDL, developed by Rissanen et al. (1996), we will use a one-part code $\bar L(D|M)$ instead of the two-part $L(H) + L(D|H)$. This will allow us to avoid the problem of specifying $L(H)$.&lt;/p&gt;

&lt;p&gt;The stochastic complexity of the data given the model is given by&lt;/p&gt;

\[\bar{L}(D|M)\]

&lt;p&gt;Where by definition, this quantity will be small whenever there is some hypothesis $H \in M$ such that $L(D|H)$ is small.&lt;/p&gt;

&lt;p&gt;$\bar{L}(D|M)$ - the stochastic complexity of the data given the model&lt;/p&gt;

&lt;p&gt;This can itself be decomposed into:&lt;/p&gt;

\[\bar{L}(D|M) = L(D\|\hat{H}) + COMP(M)\]

&lt;p&gt;where $\hat{H}$ is the best hypothesis in $M$ (the distribution that maximizes the probability of the given data $D$), and $COMP(M)$ the parametric complexity of the model $M$. The parametric complexity measures the model’s  ability to fit random data - an idea of its richness, or complexity. Recall that we are minimizing $\bar{L}(D|M)$ - we avoid overfitting by penalizing overly complex models thru the parametric complexity term.&lt;/p&gt;

&lt;h2 id=&quot;3-the-mdl-philosophy&quot;&gt;3. The MDL Philosophy&lt;/h2&gt;

&lt;p&gt;According to Grünwald, MDL informs a “radical” philosophy for statistical learning and inference, with the following main points:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Regularity as compression - the goal for statistical inference is compression. It is to distill regularity from noise. Refer to the example in section 1.&lt;/li&gt;
  &lt;li&gt;Models as languages - models are interpretable as languages for describing properties of the data. Individual hypotheses capture and summarize different patterns in the data. Notice that these patterns exist and are meaningful whether or not $\hat H \in M$ is the true distribution of $D$.&lt;/li&gt;
  &lt;li&gt;We have only the data - In fact, the concepts of “truth” and “noise” lose meaning in the MDL approach. Traditionally we assume some model generates the data and that noise is a random variable relative to this model. But in MDL noise is not a random variable. The “noise” is relative to the choice of model $M$ as the residual number of bits used to encode the data once $M$ is specified! Under the MDL principle, “noisy data” is just data that could theoretically be easily compressed using another model. This avoids what Rissanen describes as a fundamental flaw in other statistical methods, which assume the existence of a “ground truth” lying within our chosen model $M$. For instance, linear regression assumes Gaussian noise; Gaussian mixture models assume the data is generated from underlying Gaussian distributions. These are not true in practice! MDL, in contrast, has an interpretation that relies on no assumptions but the data.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-mdl-in-regression&quot;&gt;4. MDL in Regression&lt;/h2&gt;

&lt;p&gt;Consider a regression setting. To describe the description length of our model $\hat y$ and the data, we code two things - the residual $r = y - \hat{y}$, and the model (the parameters). In regression, this will be encoding 1. the features that are present in the model, and 2. the associated weights.&lt;/p&gt;

&lt;p&gt;The idea is that the residual term will be proportional to the test error, and the remaining term (the model parameters) will describe the model complexity, such that minimizing the sum (the minimum description length) minimizes the expected test error.&lt;/p&gt;

&lt;h3 id=&quot;41-residuals&quot;&gt;4.1 Residuals&lt;/h3&gt;

&lt;p&gt;First we code the residual. The optimal coding length is given by entropy - we can look at the entropy of $r$ in terms of the log-likelihood of $y$:&lt;/p&gt;

\[-\log{P(D|w,\sigma)} = -n\log{(\frac{1}{\sigma\sqrt{2\pi}})} + \frac{1}{2\sigma^2}\sum_i(y_i-w^Tx_i)^2\]

\[-\log{P(D|w,\sigma)} = n\log{(\sigma\sqrt{2\pi})} + \frac{Err}{2\sigma^2}\]

&lt;p&gt;The second term is the scaled sum of squares error. The problem is we don’t know $\sigma^2$.&lt;/p&gt;

&lt;p&gt;If we knew the true $w$, then for the corresponding $\hat{y}$, $\sigma^2=E((y-\hat{y})^2)=\frac{Err}{n}$ by the definition of variance. We don’t know it, but we can use our estimate of it.&lt;/p&gt;

&lt;p&gt;Using our estimate at the current iteration, we get $\frac{Err^t}{2Err^t/n}=\frac{n}{2}$, which is not helpful - it’s constant. But here we refer back to the likelihood’s constant term $n\log{(\sigma\sqrt{2\pi})}$, which remains.&lt;/p&gt;

\[n\log{(\sigma\sqrt{2\pi})} = n\log{(\sigma)} + ...\]

&lt;p&gt;Where … is some term which we can safely ignore, since it is independent of $\sigma$. We know:&lt;/p&gt;

\[n\log{(\sigma)} \sim n\log{\sqrt{\frac{Err}{n}}} = \frac{n}{2}\log{\frac{Err}{n}}\]

&lt;p&gt;So ultimately we have&lt;/p&gt;

\[-\log{P(D|w,\sigma)} \sim \frac{n}{2}\log{\frac{Err}{n}} \sim n\log{\frac{Err}{n}}\]

&lt;h3 id=&quot;42-weights&quot;&gt;4.2 Weights&lt;/h3&gt;

&lt;p&gt;We can code the model by asking: for each feature, is it in the model? and if so, what is its coefficient?&lt;/p&gt;

&lt;p&gt;Say we have $p$ features and we expect $q$ to be in the model. Then the probability is $\frac{q}{p}$. The entropy is:&lt;/p&gt;

\[-\sum_i \frac{q}{p}\log{(\frac{q}{p})} + \frac{p-q}{p}\log{(\frac{p-q}{p})}\]

&lt;p&gt;Two special cases that will come in handy below:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;If $q=\frac{p}{2}$, the cost of coding each feature presence or absence is 1 bit.&lt;/li&gt;
  &lt;li&gt;If $q=1$ then $\log{(\frac{p-q}{p})} \sim 0$ and the cost of coding each feature is $\sim -\log{(\frac{1}{p})} = \log{(p)}$ bits&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To code the weight values, this is handwavy - but the variance of $\hat{w} \sim \frac{1}{n}$, hence we use $\log{\sqrt{n}} = \frac{\log{(n)}}{2}$ bits for each feature.&lt;/p&gt;

&lt;p&gt;So ultimately the description length is:&lt;/p&gt;

\[n\log{\frac{Err}{n}} + \lambda|w|_0\]

&lt;p&gt;Where&lt;/p&gt;

\[\lambda=\log{(\pi)} + \frac{\log{(n)}}{2}\]

\[\pi=\frac{q}{p}\]

&lt;h3 id=&quot;43-limiting-cases&quot;&gt;4.3 Limiting Cases&lt;/h3&gt;

&lt;p&gt;Recall our discussion of MDL as training error + parametric complexity. Clearly the first term is capturing training error (the residuals) and the second the parametric complexity. Consider some limiting cases for $\lambda$:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;BIC - $\sqrt{n} &amp;gt;\hbox{}&amp;gt; p$ - the cost of coding feature presence is negligible; we essentially charge $\frac{\log{(n)}}{2}$ per feature.&lt;/li&gt;
  &lt;li&gt;RIC - $p &amp;gt;\hbox{}&amp;gt; \sqrt{n}$ - the cost of coding weights is negligible; we essentially charge $\log{(p)}$ bits per feature&lt;/li&gt;
  &lt;li&gt;AIC - $q \sim \frac{p}{2}$ and $n, p$ small - we charge 1 bit per feature.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Depending on $n, p$ and our expected $q$ a different penalty criterion $\lambda$ is more appropriate to describe the variance.&lt;/p&gt;</content><author><name></name></author><summary type="html">The minimum description length principle is an approach for the model selection problem. It is underpinned by the beautifully simple concept of learning as compression. Any pattern or regularity in the data can be exploited to compress the data. Hence we can equate the two concepts - the more we can compress, the more we know about the data!</summary></entry><entry><title type="html">Expectation Maximization</title><link href="http://bllguo.github.io/Expectation-maximization/" rel="alternate" type="text/html" title="Expectation Maximization" /><published>2019-06-16T00:00:00+00:00</published><updated>2019-06-16T00:00:00+00:00</updated><id>http://bllguo.github.io/Expectation-maximization</id><content type="html" xml:base="http://bllguo.github.io/Expectation-maximization/">&lt;p&gt;In the last two posts we have seen two examples of the expectation maximization (EM) algorithm at work, finding maximum-likelihood solutions for models with latent variables. Now we derive EM for general models, and demonstrate how it maximizes the log-likelihood.&lt;/p&gt;

&lt;h2 id=&quot;1-decomposing-the-log-likelihood&quot;&gt;1. Decomposing the log-likelihood&lt;/h2&gt;

&lt;p&gt;Suppose we have a model with variables $X$ and latent variables $Z$, with a joint distribution described by parameters $\theta$. The likelihood function is then:&lt;/p&gt;

\[p(X|\theta) = \sum_Z p(X, Z|\theta)\]

&lt;p&gt;The key assumption we make is that optimizing $p(X|\theta)$ is complex relative to optimizing $p(X, Z|\theta)$.&lt;/p&gt;

&lt;p&gt;To optimize over the latent variables we will need a distribution $q(Z)$ over the latent variables. Now we can represent the log likelihood $\ln p(X|\theta)$ as follows:&lt;/p&gt;

\[\ln p(X|\theta) = \sum_Z q(Z)\ln p(X|\theta)\]

&lt;p&gt;By the rules of probability we know $p(X,Z|\theta) = p(Z|X, \theta)p(X|\theta)$, hence:&lt;/p&gt;

\[\ln p(X|\theta) = \sum_Z q(Z)\ln \frac{p(X,Z|\theta)}{p(Z|X, \theta)}\]

\[\ln p(X|\theta) = \sum_Z q(Z)(\ln \frac{p(X,Z|\theta)}{q(Z)} - \ln\frac{p(Z|X, \theta)}{q(Z)})\]

\[\ln p(X|\theta) = \sum_Z q(Z)\ln \frac{p(X,Z|\theta)}{q(Z)} - \sum_Z q(Z)\ln\frac{p(Z|X, \theta)}{q(Z)}\]

\[\ln p(X|\theta) = \mathcal{L}(q,\theta) + KL(q\|p)\]

&lt;p&gt;Notice the second term is the KL-divergence between the prior $q(Z)$ and the posterior $p(Z|X, \theta)$! Furthermore, as KL-divergence is $\geq 0$, it follows that $\mathcal{L}(q,\theta) \leq \ln p(X|\theta)$. It is a lower bound on the log-likelihood.&lt;/p&gt;

&lt;h2 id=&quot;2-em-algorithm&quot;&gt;2. EM Algorithm&lt;/h2&gt;

&lt;p&gt;Now, let our current parameters be $\theta_0$.&lt;/p&gt;

&lt;h3 id=&quot;21-e-step&quot;&gt;2.1 E-step&lt;/h3&gt;

&lt;p&gt;Consider taking the partial of the log likelihood $\ln p(X|\theta_0)$ with respect to $q(Z)$, keeping $\theta_0$ fixed. Notice that $\ln p(X|\theta_0)$ does not depend on $q(Z)$ as it is marginalized out! However, when $q(Z) = p(Z|X,\theta_0)$ - setting the $q$ distribution to the posterior for the current $\theta_0$ - the KL-divergence term goes to 0. Then we have $\mathcal{L}(q,\theta_0) = \ln p(X|\theta_0)$.&lt;/p&gt;

&lt;p&gt;Now fix $q(Z)$ and take the partial w.r.t $\theta$ to maximize $\mathcal{L}(q,\theta)$ and find $\theta_1$. $\mathcal{L}$, the lower bound on the log-likelihood, will necessarily increase.&lt;/p&gt;

&lt;h3 id=&quot;22-m-step&quot;&gt;2.2 M-step&lt;/h3&gt;

&lt;p&gt;Remember that we fixed $q(Z) = p(Z|X, \theta_0)$. Substituting in $\mathcal{L}$:&lt;/p&gt;

\[\mathcal{L}(q,\theta) = \sum_Z p(Z|X, \theta_0)\ln p(X, Z|\theta) - \sum_z p(Z|X, \theta_0)\ln p(Z|X, \theta_0)\]

\[\mathcal{L}(q,\theta) = \sum_Z p(Z|X, \theta_0)\ln p(X, Z|\theta) + H(q(Z))\]

&lt;p&gt;Where $H(q(Z))$ is the entropy of the $q$ distribution. The key is that this quantity is independent of $\theta$. So really what we are maximizing is $\sum_Z p(Z|X, \theta_0)\ln p(X, Z|\theta) = Q(\theta, \theta_0)$ - the expected value of the complete-data ($X$ and $Z$) log-likelihood. Another way to think about this is a weighted MLE with the weights given by $q(Z)$.&lt;/p&gt;

&lt;p&gt;Also note that we fixed $q(Z) = p(Z|X, \theta_0)$ instead of $p(Z|x, \theta_1)$, so the KL-divergence term is positive (unless $\theta_0 = \theta_1$). Hence the log-likelihood actually increases by more than the increase in $\mathcal{L}$.&lt;/p&gt;

&lt;h3 id=&quot;23-summary&quot;&gt;2.3 Summary&lt;/h3&gt;

&lt;p&gt;The algorithm can be expressed beautifully as two simple steps - iteratively computing the posterior over the latent variables $p(Z|X, \theta)$, and then using the posterior to update the parameters $\theta$ by maximizing the expected full-data log-likelihood.&lt;/p&gt;

&lt;p&gt;Through the decomposition into $\ln p(X|\theta) = \mathcal{L}(q,\theta) + KL(q||p)$ we also have shown that the EM algorithm continually improves the lower-bound on the log-likelihood as well as the log-likelihood itself.&lt;/p&gt;</content><author><name></name></author><summary type="html">In the last two posts we have seen two examples of the expectation maximization (EM) algorithm at work, finding maximum-likelihood solutions for models with latent variables. Now we derive EM for general models, and demonstrate how it maximizes the log-likelihood.</summary></entry><entry><title type="html">Gaussian Mixtures and EM</title><link href="http://bllguo.github.io/Gaussian-mixtures/" rel="alternate" type="text/html" title="Gaussian Mixtures and EM" /><published>2019-06-11T00:00:00+00:00</published><updated>2019-06-11T00:00:00+00:00</updated><id>http://bllguo.github.io/Gaussian-mixtures</id><content type="html" xml:base="http://bllguo.github.io/Gaussian-mixtures/">&lt;p&gt;Continuing from last time, I will discuss Gaussian mixtures as another clustering method. We assume that the data is generated from several Gaussian components with separate parameters, and we would like to assign each observation to its most likely Gaussian parent. It is a more flexible and probabilistic approach to clustering, and will provide another opportunity to discuss expectation-maximization (EM). Lastly, we will see how K-means is a special case of Gaussian mixtures!&lt;/p&gt;

&lt;h2 id=&quot;1-gaussian-mixtures&quot;&gt;1. Gaussian Mixtures&lt;/h2&gt;

&lt;p&gt;Here we will take a probabilistic approach to clustering, where we assume the data is generated from $K$ underlying Gaussian distributions:&lt;/p&gt;

\[p(x) = \sum_{k=1}^K \pi_kN(x|\mu_k,\Sigma_k)\]

&lt;p&gt;where $\pi_k$, the mixing coefficient, is the probability that the sample was drawn from the $k$th Gaussian distribution. We can reformulate this model in terms of an explicit latent variable $z$ with a 1-of-K representation. That is, $z$ is $K$-dimensional and $z_k = 1$ when the sample belongs to the $k$th Gaussian. Let us proceed with this to arrive at the joint distribution $p(x, z) = p(z)p(x|z)$.&lt;/p&gt;

&lt;p&gt;The marginal distribution over $z$ can be specified:&lt;/p&gt;

\[p(z) = \prod_k \pi_k^{z_k}\]

&lt;p&gt;since&lt;/p&gt;

\[p(z_k=1) = \pi_k\]

&lt;p&gt;and $0 \leq \pi_k \leq 1$ and $\sum_k \pi_k=1$.&lt;/p&gt;

&lt;p&gt;The conditional for a particular $z$ is:&lt;/p&gt;

\[p(x|z_k=1) = N(x|\mu_k, \Sigma_k)\]

&lt;p&gt;Hence using the 1-of-K representation,&lt;/p&gt;

\[p(x|z) = \prod_k N(x|\mu_k, \Sigma_k)^{z_k}\]

&lt;p&gt;So the joint distribution is simply:&lt;/p&gt;

\[p(x, z) = \prod_k (\pi_kN(x|\mu_k, \Sigma_k))^{z_k}\]

&lt;p&gt;Now the marginal distribution of $x$ can be obtained from the joint:&lt;/p&gt;

\[p(x) = \sum_z p(z)p(x|z)\]

\[p(x) = \sum_z \prod_k^K (\pi_kN(x|\mu_k, \Sigma_k))^{z_k}\]

&lt;p&gt;Consider what the possible values of $z$ are. They are $K$-dimensional one-hot vectors. So the summation over $z$ is just over $K$ possibilities. Furthermore, if $z_k=1$, notice that the product simplifies to $\pi_kN(x|\mu_k, \Sigma_k)$ as $z_{i\neq k} = 0$.&lt;/p&gt;

\[p(x) = \sum_j^K \pi_jN(x|\mu_j, \Sigma_j)\]

&lt;p&gt;So we have recovered the initial Gaussian mixture formulation, but now with the latent $z$.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Lastly we can define the conditional $p(z&lt;/td&gt;
      &lt;td&gt;x)$:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[p(z_k=1|x) = \frac{p(x|z_k=1)p(z_k=1)}{p(x)}\]

\[p(z_k=1|x) = \frac{\pi_kN(x|\mu_k, \Sigma_k)}{\sum_j^K \pi_jN(x|\mu_j, \Sigma_j)} = \gamma(z_k)\]

&lt;p&gt;So $p(z_k=1|x) = \gamma(z_k)$ is the posterior probability of $z_k=1$, and $\pi_k$ the prior.&lt;/p&gt;

&lt;h2 id=&quot;2-maximum-likelihood&quot;&gt;2. Maximum likelihood&lt;/h2&gt;

&lt;p&gt;We have a dataset of observations $x^{(1)}, …, x^{(N)}$ which we assume are i.i.d. Their corresponding latent variables are $z^{(1)}, …, z^{(N)}$. We can stack them into matrices $X, Z$ which are $N\times D$ and $N\times K$, respectively.&lt;/p&gt;

&lt;p&gt;We know:&lt;/p&gt;

\[p(x) = \sum_j^K \pi_jN(x|\mu_j, \Sigma_j)\]

&lt;p&gt;So the likelihood:&lt;/p&gt;

\[p(X|\pi, \mu, \Sigma) = \prod_n\sum_k^K \pi_kN(x^{(n)}|\mu_k, \Sigma_k)\]

&lt;p&gt;And the log-likelihood:&lt;/p&gt;

\[\ln p(X|\pi, \mu, \Sigma) = \sum_n \ln(\sum_k^K \pi_kN(x^{(n)}|\mu_k, \Sigma_k))\]

&lt;h3 id=&quot;21-mu_k&quot;&gt;2.1 $\mu_k$&lt;/h3&gt;

&lt;p&gt;Taking the partial with respect to $\mu_k$ and carefully stepping through the math, we obtain:&lt;/p&gt;

\[\mu_k = \frac{1}{N_k}\sum_n \gamma(z_{nk})x^{(n)}\]

\[N_k = \sum_n \gamma(z_{nk})\]

&lt;p&gt;Notice that $\mu_k$ is the weighted mean of $x$ where the weights are the posterior probabilities that $x^{(n)}$ belongs to Gaussian component $k$. $N_k$ thus can be interpreted as the effective number of points assigned to $k$.&lt;/p&gt;

&lt;h3 id=&quot;22-sigma_k&quot;&gt;2.2 $\Sigma_k$&lt;/h3&gt;

&lt;p&gt;Taking the partial with respect to $\Sigma_k$ we will arrive at a similar weighted result:&lt;/p&gt;

\[\Sigma_k = \frac{1}{N_k}\sum_n \gamma(z_{nk})(x^{(n)} - \mu_k)(x^{(n)} - \mu_k)^T\]

&lt;h3 id=&quot;23-pi_k&quot;&gt;2.3 $\pi_k$&lt;/h3&gt;

&lt;p&gt;Lastly, we take the partial with respect to $\pi_k$. Recall $\sum_k \pi_k = 1$, so we will need a Lagrange multiplier to maximize&lt;/p&gt;

\[\ln p(X|\pi, \mu, \Sigma) + \lambda(\sum_k \pi_k - 1)\]

&lt;p&gt;We will arrive at&lt;/p&gt;

\[\pi_k = \frac{N_k}{N}\]

&lt;h3 id=&quot;24-expectation-maximization-for-gaussian-mixtures&quot;&gt;2.4 Expectation-maximization for Gaussian mixtures&lt;/h3&gt;

&lt;p&gt;This is not a closed-form solution thanks to the complicated relationship to $\gamma(z_{nk})$. However we can solve for our parameters using the iterative method of EM!&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Initialize the parameters and evaluate the initial log-likelihood&lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;E-step: Evaluate the posteriors under the current parameters:&lt;/p&gt;

\[\gamma(z_{nk}) = frac{\pi_kN(x^{(n)}|\mu_k, \Sigma_k)}{\sum_j^K \pi_jN(x^{(n)}|\mu_j, \Sigma_j)}\]
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;M-step: Re-evaluate the parameters using the new posteriors:&lt;/p&gt;

\[\mu_k = \frac{1}{N_k}\sum_n \gamma(z_{nk})x^{(n)}\]

\[\Sigma_k = \frac{1}{N_k}\sum_n \gamma(z_{nk})(x^{(n)} - \mu_k)(x^{(n)} - \mu_k)^T\]

\[\pi_k = \frac{N_k}{N}\]

\[N_k = \sum_n \gamma(z_{nk})\]
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Calculate the log-likelihood and check stopping criteria:&lt;/p&gt;

\[\ln p(X|\pi, \mu, \Sigma) = \sum_n \ln(\sum_k^K \pi_kN(x^{(n)}|\mu_k, \Sigma_k))\]
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;3-expectation-maximization&quot;&gt;3. Expectation-maximization&lt;/h2&gt;

&lt;p&gt;In general, EM is used to find MLE solutions when we have latent variables. Consider the general log-likelihood:&lt;/p&gt;

\[\ln p(X|\theta) = \ln(\sum_Z p(X, Z|\theta))\]

&lt;p&gt;where we have introduced the latent variable matrix $Z$.&lt;/p&gt;

&lt;p&gt;We cannot compute this in practice, because we do not observe the latent variables $Z$. What we know about $Z$ is captured by our posterior $p(Z|X, \theta)$. We can use it to compute the expected value of the log-likelihood under this posterior.&lt;/p&gt;

&lt;p&gt;Consider our current parameters $\theta_0$ and the new parameters $\theta_1$.&lt;/p&gt;

&lt;p&gt;In the E-step, we use $\theta_0$ to find the posterior over the latent variables, $p(Z|X, \theta_0)$. We can use it to calculate:&lt;/p&gt;

\[Q(\theta, \theta_0) = \sum_Z p(Z|X, \theta_0)\ln p(X, Z|\theta)\]

&lt;p&gt;which is the expectation of the log-likelihood for a general $\theta$.&lt;/p&gt;

&lt;p&gt;In the M-step, we find $\theta_1$ by maximizing the expectation:&lt;/p&gt;

\[\theta_1 = \text{arg max}_{\theta} Q(\theta, \theta_0)\]

&lt;h2 id=&quot;4-comparison-with-k-means&quot;&gt;4. Comparison with K-means&lt;/h2&gt;

&lt;p&gt;Notice that K-means performs a hard, binary assignment of observations to clusters - a point is either in a cluster or it isn’t. In Gaussian mixtures, we make a soft assignment by way of the posterior probabilities. It turns out that K-means is a special case of Gaussian mixtures!&lt;/p&gt;

&lt;p&gt;Let the covariance matrices $\Sigma_k$ all be equal to $\epsilon I$. Then:&lt;/p&gt;

\[p(x|\mu_k, \Sigma_k) = \frac{1}{(2\pi\epsilon)^{D/2}}\exp(-\frac{||x-\mu_k||^2}{2\epsilon})\]

&lt;p&gt;by the definition of the multivariate Gaussian.&lt;/p&gt;

&lt;p&gt;Treating the variances $\epsilon$ as fixed, we arrive at:&lt;/p&gt;

\[\gamma(z_{nk}) = \frac{\pi_k\exp(-\frac{||x^{(n)}-\mu_k||^2}{2\epsilon})}{\sum_j \pi_j\exp(-\frac{||x^{(n)}-\mu_j||^2}{2\epsilon})}\]

&lt;p&gt;As $\epsilon \rightarrow 0$, the term with the smallest value of $\|x^{(n)}-\mu_l\|^2$ will approach $0$ slowest. So in the limit, $\gamma(z_{nl}) \rightarrow 1 \rightarrow r_{nl}$ while the other posteriors converge to 0. We have obtained the hard assignment of K-means. Recall:&lt;/p&gt;

\[r_{nk} = \begin{cases}
1,  &amp;amp; \text{if }k=\text{arg min}_j ||x_n-\mu_j||^2 \\\
0, &amp;amp; \text{otherwise}
\end{cases}\]

&lt;p&gt;The update equation for $\mu_k$ will simplify to the K-means result thanks to these weights. We can also show that as $\epsilon \rightarrow 0$, the log-likelihood converges to the distortion loss in K-means.&lt;/p&gt;

&lt;p&gt;Notice the geometric interpretation here. Because of the way we have specified the $\Sigma_k$ in K-means (as diagonal matrices), the underlying assumption is spherical clusters. Whereas in Gaussian mixtures, we can have elliptical clusters depending on our $\Sigma_k$.&lt;/p&gt;</content><author><name></name></author><summary type="html">Continuing from last time, I will discuss Gaussian mixtures as another clustering method. We assume that the data is generated from several Gaussian components with separate parameters, and we would like to assign each observation to its most likely Gaussian parent. It is a more flexible and probabilistic approach to clustering, and will provide another opportunity to discuss expectation-maximization (EM). Lastly, we will see how K-means is a special case of Gaussian mixtures!</summary></entry><entry><title type="html">K-means and EM</title><link href="http://bllguo.github.io/K-means/" rel="alternate" type="text/html" title="K-means and EM" /><published>2019-06-10T00:00:00+00:00</published><updated>2019-06-10T00:00:00+00:00</updated><id>http://bllguo.github.io/K-means</id><content type="html" xml:base="http://bllguo.github.io/K-means/">&lt;p&gt;Clustering is an unsupervised learning problem in which we try to identify groupings of similar data points, i.e. learn the structure of our data. Today I will introduce K-means, a popular and simple clustering algorithm. Our true motivation will be to use this as a gentle introduction to clustering and the expectation maximization (EM) algorithm. In subsequent posts we will expand on this foundation towards Gaussian mixtures, and finally into latent Dirichlet allocation (LDA).&lt;/p&gt;

&lt;h2 id=&quot;1-k-means-clustering&quot;&gt;1. K-means Clustering&lt;/h2&gt;

&lt;p&gt;Suppose we have $n$ observations of data $x$, with dimensionality $D$. We want to partition them into $K$ clusters such that points in each cluster are close together, and are far from points outside.&lt;/p&gt;

&lt;p&gt;To indicate cluster assignment, we will define indicator variables $r_{nk}$ such that $r_{nk}=1$ if $x_n$ belongs to cluster $k$, and $r_{nj}=0$ for $j\neq k$.&lt;/p&gt;

&lt;p&gt;The simple scheme we employ will be based on distortion, or sum of squared distances, which is a very natural objective function to employ:&lt;/p&gt;

\[J = \sum_n\sum_k r_{nk}||x_n-\mu_k||^2\]

&lt;p&gt;$mu_k$ is a $D$-dimensional vector representing the center of cluster $k$. We need to manipulate $r_{nk}$ and $\mu_k$ to minimize $J$.&lt;/p&gt;

&lt;p&gt;A simple iterative algorithm to do this is:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Initialize $\mu_k$&lt;/li&gt;
  &lt;li&gt;Minimize $J$ with respect to $r_{nk}$&lt;/li&gt;
  &lt;li&gt;Minimize $J$ with respect to $\mu_k$&lt;/li&gt;
  &lt;li&gt;Repeat 1-2 until convergence&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is our first introduction to the expectation maximization (EM) algorithm!&lt;/p&gt;

&lt;h3 id=&quot;11-e-step---fracpartial-jpartial-r_nk&quot;&gt;1.1 E-step - $\frac{\partial J}{\partial r_{nk}}$&lt;/h3&gt;

&lt;p&gt;$\frac{\partial J}{\partial r_{nk}}$ is easy to calculate. We swiftly arrive at&lt;/p&gt;

\[r_{nk} = \begin{cases}
1,  &amp;amp; \text{if }k=\text{arg min}_j ||x_n-\mu_j||^2 \\\
0, &amp;amp; \text{otherwise}
\end{cases}\]

&lt;p&gt;Notice that having to recompute distances between $mu_k$ and $x_n$ in every E-step is very costly.&lt;/p&gt;

&lt;h3 id=&quot;12-m-step---fracpartial-jpartial-mu_k&quot;&gt;1.2 M-step - $\frac{\partial J}{\partial \mu_k}$&lt;/h3&gt;

&lt;p&gt;$\frac{\partial J}{\partial \mu_k}$ is not much more difficult:&lt;/p&gt;

\[\frac{\partial J}{\partial \mu_k} = 2\sum_n r_{nk}(x_n-\mu_k) = 0\]

\[\mu_k = \frac{\sum_n r_{nk}x_n}{\sum_n r_{nk}}\]

&lt;p&gt;Which is actually the mean of all points in cluster $k$.&lt;/p&gt;

&lt;h2 id=&quot;2-properties&quot;&gt;2. Properties&lt;/h2&gt;

&lt;p&gt;Convergence can be decided in many ways - threshold on $J$, number of iterations, until assignments no longer change, etc. Notice that under EM, the objective function is bound to decrease after every iteration. Of course, we are not guaranteed to stumble into the global optimum. Also notice that the algorithm is stochastic in that it depends on the initialization of $\mu_k$.&lt;/p&gt;

&lt;p&gt;An alternative to this batch formulation of k-means can be derived using stochastic approximation methods, yielding the sequential update equation:&lt;/p&gt;

\[\mu_k^{1} = \mu_k^{0} + \eta_n(x_n-\mu_k^{0})\]

&lt;p&gt;$\eta_n$ is the learning rate parameter; its dependence on $n$ allows it to be annealed over time. This formulation lets us use k-means in online settings.&lt;/p&gt;

&lt;h2 id=&quot;3-kernelization&quot;&gt;3. Kernelization&lt;/h2&gt;

&lt;p&gt;So far, our formulation and interpretation of k-means is wholly reliant on squared Euclidean distance. This is not always the best metric for evaluating similarity of points. We can generalize with kernels $k(x_i, x_j) = \phi(x_i)^T\phi(x_j)$:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;E-step&lt;/p&gt;

\[r_{nk} = \begin{cases}
 1,  &amp;amp; \text{if }k=\text{arg min}_j ||\phi(x_n)-\mu_j||^2 \\\
 0, &amp;amp; \text{otherwise}
 \end{cases}\]

    &lt;p&gt;Notice that we can express $\|\phi(x)-\mu_k^2\|$ purely using the kernel function, in yet another example of the kernel trick:&lt;/p&gt;

\[||\phi(x)-\mu_k||^2 = \phi(x)^T\phi(x) - 2\mu_k^T\phi(x) + \mu_k^T\mu_k\]

    &lt;p&gt;Let $y_k = \sum_n r_{nk}$:&lt;/p&gt;

\[||\phi(x)-\mu_k||^2 = \frac{1}{y_k^2}\sum_{n,m}r_{nk}r_{mk}k(x_n, x_m) - \frac{2}{y_k}\sum_n r_{nk}k(x_n, x) + k(x, x)\]
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;M-step&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

\[\mu_k = \frac{\sum_n r_{nk}\phi(x_n)}{\sum_n r_{nk}}\]</content><author><name></name></author><summary type="html">Clustering is an unsupervised learning problem in which we try to identify groupings of similar data points, i.e. learn the structure of our data. Today I will introduce K-means, a popular and simple clustering algorithm. Our true motivation will be to use this as a gentle introduction to clustering and the expectation maximization (EM) algorithm. In subsequent posts we will expand on this foundation towards Gaussian mixtures, and finally into latent Dirichlet allocation (LDA).</summary></entry><entry><title type="html">Due-tos</title><link href="http://bllguo.github.io/Differential-decomposition/" rel="alternate" type="text/html" title="Due-tos" /><published>2019-06-06T00:00:00+00:00</published><updated>2019-06-06T00:00:00+00:00</updated><id>http://bllguo.github.io/Differential-decomposition</id><content type="html" xml:base="http://bllguo.github.io/Differential-decomposition/">&lt;p&gt;This post is a throwback to the methodology behind one of my first analytics projects at System1. The due-to is a simple name for a simple idea - isolating the effects of individual key performance indicators (KPIs) on a business metric, like gross profit. Sometimes - most times, even - data science doesn’t have to be that sophisticated.&lt;/p&gt;

&lt;h2 id=&quot;1-problem-setup&quot;&gt;1. Problem Setup&lt;/h2&gt;

&lt;p&gt;Let us consider a simple example. Imagine being the proud owner of Widgets Incorporated. Your new widget has just entered the market and you want to do some digital marketing.&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;You place an ad for your widget via Google Ads. After spending some amount at the auction, you end up acquiring some number of impressions, or some number of appearances on Google search engine result pages. A useful KPI here is the cost per impression, which we will denote hereafter as CPC. (Typically, in digital advertising, this is formulated as the cost per thousand impressions, or the cost per mille (CPM))&lt;/li&gt;
  &lt;li&gt;A few users who see your ad end up clicking through to your website, which extolls the virtues of the Widget 3.0. The number of clicks over the number of impressions will be the click-through rate, CTR.&lt;/li&gt;
  &lt;li&gt;From there, some number of visitors who click through also complete a purchase. Revenue is generated. We can easily define revenue per click, RPC.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now, what is your gross profit $\pi$?&lt;/p&gt;

\[\pi = Revenue - Cost\]

&lt;p&gt;Let us do some algebraic manipulations to define profit in terms of our KPIs:&lt;/p&gt;

\[\pi = Impressions(\frac{Revenue - Cost}{Impressions})\]

\[\pi = Impressions(\frac{Revenue}{Clicks}\frac{Clicks}{Impressions} - \frac{Cost}{Impressions})\]

\[\pi = Impressions(RPC\times CTR - CPC)\]

&lt;p&gt;Let $V$ be the total volume of impressions.&lt;/p&gt;

\[\pi = V(RPC\times CTR - CPC)\]

&lt;p&gt;You can monitor the performance of your ad looking at the gross profit as well as the daily values of your KPIs.&lt;/p&gt;

&lt;p&gt;Imagine now that you notice a drastic decrease in profit week-over-week, with corresponding changes in the key metrics. How can you understand more quantitatively the effect of V vs. RPC or CTR on the change in profit? What is the effect on profit &lt;em&gt;due to&lt;/em&gt; changes in RPC or CPC?&lt;/p&gt;

&lt;h2 id=&quot;2-decomposition-w-differentiation&quot;&gt;2. Decomposition w/ Differentiation&lt;/h2&gt;

&lt;p&gt;More formally, we observe, over two time periods $t_1, t_2$, a change in $\pi$, $\Delta\pi$.&lt;/p&gt;

\[\Delta\pi = \pi_{t_2} - \pi_{t_1}\]

&lt;p&gt;We would like to identify how much of this $\Delta$ is due to the change in volume $\Delta V$, or change in RPC $\Delta RPC$, etc.&lt;/p&gt;

&lt;p&gt;Differentiate!&lt;/p&gt;

\[\frac{\partial\pi}{\partial t} = \frac{\partial(V(RPC\times CTR - CPC))}{\partial t}\]

&lt;p&gt;An elementary application of the chain rule will give us:&lt;/p&gt;

\[\frac{\partial\pi}{\partial t} = \frac{\partial V}{\partial t}(RPC\times CTR - CPC) + \frac{\partial RPC}{\partial t}(V\times CTR) + \\\frac{\partial CTR}{\partial t}(V \times RPC) - \frac{\partial CPC}{\partial t}(V)\]

&lt;p&gt;We can approximate the partials with our observed deltas, using finite differences. Here we simply use the forward difference:&lt;/p&gt;

\[\frac{\Delta\pi}{\Delta t} = \frac{\Delta V}{\Delta t}(RPC\times CTR - CPC) + \frac{\Delta RPC}{\Delta t}(V\times CTR) + \\\frac{\Delta CTR}{\Delta t}(V \times RPC) - \frac{\Delta CPC}{\Delta t}(V)\]

&lt;p&gt;Along the same vein, we can substitute in values for $V, RPC, CTR, CPC$ from our real observations. $V = V_{t_2}$, $V = V_{t_1}$, or $V = \frac{V_{t_2} + V_{t_1}}{2}$ are all valid choices.&lt;/p&gt;

&lt;p&gt;So we have successfully decomposed $\Delta\pi$! Nota bene:&lt;/p&gt;

\[\Delta \pi = \Delta \pi_{V} + \Delta \pi_{RPC} + \Delta \pi_{CTR} + \Delta \pi_{CPC}\]

\[\Delta \pi_V = \Delta V(RPC\times CTR - CPC)\]

\[\Delta \pi_{RPC} = \Delta RPC(V\times CTR)\]

\[\Delta \pi_{CTR} = \Delta CTR(V \times RPC)\]

\[\Delta \pi_{CPC} = -\Delta CPC(V)\]

&lt;p&gt;That is, the contribution to $\Delta \pi$ from each KPI is given directly from these terms. Dimensional analysis confirms that $\Delta \pi_{KPI}$ are all in units of $\Delta \pi$.&lt;/p&gt;

&lt;p&gt;With this information we can build a slick waterfall chart that satisfies our equation, with the first four bars summing to the last (count the heights!).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/dueto.png&quot; alt=&quot;dueto&quot; /&gt;&lt;/p&gt;

&lt;p&gt;In this case, reductions in cost per click since the last week drove the majority of the profit increase, but click-thru rate plummeted. This may indicate that the keywords we are bidding on are no longer very relevant. While competition in the auction is lower for these keywords, consumer interest has also waned to a degree that nearly offsets that change. We can extract clear practical insights immediately.&lt;/p&gt;

&lt;p&gt;In general, this analysis can be useful in:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;identifying which KPI has the most impact on our metric of interest&lt;/li&gt;
  &lt;li&gt;providing a bird’s-eye view of macro-level trends and performance over two time periods&lt;/li&gt;
  &lt;li&gt;disentangling the effects of individual KPIs for particularly convoluted metrics&lt;/li&gt;
&lt;/ol&gt;</content><author><name></name></author><summary type="html">This post is a throwback to the methodology behind one of my first analytics projects at System1. The due-to is a simple name for a simple idea - isolating the effects of individual key performance indicators (KPIs) on a business metric, like gross profit. Sometimes - most times, even - data science doesn’t have to be that sophisticated.</summary></entry></feed>