
















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!

















General note: The data came from a ten-dimensional Gaussian. Each variable had an expected value of 100 and a standard deviation of 15. The correlation matrix was random, different for each data set, and did not fit a factor model. Begin by loading the data. Note that each line begins with a row-number; setting row.names = 1 prevents this from becoming a variable column.
x = read.csv("data.csv", row.names=1)
(Alternately, load without row.names and delete the first column.) Check that it’s got the right properties:
> dim(x) [1] 1000 10 > colnames(x) [1] "X.1" "X.2" "X.3" "X.4" "X.5" "X.6" "X.7" "X.8" "X.9" [10] "X.10"
Figure 1:
Non parametric joint density estimate
X.
X.
60
80
100
120
140
60 80 100 120 140
0.00025 0.
0.00045 0.
Figure 2:
(b) Answer: As mentioned in class, and in the notes for Lecture 20, the maximum likelihood estimate for a multivariate Gaussian has the sample mean for its estimated mean vector, and the sample covari- ances for its estimated covariance matrix. (This is also easily checked by writing out the log-likelihood and maximizing.) One could find these means and covariances by hand, but there are built-in functions for the purposes: means = colMeans(x[,c(1,10)]) cov.mat = cov(x[,c(1,10)]) Notice that we only want the first and tenth columns of the original data matrix. Now we evaluate the multivariate Gaussian density (using the mvtnorm package), on the same grid as before, and plot it: require(mvtnorm) fitted.gauss = dmvnorm(np.grid,means,cov.mat) contourplot(fitted.gauss~np.grid[,1]np.grid[,2],cuts=20, xlab="X.1", ylab="X.10", labels=list(cex=0.6), main = "Fitted Gaussian joint density estimate") See Figure 3. (c) Answer: Since we have evaluated the two density estimates on the same grid of points, we can just subtract one from the other, and plot: diff.np.gauss = fitted.gauss - np.plot$dens contourplot(diff.np.gauss~np.grid[,1]np.grid[,2],cuts=20, xlab="X.1", ylab="X.10", labels=list(cex=0.6), main = "Gaussian fit minus non parametric fit") See Figure 4. Even if the Gaussian models is right, there would be some difference between it and a non-parametric estimate. Ideally, however, this should be small, and the difference between the two fits should itself follow the pattern predicted by the parametric model. (Think about what we would get if we divided the data in two, fitted a eparate Gaussian for each, and plotted the difference.)
(d) Answer: The procedures described in problem 1 work for 1-dimensional data, and it is not clear how to adjust these procedures to apply for a two-dimensional distribution with correlation between the variables. Q-Q plots need quantiles, and quantiles need us to be able to put the data in order, which is hard with two variables. The Shapiro-Wilks test also relies on order statistics. Here is an alternative test that could work: look at the difference in log likelihood between parameteric and non-parametric estimate, then get the distribution of this under the Gaussian by simulation (a la comparing regression models). Simulation would require running
60 80 100 120 140
- X.the non-parametric estimate many times, which would take a sub- stantial amount of time. This is why actually implementing the test is considered extra credit. (e) Answer: Extra Credit As usual, we separate calculating the test statistic from doing the simulation. Here we find the difference in log-likelihoods: diff.log.like <- function(data) { my.np <- npudens(~X.1+X.10,data=data,tol=0.1,ftol=0.1) my.means <- colMeans(data) my.cov <- cov(data) np.ll <- sum(log(predict(my.np))) gauss.ll <- sum(log(dmvnorm(data,my.means,my.cov))) return(np.ll - gauss.ll) } Applied to the data, > diff.log.like(x[,c(1,10)]) [1] 15. The simulation is very simple: p2sim <- function() { sim <- rmvnorm(nrow(x),means,cov.mat) sim <- data.frame(X.1=sim[,1],X.10=sim[,2]) return(sim) } produces the right number of random Gaussian vectors (in this case, 1000), with the right means and covariances, and the right column names (for use in diff.log.like. test.stats <- replicate(100,diff.log.like(p2sim())) repeats the simulation 100 times and stores the tests. The test statis- tic is right in the middle of this sampling distribution: > summary(test.stats) Min. 1st Qu. Median Mean 3rd Qu. Max. 10.11 14.52 16.37 15.61 17.93 19. giving no evidence whatsoever against the Gaussian distribution.
x.pca = prcomp(x)
(a) Answer: This is very much the same as the problems in homework 9 asking for plots of the components. Remember that prcomp stores the principal component vectors in an array called rotation, with each column a different principal component.
cumulative.pct = cumsum(x.pca$sdev^2)/sum(x.pca$sdev^2) plot(1:10, cumulative.pct, type = "b", xlab = "Number of components", ylab = "Fraction of variance retained by principal components")
2 4 6 8 10
Number of components
Fraction of variance retained by principal components
Figure 6:
x.fa = factanal(x,factors=1) The factor loadings are stored in an array called loadings. We plot it along with the first principal component, to facilitate the comparison. plot(x.pca$rotation[,1],type="l",col=2, ylim = c(0, 0.8), lwd = 2, xlab = "Column index", ylab = "Projection") lines(x.fa$loadings,type="l",lwd = 2) legend(1, 0.7, c("FA first factor", "PCA first component"), col = c(1,2), text.col = c(1,2), lty = c(1,1), bty = "n") See Figure 7. The factor seems quite similar to the first principal component, as we would hope. The goal of PCA is to find the line
(or plane, hyper-plane...) which comes closest, on average, to the data. The goal of FA is to find a line (plane, etc.) which the data has a Gaussian distribution around. If we are limited to just one factor or component, both methods should at least get something similar.
2 4 6 8 10
Column index
Projection
FA first factor PCA first component
Figure 7:
(b) Answer: Fit a two-factor model: x.fa2 = factanal(x,factors=2) Plot the two factors along with the factor from part (4a) for compar- ison: plot(x.fa2$loadings[,1],type="l", ylim = c(0, 0.8), lwd = 2, xlab = "Column index", ylab = "Projection") lines(x.fa2$loadings[,2],type="l",lwd = 2, col=2) lines(x.fa$loadings,type="l",lwd = 1, col=3, lty = 2) legend(1, 0.7, c("First factor", "Second factor", "Former first factor"), col = c(1,2,3), text.col = c(1,2,3), lty = c(1,1,2), bty = "n")
Instead, fit models with different numbers of factors, and look at the total amount of variance retained by each one.
It is worth thinking through how R calculates this; it also lets us automate it. As a preliminary step in factor analysis (done inside factanal, each of the p observable variables (= columns of the data frame) is centered to have mean zero and scaled to have variance
∑p i=1 1 −^ ψi^ =^ p^ −^
∑p i=1 ψi. The
fraction of variance retained is then
p−
∑p i=1 ψi p = 1^ −^ p
− 1 ∑p i=1 ψi. Let’s encapsulate this in a function:
var.fraction <- function(fa) { psi <- fa$uniquenesses p <- length(psi) return(1-sum(psi)/p) }
Check that this isn’t just crazy talk:
> x.fa
Factor1 Factor SS loadings 0.839 0. Proportion Var 0.084 0. Cumulative Var 0.084 0.
> var.fraction(x.fa2) [1] 0.
so this agrees with R’s internal calculations. Now do this for 1– factors:
var.fraction.with.q.factors <- function(q,data=x) { return(var.fraction(factanal(data,factors=q))) }
cumulative.pct.factors <- sapply(1:5,var.fraction.with.q.factors)
Finally, plot:
plot(1:5, cumulative.pct.factors, type = "l", ylim=c(0,1), xlab = "Number of factors or components", ylab = "Fraction of variance retained") lines(1:5, cumulative.pct[1:5], lty = 2) legend(1,0.8,legend=c("Factors","Principal Components"),lty=c(1,2),bty="n")
See Figure 9. The solid line shows the fraction of variance retained by the first q factors. For comparison the principal component shares are included on the plot as the dashed line. The factors account for less of the variance than the principal components. This is not surprising, because principal components are designed to maximize the amount of variance retained, while factors are supposed to retain the pattern of correlations.
1 2 3 4 5
Number of factors or components
Fraction of variance retained
Factors Principal Components
Figure 9:
of those vectors. (Cautious programming would check that x has the right number of columns to work with the factor-model object fa.) The scale() function centers and scales each column separately.) It returns as many numbers as there are rows of x. loglik.factanal <- function(x,fa) { return(sum(log(dfactanal(x,fa)))) } Here at last is the log-likelihood function.
logliks <- vector(length=5) num.params <- vector(length=5) p= for (q in 1:5) { logliks[q] <- loglik.factanal(x,factanal(x,factors=q)) num.params[q] <- pq-q(q-1)/ } test.stats <- 2*diff(logliks) dfs <- diff(num.params)
Now that we have the test statistics and the number of degrees of freedom, we can calculate p-values: > signif(pchisq(test.stats,df=dfs,lower.tail=FALSE),3) [1] 1.42e-12 2.73e-11 2.24e-06 3.93e- Since even the largest of these, the p-value for comparing 4 factors to 5, is less than 4 × 10 −^3 , we can be quite confident in preferring a five-factor model to any smaller factor model. (c) Answer: As explained in Lecture 18, the usual goodness-of-fit test for factor models uses the observation that every factor model is a multivariate Gaussian distribution, but with a special, constrained covariance matrix. We can thus use the log-likelihood ratio test to test the null hypothesis that the factor model is right against the alternative that an unrestricted Gaussian is genuinely better. This is, in effect, testing whether the covariance matrix obeys the restrictions of the factor model to within sampling error. We could do this by hand, just as above (the number of parameters for the unrestricted Gaussian is p(p − 1)/2 — why?), but factanal actually does this for us. The p-value for this χ^2 test is given in the PVAL element: > x.fa5 <- factanal(x,5) > x.fa5$PVAL objective
(d) Answer: The very small p-value shows that the model does not match the data. This might not be a practically significant issue. We
have only shown, with high statistical significance, that the model is at least a little off. In fact, as mentioned at the beginning of these notes, the factor model is here completely wrong (but nonetheless “explains” 40% of the variance).
myfunction <- function(x, t=100, eps=1e-2/sqrt(nrow(x))) {
stopifnot(require(mixtools),is.array(x))
n <- nrow(x)
w <- rep(c(0,1),length.out=n)
w <- sample(w)
del <- Inf
i <- 0
while ((del > eps) && (i < t)) {
i <- i+
l1 <- mean(abs(w))
l2 <- 1 - l
We can re-run with more iterations until it does converge; 400 steps almost always works here. (Doing this is not required for the prob- lem.) We get two ten-dimensional Gaussians, arbitrarily numbered “1” and “2”, with respective mixing weights of 0.453 and 0.547 (out$l1 and out$l2). Figure 10 shows the mean vectors for the two Gaussians, in the same style as the earlier plots of principal components and factor loadings. Figures 11–12 shows heat-maps of their covariance matrices.
2 4 6 8 10
80
90
100
110
120
Observable
Expected value
stddevs1 <- sqrt(diag(out$s1)) stddevs2 <- sqrt(diag(out$s2)) plot(1:10,out$m1,ylim=c(100-25,100+25),type="l",xlab="Observable", ylab="Expected value") segments(x0=1:10,x1=1:10,y0=out$m1-stddevs1,y1=out$m1+stddevs1) lines(1:10,out$m2,lty=2) segments(x0=(1:10)+0.02,x1=(1:10)+0.02,y0=out$m2-stddevs2,y1=out$m2+stddevs2,lty=2)
Figure 10: Solid line: expected values of the observables from the first compo- nent. Dashed line: expected values from the second component. Vertical lines: ±1 standard deviation, based on the covariance matrix of each component. (The standard deviation lines for component 2 are plotted very slightly off-set to the right for visual clarity.)