Monday, December 15, 2014

Squares, Faces and the Good Old Singular Value Decomposition

In my applied linear algebra class we received an assignment to use linear least squares to predict the right hand side of a person's face given the left hand side.

For this task we used the grayscale image of faces from the Labeled Faces in the Wild Project.

The left and right hand side of each face was a $64\times 32$ matrix and so the whole face was a $64\times 64$ matrix.

You might be highly skeptical about the efficacy of linear least squares in tackling such a problem, I certainly was, since it seems unlikely that the pixels in the right hand side of the face are linear combinations of the pixels in the left hand side of the face. But hey, it's always worth it to try, surprising things do happen!

But to apply linear least squares meant first choosing a way to represent each face as two row vectors, one for the left side of the face, and another for the right side of the face. In keeping with the "let's do this the simplest possible way first" approach I decided to simply collapse the left and right hand side matrix of each face along its columns into a row vector. The 12000 faces that we had in the training were too much to fit into memory, so I figured start small with 2000.

And voila!
Simple Linear Least Squares with 2000 Examples
Well... those results were even worse than I had expected... but 2000 training examples is not too many, so let's see what happens when we double it to 4000!
Simple Linear Least Squares with 4000 Examples
Alright, so that's just not going to work.

So let's reflect for a moment and consider why this simple application of linear least squares is giving such poor results. There are two important things to notice about the system of linear equations that we set up. First our system is treating each pixel in the right hand side of the face as if it were a linear combination of all the pixels in the left hand side, an issue that we had pointed out earlier. Second, our system treats each pixel that we are trying to predict in isolation of all the other pixels that it is trying to predict. Stated another way, this system of linear equations weights all the wrong pixels in all the wrong ways, and none of the right pixels in any way. Uh oh... So how can we address this? What can we do to take advantage of the fact that human faces vary in highly structured ways while still only using linear least squares?

Enter the singular value decomposition! Recall that the singular value decomposition of a matrix $A\in \mathbb{R}^{m\times n}$ produces, among other things, a decomposition of $A$ into the sum of $r$ mutually orthogonal matrices, $Z_i$, where $r$ is the rank($A$). In other words, $A$ is a linear combination of these $r$ matrices. moreover, the structure of $A$'s variations are encapsulated in linear combinations of these matrices. So how can we apply that to our current problem? Well if we average the faces and apply the singular value decomposition to this average face we will obtain rank($A$) matrices which structure the ways in which the average of the faces in the data vary. If we think of each face as a linear combination of these matrices we can solve for this linear combination using the left hand side of the face and linear least squares. Then we can use this solution to predict the right hand side of the face!

And sooooo!
From the stand point of what we would like face prediction to be this is still bad. But considering that all we used was linear least squares, this is surprisingly good! It is also another case in point that often it is not the choice of model that matters so much as the form of the data to which the model is applied!

Sunday, December 7, 2014

Beautiful Figures

This semester I have had the good fortune to have a job conducting computational experiments on extended ordered binary trees. Part of this work is creating visualizations of these trees. Below are a couple of figures that struck me as particularly beautiful. Enjoy!
10101010101010100
For the curious, the figures are a depiction of the polygonal triangulation associated to the tree.
11010101101010000

Monday, August 25, 2014

The Strength of 1 Person with the Power of 665,305,705.62

For the past few months I have been grappling with the classic machine learning problem of classifying handwritten digits using their gray-scale pixel maps. The first thing I tried was to apply the k-nearest neighbors algorithm. Naively, I implemented the algorithm from scratch in C++ using only the Standard Template Library. Doing so meant that writing the implementation took me one week. When the program was executed, for each test digit, it calculated the square distance between it and each training digit. Then it sorted the training digits in order from nearest to furthest, took the first k and predicted that the test digit was the same as the most frequently occurring digit among those first k training digits. The total running time for the program was 24 hours. This post is not about machine learning it is about the following question: how much time would it have taken a human being to do the same work as the program?

We need to come up with a way to measure work done by the program and by a human being in order to compare them. We'll do that by measuring work done in terms of operations performed.

We can get a ballpark underestimate of how much work was done by the program as follows. There were 42,000 training digits. For each test digit, calculating the distance between it and one training digit required 2351 operations. Then, the training digits were sorted from nearest to furthest using the heap-sort algorithm which has a time complexity of $O(n*log(n))$. Putting this together we find that the program performed approximately $28000 * 42000 * 2351 * 42000 * log_{2}(42000) \approx 1.78 * 10^{18}$ operations.

Okay! So what about a human being? Assuming a person could do 60 operations per minute, every minute of every day, every day of every year, every year for 85 years, one person could do $2.68056 * 10^9$ operations in their life. This means it would take $\frac{1.78 * 10^{18}}{2.68056 * 10^9} \approx 6.65 * 10^{8}$ human lives to do the same number of operations.

How incredible is it that human beings have made it possible for one person to program a machine to do an amount of work in one day that would require the lives of hundreds of millions of human beings to do manually! What an incredible testament to the accomplishments of humanity!

Saturday, July 19, 2014

Linear Circles

One thing that blows my mind in machine learning is that it is possible to construct a linear model with with nonlinear decision boundaries.

Say that we are trying to build a binary classifier and imagine that the scatter plot of our two classes produces figure 1.

Figure 1: Scatter Plot of Toy Data Set
Clearly, the classes are not linearly separable. That is, there is no line that we can possibly draw in the plane that could separate these two classes perfectly. In fact, fitting a linear support vector machine to the toy data set gives the following decision boundary.

Figure 2
And yet, at the same time, it is also clear that the classes are perfectly separable since the two classes in our toy dataset do not overlap as the two classes in this set do:
Figure 3: Overlapping Classes

So how can a linear model learn a nonlinear decision boundary? One way is by using basis functions, that is, by applying one or more nonlinear functions to each of the features, the features can be mapped to another space in which the decision boundary is a line (plane, hyperplane). This has the nice consequence that in this new space, points on one side of the "line" fall "within" the nonlinear decision boundary and points on the other side fall "outside."

For example, imagine that the decision boundary we wish our model to learn is the unit circle (of course in practice we don't pick a decision boundary for the model, the model picks the decision boundary for itself based on the data) where every instance inside the circle it predicts to be the blue class and every instance outside the circle it predicts to be the red class. This is illustrated in figure 4.
Figure 4: Unit Circle as Decision Boundary
If we go back to the equation for the unit circle $x^2 + y^2 = 1$ and do some mental reshuffling we can think of it instead as $c_{x}\phi_{x}(x) + c_{y}\phi_{y}(y) = 1$ where $c_{x}$ and $c_{y}$ are coefficients and $\phi_{x}(x)$ and $\phi_{y}(y)$ are the basis functions which we apply to $x$ and $y$ where $\phi_{z}(z) = z^2$. When we think of the equation for the unit circle in this way, we end up with a line in the variables $\phi_{x}(x)$ and $\phi_{y}(y)$. Specifically we get $\phi_{x}(x) + \phi_{y}(y) = 1$ because $c_{x} = c_{y} = 1$.
Figure 5: Decision Boundary Induced by Basis Functions
Now, notice that every point inside the circle satisfies the inequality $x^2 + y^2 < 1$ or equivalently $\phi_{x}(x) + \phi_{y}(y) < 1$ and this corresponds to all the points on one side of the line $\phi_{x}(x) + \phi_{y}(y) = 1$ Since the points on the other side of the line all satisfy $\phi_{x}(x) + \phi_{y}(y) > 1$ they all correspond to $x^2 + y^2 > 1$ which are all the points outside the unit circle! Thus, if we take the the parameters of our model to be the coefficients, $c_{x}$ and $c_{y}$, of the basis functions we will have a model that is linear in its parameters but whose decision boundary is nonlinear in the input feature space!

Using basis functions is not the only method for building a linear model with a nonlinear decision boundary. And there is much more that can and should be said about it, but in the interest of making this short and sweet I will stop here. I just thought that the idea that we can map nonlinear boundaries in one space to lines in another space where the points on one side of the nonlinear boundary all end up together on one side of the line in the new space was incredible and worth sharing!

Sunday, July 13, 2014

Checkpointing It Out

I really enjoy solving math problems. So it's a real bummer when I spend a good amount of time solving one only to find that neither an answer nor a worked out solution is available for me to check my work against. Here is one that I felt like would be fun to share in the hopes that either someone can enjoy the solution to this problem as well or perhaps point out if I have made a mistake.

This problem comes from the text Mining of Massive Datasets by Ullman and Rajaraman (edited slightly for text jargon that is confusing out of context):

Suppose a job consists in $n$ tasks and each task has a probability $p$ of failure. Suppose also that the execution time (summed over all tasks) of taking a checkpoint (backing everything up so that not all of the work has to be redone in case of failure) is $c$ times the time it takes to execute a task. To minimize the expected execution time of the job, how many tasks should elapse between checkpoints?

Definitely go ahead and solve this before reading on!

We can tackle this problem as follows, first derive an expression for the expected execution time of a job in terms of the number of checkpoints taken during the job. With such an expression we can solve for the number of checkpoints using standard optimization techniques i.e. differentiate with respect to the number of checkpoints, set the derivative to $0$ and solve.

Let $T$ be the time required to complete the job. In the best case, $T$ will be equal to the sum of the time it takes to complete all tasks and the time that it takes to make all the checkpoints, that is $T=nt + n_{c}ct$ where $n$ is the number of tasks, $t$ is the average time to complete each tasks and $n_{c}$ is the number of checkpoints being taken. If we let $t=1$ then the expression simplifies to: $T=n + n_{c}c$. Of course, this is the best case, where there are no failures, so to account for failures we introduce the term work lost, $w_{l}=\Sigma_{i=1}^{f} l_{i}$ where $f$ is the number of failures and $l_{i}$ is the number of jobs lost on the $i^{th}$ failure. This makes our expression $T=n + n_{c}c + w_{l}$, now we may take the expectation $E\lbrack T\rbrack = E[n + n_{c}c + w_{l}] = n + n_{c}c + E[w_{l}]$. We must now disentangle $E[w_{l}]=E[\Sigma_{i=1}^{f} l_{i}] = E[f]E[l_{i}] = np\frac{n}{2n_{c}}$ Plugging this back in we have $E[T] = n + n_{c}c + np\frac{n}{2n_{c}}$. And so we have derived a differentiable expression for $E[T]$ which completes the first step in our solution!

In the second step we differentiate $E[T]$ with respect to $n_{c}$ as follows and set the derivative equal to 0, this gives: $\frac{\partial}{\partial n_{c}}E[T]=c-\frac{n^2 p}{2n_{c}^2} = 0$. Solving this equality for $n_{c}$ we obtain $n_{c}=n\sqrt{\frac{p}{2c}}$ and finally we divide $n$ by $n_{c}$ for the number of tasks that should elapse between checkpoints for a final answer of $\frac{n}{n_{c}} = \sqrt{\frac{2c}{p}}$.

I have a feeling that there may be a simpler solution to this problem which skirts the introduction of so many variables. If anyone thinks of one please share!

Friday, July 11, 2014

The Writing in the Pixels


For the past few months I have been tackling the classic machine learning problem of classifying handwritten digits. As all nerds do I really enjoy visualizations of data. Here are two that I thought would be fun to share!

Visualizing handwritten digits:

Figure 1: Axes Determined by Principal Components of 0

This is a scatter plot of 0's and 1's. The 0's are green and marked as O's and the 1's are blue and marked as 1's.

Figure 2: Axes Determined by Principal Components of 1
And here is another one! Ditto for the legend.

Figure 3: Axes Determined by Principal Components of 0 and 1
And here is another that I added after first writing this post. This one is the 0's and 1's plotted against the first three principal components of the 0's and 1's. Ditto for the legend.


Assuming that these scatter plots came from the same handwritten digit examples, which they did, you might be wondering about two things. First, how can one create a 3 dimensional scatter plot of what is originally a 784 dimensional vector and second how could you possibly end up with two different scatter plots from the same examples?

The answer to the first question is that these are scatter plots of the first three principal components of the handwritten digits. This is also the key to the second answer. Two different scatter plots may be obtained because the principal components used are different, in the first figure the digits are plotted against the first three principal components of the 0's and in the second figure the digits are plotted against the first three principal components of the 1's.

I think I am going to try to make the scatter plots interactive by
embedding a python script using Brython, but I've never used Brython and it supports Python 3 while up to date I have been using Python 2.7, so I'll have quite a bit of learning to do to make that happen!

Wednesday, July 9, 2014

Cauchy or Gauss?

In the methods section of The Expression of Emotions in 20th Century Books (Acerbi, Lampos, Garnett and Bentley, 2013), the authors defined the mood score of year $y$ as $\mathcal{M_{y}}=\frac{1}{n}\Sigma_{i=1}^{n}\frac{c_{i}}{C_{the}}$ where $c_{i}$ is the count of the associated word in the year and $C_{the}$ is the count of the word 'the' in the year. In order to compare the different year's mood scores they then computed the z-score of year $y$ as follows $\mathcal{M_{zy}}=\frac{\mathcal{M_{y}}-\mu_{\mathcal{M}}}{\sigma_{\mathcal{M}}}$ where $\mu_{\mathcal{M}}$ is the average mood score and $\sigma_{\mathcal{M}}$ is the standard deivation of the mood scores. But it seems odd that the mood scores from different years would be compared by applying the standardization transformation associated with the Gaussian distribution since it is not entirely clear to me whether the mood score itself is a Gaussian random variable.

Clearly, when computing the mood score associated with a given year, each $c_{i}$ in the numerator may be conceived of as Binomial($m$, $p_{i}$), where $m$ is the total number of words in the year, $p_{i}$ is the probability that a randomly chosen word is the one associated with $c_{i}$ and is therefore approximately Gaussian provided $m$ is sufficiently large. By the same reasoning, $C_{the}$ in the denominator is also approximately Gaussian. Additionally, all the $c_{i}$ in the numerator may be "collapsed" into one Gaussian since the sum of Gaussians is again Gaussian. No confusion so far. But then the mood score divides the Gaussian in the numerator by the Gaussian in the denominator. This begs the question, is the ratio of two Gaussians Gaussian? But according to Wikipedia the distribution of the ratio of Gaussians is not Gaussian but Cauchy! And if the mood score is Cauchy, then applying any linear transformation to it, including the one associated with the standardization of a Gaussian, would result in another Cauchy distribution. Thus, interpreting the z-score as standard Gaussian would be a mistake. But frankly, I'm probably missing something, so I figured it would be interesting to generate mood scores and test whether their distribution is Gaussian or Cauchy.

To test the distribution of mood scores I set $n=5$ where the words used were: scared, terrified, whimper, fear and worried. To set the parameters I used the percentage of times these words occurred in English Fiction in the year 2000 from Google's Ngram Viewer.

$\begin{array}{|c | c|}
\hline
word & percentage & probability \\
\hline
the & 4.00 & 0.0400 \\
scared & 0.00422 & 0.0000422 \\
terrified & 0.00188 & 0.0000188 \\
whimper & 0.000271 & 0.00000271 \\
fear & 0.0133 & 0.000133 \\
worried & 0.00602 & 0.0000602 \\
\hline
\end{array}$

Since the probability that a randomly chosen word would be whimper was so small, I chose $m=10,000,000$ so that the expectation of the number of words whimper would be $E(c_{whimper})\approx 27$. The results of generating one thousand mood scores, fitting a Cauchy and a Gaussian distribution to them and testing their goodness of fit using the Kolmogorov-Smirnov test are shown below.


Wondering what it was that I had misunderstood I went back to the Wikipedia article that I had consulted when trying to determine whether the ratio of two Gaussians is Gaussian and found what is probably the source of my error "The random variable associated with this distribution [Cauchy] comes about as the ratio of two Gaussian (normal) distributed variables with zero mean." While the mean of the mood scores is close to zero, it certainly is not, moreover, by the definition of mood score it is effectively impossible for the mean of the mood scores to be zero. Later I will test that.

The astronomical winner is Gauss!