















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
















1 Snoqualmie Falls Revisited 1 1.1 Fitting a Mixture of Gaussians to Real Data........... 1 1.2 Calibration-checking for the Mixture................ 5 1.3 Selecting the Number of Components by Cross-Validation.... 7 1.4 Interpreting the Mixture Components, or Not........... 12 1.5 Hypothesis Testing for Mixture-Model Selection.......... 17
2 Multivariate Gaussians 20
3 Exercises 23
Let’s go back to the Snoqualmie Falls data set, last used in lecture 16. There we built a system to forecast whether there would be precipitation on day t, on the basis of how much precipitation there was on day t − 1. Let’s look at the distribution of the amount of precipitation on the wet days.
snoqualmie <- read.csv("snoqualmie.csv",header=FALSE) snoqualmie.vector <- na.omit(unlist(snoqualmie)) snoq <- snoqualmie.vector[snoqualmie.vector > 0]
Figure 1 shows a histogram (with a fairly large number of bins), together with a simple kernel density estimate. This suggests that the distribution is rather skewed to the right, which is reinforced by the simple summary statistics
> summary(snoq) Min. 1st Qu. Median Mean 3rd Qu. Max. 1.00 6.00 19.00 32.28 44.00 463.
Notice that the mean is larger than the median, and that the distance from the first quartile to the median is much smaller (13/100 of an inch of precipitation) than that from the median to the third quartile (25/100 of an inch). One way this could arise, of course, is if there are multiple types of wet days, each with a different characteristic distribution of precipitation. We’ll look at this by trying to fit Gaussian mixture models with varying numbers of components. We’ll start by using a mixture of two Gaussians. We could code up the EM algorithm for fitting this mixture model from scratch, but instead we’ll use the mixtools package.
library(mixtools) snoq.k2 <- normalmixEM(snoq,k=2,maxit=100,epsilon=0.01)
The EM algorithm “runs until convergence”, i.e., until things change so little that we don’t care any more. For the implementation in mixtools, this means running until the log-likelihood changes by less than epsilon. The default tolerance for convergence is not 10−^2 , as here, but 10−^8 , which can take a very long time indeed. The algorithm also stops if we go over a maximum number of iterations, even if it has not converged, which by default is 1000; here I have dialed it down to 100 for safety’s sake. What happens?
> snoq.k2 <- normalmixEM(snoq,k=2,maxit=100,epsilon=0.01) number of iterations= 59 > summary(snoq.k2) summary of normalmixEM object: comp 1 comp 2 lambda 0.557564 0. mu 10.267390 60. sigma 8.511383 44. loglik at estimate: -32681.
There are two components, with weights (lambda) of about 0.56 and 0.44, two means (mu) and two standard deviations (sigma). The over-all log-likelihood, obtained after 59 iterations, is − 32681 .21. (Demanding convergence to ± 10 −^8 would thus have required the log-likelihood to change by less than one part in a trillion, which is quite excessive when we only have 6920 observations.) We can plot this along with the histogram of the data and the non-parametric density estimate. I’ll write a little function for it.
plot.normal.components <- function(mixture,component.number,...) { curve(mixture$lambda[component.number] * dnorm(x,mean=mixture$mu[component.number], sd=mixture$sigma[component.number]), add=TRUE, ...) }
This adds the density of a given component to the current plot, but scaled by the share it has in the mixture, so that it is visually comparable to the over-all density.
Precipitation in Snoqualmie Falls
Precipitation (1/100 inch)
Density
0 100 200 300 400
plot(hist(snoq,breaks=101),col="grey",border="grey",freq=FALSE, xlab="Precipitation (1/100 inch)",main="Precipitation in Snoqualmie Falls") lines(density(snoq),lty=2) sapply(1:2,plot.normal.components,mixture=snoq.k2)
Figure 2: As in the previous figure, plus the components of a mixture of two Gaussians, fitted to the data by the EM algorithm (dashed lines). These are scaled by the mixing weights of the components.
Examining the two-component mixture, it does not look altogether satisfactory — it seems to consistently give too much probability to days with about 1 inch of precipitation. Let’s think about how we could check things like this. When we looked at logistic regression, we saw how to check probability forecasts by checking calibration — events predicted to happen with probability p should in fact happen with frequency ≈ p. Here we don’t have a binary event, but we do have lots of probabilities. In particular, we have a cumulative distribution function F (x), which tells us the probability that the precipitation is ≤ x on any given day. When x is continuous and has a continuous distribution, F (x) should be uniformly distributed.^1 The CDF of a two-component mixture is F (x) = λ 1 F 1 (x) + λ 2 F 2 (x) (1)
and similarly for more components. A little R experimentation gives a function for computing the CDF of a Gaussian mixture:
pnormmix <- function(x,mixture) { lambda <- mixture$lambda k <- length(lambda) pnorm.from.mix <- function(x,component) { lambda[component]*pnorm(x,mean=mixture$mu[component], sd=mixture$sigma[component]) } pnorms <- sapply(1:k,pnorm.from.mix,x=x) return(rowSums(pnorms)) }
and so produce a plot like Figure 1.2. We do not have the tools to assess whether the size of the departure from the main diagonal is significant^2 , but the fact that the errors are so very structured is rather suspicious.
(^1) We saw this principle when we looked at generating random variables in lecture 7. (^2) Though we could: the most straight-forward thing to do would be to simulate from the mixture, and repeat this with simulation output.
Since a two-component mixture seems iffy, we could consider using more com- ponents. By going to three, four, etc. components, we improve our in-sample likelihood, but of course expose ourselves to the danger of over-fitting. Some sort of model selection is called for. We could do cross-validation, or we could do hypothesis testing. Let’s try cross-validation first. We can already do fitting, but we need to calculate the log-likelihood on the held-out data. As usual, let’s write a function; in fact, let’s write two.
dnormalmix <- function(x,mixture,log=FALSE) { lambda <- mixture$lambda k <- length(lambda)
like.component <- function(x,component) { lambda[component]*dnorm(x,mean=mixture$mu[component], sd=mixture$sigma[component]) }
likes <- sapply(1:k,like.component,x=x)
d <- rowSums(likes) if (log) { d <- log(d) } return(d) }
loglike.normalmix <- function(x,mixture) { loglike <- dnormalmix(x,mixture,log=TRUE) return(sum(loglike)) }
To check that we haven’t made a big mistake in the coding:
> loglike.normalmix(snoq,mixture=snoq.k2) [1] -32681.
which matches the log-likelihood reported by summary(snoq.k2). But our func- tion can be used on different data! We could do five-fold or ten-fold CV, but just to illustrate the approach we’ll do simple data-set splitting, where a randomly-selected half of the data is used to fit the model, and half to test.
n <- length(snoq) data.points <- 1:n data.points <- sample(data.points) # Permute randomly train <- data.points[1:floor(n/2)] # First random half is training
test <- data.points[-(1:floor(n/2))] # 2nd random half is testing candidate.component.numbers <- 2: loglikes <- vector(length=1+length(candidate.component.numbers))
mu<-mean(snoq[train]) # MLE of mean sigma <- sd(snoq[train])*sqrt((n-1)/n) # MLE of standard deviation loglikes[1] <- sum(dnorm(snoq[test],mu,sigma,log=TRUE)) for (k in candidate.component.numbers) { mixture <- normalmixEM(snoq[train],k=k,maxit=400,epsilon=1e-2) loglikes[k] <- loglike.normalmix(snoq[test],mixture=mixture) }
When you run this, you will probably see a lot of warning messages saying “One of the variances is going to zero; trying new starting values.” The issue is that we can give any one value of x arbitrarily high likelihood by centering a Gaussian there and letting its variance shrink towards zero. This is however generally considered unhelpful — it leads towards the pathologies that keep us from doing pure maximum likelihood estimation in non-parametric problems (lecture 6) — so when that happens the code recognizes it and starts over. If we look at the log-likelihoods, we see that there is a dramatic improvement with the first few components, and then things slow down a lot^3 :
> loglikes [1] -17656.86 -16427.83 -15808.77 -15588.44 -15446.77 -15386. [7] -15339.25 -15325.63 -15314.22 -15315.
(See also Figure 4). This favors nine components to the mixture. It looks like Figure 5. The calibration is now nearly perfect, at least on the training data (Figure 1.3).
(^3) Notice that the numbers here are about half of the log-likelihood we calculated for the two-component mixture on the complete data. This is as it should be, because log-likelihood is proportional to the number of observations. (Why?) It’s more like the sum of squared errors than the mean squared error. If we want something which is directly comparable across data sets of different size, we should use the log-likelihood per observation.
Precipitation in Snoqualmie Falls
Precipitation (1/100 inch)
Density
0 100 200 300 400
snoq.k9 <- normalmixEM(snoq,k=9,maxit=400,epsilon=1e-2) plot(hist(snoq,breaks=101),col="grey",border="grey",freq=FALSE, xlab="Precipitation (1/100 inch)",main="Precipitation in Snoqualmie Falls") lines(density(snoq),lty=2) sapply(1:9,plot.normal.components,mixture=snoq.k9)
Figure 5: As in Figure 2, but using the nine-component Gaussian mixture.
0.0 0.2 0.4 0.6 0.8 1.
Theoretical CDF
Empirical CDF
distinct.snoq <- sort(unique(snoq)) tcdfs <- pnormmix(distinct.snoq,mixture=snoq.k9) ecdfs <- ecdf(snoq)(distinct.snoq) plot(tcdfs,ecdfs,xlab="Theoretical CDF",ylab="Empirical CDF",xlim=c(0,1), ylim=c(0,1)) abline(0,1)
Figure 6: Calibration plot for the nine-component Gaussian mixture.
0 50 100 150 200
0
20
40
60
80
Component mean
Component standard deviation
1
234
5
6
7
8
9
plot(0,xlim=range(snoq.k9$mu),ylim=range(snoq.k9$sigma),type="n", xlab="Component mean", ylab="Component standard deviation") points(x=snoq.k9$mu,y=snoq.k9$sigma,pch=as.character(1:9), cex=sqrt(0.5+5*snoq.k9$lambda))
Figure 7: Characteristics of the components of the 9-mode Gaussian mixture. The horizontal axis gives the component mean, the vertical axis its standard deviation. The area of the number representing each component is proportional to the component’s mixing weight.
0 100 200 300 400
Comparison of density estimates Kernel vs. Gaussian mixture
Precipitation (1/100 inch)
Density
plot(density(snoq),lty=2,ylim=c(0,0.04), main=paste("Comparison of density estimates\n", "Kernel vs. Gaussian mixture"), xlab="Precipitation (1/100 inch)") curve(dnormalmix(x,snoq.k9),add=TRUE)
Figure 8: Dashed line: kernel density estimate. Solid line: the nine-Gaussian mixture. Notice that the mixture, unlike the KDE, gives negligible probability to negative precipitation.
plot(0,xlim=c(1,366),ylim=range(snoq.k9$mu),type="n",xaxt="n", xlab="Day of year",ylab="Expected precipiation (1/100 inch)") axis(1,at=1+(0:11)*30) for (year in 1:nrow(snoqualmie.classes)) { points(1:366,snoqualmie.classes[year,],pch=16,cex=0.2) }
Figure 9: Plot of days classified according to the nine-component mixture. Hor- izontal axis: day of the year, numbered from 1 to 366 (to handle leap-years). Vertical axis: expected amount of precipitation on that day, according to the most probable class for the day.
An alternative to using cross-validation to select the number of mixtures is to use hypothesis testing. The k-component Gaussian mixture model is nested within the (k + 1)-component model, so the latter must have a strictly higher likelihood on the training data. If the data really comes from a k-component mixture (the null hypothesis), then this extra increment of likelihood will follow one distribution, but if the data come from a larger model (the alternative), the distribution will be different, and stochastically larger. Based on general likelihood theory, we might expect that the null distribution is, for large sample sizes,
2(log Lk+1 − log Lk) ∼ χ^2 dim(k+1)−dim(k) (2)
where Lk is the likelihood under the k-component mixture model, and dim(k) is the number of parameters in that model. (See the appendix to Lecture 2.) There are however several reasons to distrust such an approximation, including the fact that we are approximating the likelihood through the EM algorithm. We can however simply find the null distribution by simulating from the smaller model, which is to say we can do a parametric bootstrap. While it is not too hard to program this by hand^6 , the mixtools package contains a function to do this for us, called boot.comp, for “bootstrap compar- ison”. Let’s try it out^7.
source("http://www.stat.cmu.edu/~cshalizi/402/lectures/20-mixture-examples/bootcomp.R") snoq.boot <- boot.comp(snoq,max.comp=10,mix.type="normalmix", maxit=400,epsilon=1e-2)
This tells boot.comp() to consider mixtures of up to 10 components (just as we did with cross-validation), increasing the size of the mixture it uses when the difference between k and k + 1 is significant. (The default is “significant at the 5% level”, as assessed by 100 bootstrap replicates, but that’s controllable.) The command also tells it what kind of mixture to use, and passes along control settings to the EM algorithm which does the fitting. Each individual fit is fairly time-consuming, and we are requiring 100 at each value of k. This took about five minutes to run on my laptop. This selected three components (rather than nine), and accompanied this decision with a rather nice trio of histograms explaining why (Figure 10). Re- member that boot.comp() stops expanding the model when there’s even a 5% chance of that the apparent improvement could be due to mere over-fitting. This is actually pretty conservative, and so ends up with rather fewer components than cross-validation. (^6) Exercise: Try it! (^7) As of this writing (5 April 2011), there is a subtle, only-sporadically-appearing bug in the version of this function which is part of the released package. The bootcomp.R file on the class website contains a fix, kindly provided by Dr. Derek Young, and should be sourced after loading the package, as in the code example following. Dr. Young informs me that the fix will be incorporated in the next release of the mixtools package, scheduled for later this month.
Let’s explore the output of boot.comp(), conveniently stored in the object snoq.boot.
> str(snoq.boot) List of 3 $ p.values : num [1:3] 0 0.01 0. $ log.lik :List of 3 ..$ : num [1:100] 5.889 1.682 9.174 0.934 4. ... ..$ : num [1:100] 2.434 0.813 3.745 6.043 1. ... ..$ : num [1:100] 0.693 1.418 2.372 1.668 4. ... $ obs.log.lik: num [1:3] 5096 2354 920
This tells us that snoq.boot is a list with three elements, called p.values, log.lik and obs.log.lik, and tells us a bit about each of them. p.values contains the p-values for testing H 1 (one component) against H 2 (two compo- nents), testing H 2 against H 3 , and H 3 against H 4. Since we set a threshold p-value of 0.05, it stopped at the last test, accepting H 3. (Under these circum- stances, if the difference between k = 3 and k = 4 was really important to us, it would probably be wise to increase the number of bootstrap replicates, to get more accurate p-values.) log.lik is itself a list containing the bootstrapped log-likelihood ratios for the three hypothesis tests; obs.log.lik is the vector of corresponding observed values of the test statistic. Looking back to Figure 4, there is indeed a dramatic improvement in the generalization ability of the model going from one component to two, and from two to three, and diminishing returns to complexity thereafter. Stopping at k = 3 produces pretty reasonable results, though repeating the exercise of Figure 9 is no more encouraging for the reality of the latent classes.
2 Multivariate Gaussians
Most of this section repeats the appendix to Lecture 4.
The multivariate Gaussian is just the generalization of the ordinary Gaussian to vectors. Scalar Gaussians are parameterized by a mean μ and a variance σ^2 , which we symbolize by writing X ∼ N (μ, σ^2 ). Multivariate Gaussians, likewise, are parameterized by a mean vector ~μ, and a variance-covariance matrix Σ, written X~ ∼ MVN (~μ, Σ). The components of ~μ are the means of the different components of X~. The i, jth^ component of Σ is the covariance between Xi^ and Xj^ (so the diagonal of Σ gives the component variances). Just as the probability density of scalar Gaussian is
p(x) =
2 πσ^2
exp
(x − μ)^2 σ^2
the probability density of the multivariate Gaussian is
p(~x) = (2π det Σ)−d/^2 exp
(~x − ~μ) · Σ−^1 (~x − ~μ)
Finally, remember that the parameters of a Gaussian change along with linear transformations
X ∼ N (μ, σ^2 ) ⇔ aX + b ∼ N (aμ + b, a^2 σ^2 ) (5)
and we can use this to “standardize” any Gaussian to having mean 0 and vari- ance 1 (by looking at Xσ− μ). Likewise, if
X^ ~ ∼ MVN (~μ, Σ) (6)
then a X~ + ~b ∼ MVN (a~μ + ~b, aΣaT^ ) (7)
In fact, the analogy between the ordinary and the multivariate Gaussian is so complete that it is very common to not really distinguish the two, and write N for both. The multivariate Gaussian density is most easily visualized when d = 2, as in Figure 11. The probability contours are ellipses. The density changes comparatively slowly along the major axis, and quickly along the minor axis. The two points marked + in the figure have equal geometric distance from ~μ, but the one to its right lies on a higher probability contour than the one above it, because of the directions of their displacements from the mean. In fact, we can use some facts from linear algebra to understand the general pattern here, for arbitrary multivariate Gaussians in an arbitrary number of dimensions. The covariance matrix Σ is symmetric and positive-definite, so we know from matrix algebra that it can be written in terms of its eigenvalues and eigenvectors: Σ = vT^ dv (8)