Linear Models

Working in R, we get very used to having fast linear modeling tools at our fingertips:

data(iris)
print(system.time(lm.out <- lm(Sepal.Width ~ ., data = iris)))
##    user  system elapsed 
##       0       0       0
summary(lm.out)
## 
## Call:
## lm(formula = Sepal.Width ~ ., data = iris)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.00102 -0.14786  0.00441  0.18544  0.69719 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)        1.65716    0.25595   6.475 1.40e-09 ***
## Sepal.Length       0.37777    0.06557   5.761 4.87e-08 ***
## Petal.Length      -0.18757    0.08349  -2.246   0.0262 *  
## Petal.Width        0.62571    0.12338   5.072 1.20e-06 ***
## Speciesversicolor -1.16029    0.19329  -6.003 1.50e-08 ***
## Speciesvirginica  -1.39825    0.27715  -5.045 1.34e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.2678 on 144 degrees of freedom
## Multiple R-squared:  0.6352, Adjusted R-squared:  0.6225 
## F-statistic: 50.14 on 5 and 144 DF,  p-value: < 2.2e-16

It’s also quite easy to explore concepts in linear models more directly. For example, we can obtain the design matrix for a particular model easily:

X <- model.matrix(Sepal.Width ~ ., data = iris)
dim(X)
## [1] 150   6
colnames(X)
## [1] "(Intercept)"       "Sepal.Length"      "Petal.Length"     
## [4] "Petal.Width"       "Speciesversicolor" "Speciesvirginica"

This allows us to directly solve for the least squares regression coefficients:

Y <- iris$Sepal.Width
solve(t(X)%*%X)%*%t(X)%*%Y
##                         [,1]
## (Intercept)        1.6571639
## Sepal.Length       0.3777734
## Petal.Length      -0.1875666
## Petal.Width        0.6257105
## Speciesversicolor -1.1602853
## Speciesvirginica  -1.3982549
lm.out$coefficients
##       (Intercept)      Sepal.Length      Petal.Length       Petal.Width 
##         1.6571639         0.3777734        -0.1875666         0.6257105 
## Speciesversicolor  Speciesvirginica 
##        -1.1602853        -1.3982549

Recall, that for a linear regression problem, with a design matrix \(X\) with \(n\) rows and \(p\) columns, where \(n>p\) and none of the \(p\) columns are linearly dependent, and data Y we can obtain the normal equations:

\(X^TX\beta = X^TY\)

Solutions to this set of linear equations provides the least squares solution, \(\hat{\beta}\), for the unknown parameters \(\beta\).

In R, we can directly try to solve these, by computing \((X^TX)^{-1}\):

XtXinv <- solve(t(X)%*%X)
image(XtXinv)

We can also directly construct the projection matrix onto the column space of the design matrix \(X\) (the `hat matrix’):

Px <- X %*% solve(t(X)%*%X)%*%t(X)
Yhat <- Px %*% Y
hist(Yhat - lm.out$fitted.values, main = "Not exactly the same, but close")

Things start to get a little more complicated when we have larger problems:

# Simulate True Data:
N <- 10000
P <- 100
X <- cbind(1, matrix(rnorm(N*P), ncol = P))
B <- rnorm(ncol(X))
SSQ <- 0.25
Y <- X %*% B + rnorm(nrow(X), mean = 0, sd = sqrt(SSQ))
system.time(lm.out <- lm(Y ~ X))
##    user  system elapsed 
##    0.19    0.00    0.19
system.time(Px <- X %*% solve(t(X)%*%X)%*%t(X))
##    user  system elapsed 
##    4.93    0.19    5.12
Yhat <- Px %*% Y
hist(Yhat - lm.out$fitted.values, main = "Not exactly the same, but close")

As you can see, the ‘lm’ function is way faster than trying to solve the normal equations directly. Numerical problems can also sneak in pretty easily. As data gets larger, and correlation among covariates increases, trying to directly solve these problems becomes difficult and unstable.

# Make a toeplitz covariance matrix. Adjacent columns are correlated
# https://en.wikipedia.org/wiki/Toeplitz_matrix
V <- toeplitz(c(SSQ, 0.6*SSQ,0.2*SSQ, 0.05*SSQ, rep(0, P-4)))

# Function to generate multivariate normal random variables
# using Cholesky decomposition
# https://en.wikipedia.org/wiki/Cholesky_decomposition
rmultnorm <- function(n,mu,V){
  A <- t(chol(V))
  X <- matrix(rnorm(n*length(mu), mean = 0, sd = 1),
              nrow = length(mu))
  t(A %*% X + mu)
}

# Use it to generate multivariate normal data covariates:
X <- rmultnorm(N, mu = rep(0, ncol(V)), V)
B <- rnorm(ncol(X))
Y <- X %*% B + rnorm(nrow(X), sd = sqrt(SSQ))

system.time(lm.out <- lm(Y ~ X))
##    user  system elapsed 
##    0.10    0.02    0.11
system.time(Px <- X %*% solve(t(X)%*%X)%*%t(X))
##    user  system elapsed 
##    4.79    0.31    5.10
Yhat <- Px %*% Y

hist(Yhat - lm.out$fitted.values, main = "Not great")

Linear Algebra Review

How does R do such a better, faster job? The answer is that modeling procedures in R appropriately use matrix decomposition. Often in data analysis, the mathematical equations used to describe a problem and its solution are a poor basis for an actual algorithm for solving the problem; the normal equations are a perfect example of this. In this section, we’ll start exploring some of the relevant numerical linear algebra tools.

Note: if you’re super rusty on linear algebra, skim the following articles:

Finally, everyone should skim Graham Schmidt, which is listed in the reading material for this week anyway.

Consider the following two vectors:

drawVector <- function(v,...){
  if (length(v) > 2){stop("2d vectors only")}
  lines(x=c(0,v[1]), y = c(0, v[2]), ...)
  points(x = v[1], y = v[2], ...)
}

plot(0,0,xlim = c(0,10), ylim = c(0,10), type = "n", main="Vectors and Projection")
drawVector(c(4,2),pch = 16, col = "blue", lwd = 2)
drawVector(c(0.1,4),pch = 16, col = "red", lwd = 2)

If we want to project the blue vector onto the red vector, we can so so with the projection operator (a one dimensional version of the projection matrix mentioned previously):

# Projects X onto Y
proj <- function(x, y){
    c(x %*% y)/c(y %*% y)*y
}
vnorm <- function(x){
  c(sqrt(x%*%x))
}


plot(0,0,xlim = c(0,10), ylim = c(0,10), type = "n", main="Vectors and Projection")
drawVector(c(4,2),pch = 16, col = "blue", lwd = 2)
drawVector(c(0.1,4),pch = 16, col = "red", lwd = 2)
drawVector(proj(c(4,2), c(0.1,4)),pch = 16, col = "green", lwd = 2)

The green vector is the projection of the blue vector onto the red vector - the shadow the blue vector casts onto the red vector.

Often, in data analysis, we’re interest in the space spanned by a set of vectors (usually column vectors of a design matrix). That is, what points can we describe as linear combinations of the input vectors. For the red and blue vector given in the images above, that space is \(\mathcal{R^2}\), the two dimensional real number field. These are not the only two vectors which could do so, however; the pair \(v1 = (0,1); v2 = (1,0)\) comes to mind. Like these unit vectors in the cartesian coordinate system, we often want to create an orthogonal (perpendicular) basis (spanning set of vectors) from a set of non-orthogonal inputs.

v1 <- c(0.1,4)
v2 <- c(4,2)

u1 <- v1/vnorm(v1)
u2 <- v2 - proj(v2, v1)
u2 <- u2/vnorm(u2)

plot(0,0,xlim = c(0,10), ylim = c(0,10), type = "n", main="Vectors and Projection")
drawVector(u1,pch = 16, col = "blue", lwd = 2)
drawVector(u2,pch = 16, col = "blue", lwd = 2)

drawVector(v1,pch = 16, col = "red", lwd = 2, lty = 2)
drawVector(v2,pch = 16, col = "red", lwd = 2, lty = 2)

# These have length 1
vnorm(u1)
## [1] 1
vnorm(u2)
## [1] 1
# These are (to numerical precision) orthogonal:
u1 %*% u2
##             [,1]
## [1,] 5.89806e-17

Graham Schmidt and QR Decomposition

This idea, of modifying a set of vectors to provide an orthogonal basis spanning the same space as the original set, is the motivation for Graham Schmidt orthonormalization (fancy word for making stuff orthogonal and of length 1). In Graham Schmidt, we iterate over the columns of a matrix, successively making each one orthogonal to the previous ones, and then normalizing it to have length 1. Furthermore, because the projection operator is linear, the columns of our new ortho-normal matrix are constructed as linear combinations of the columns of our input matrix, and vice-versa. We can then write:

\({\bf X} = {\bf Q}{\bf R}\), where \({\bf X}\) is our input design matrix, \({\bf Q}\) is an orthonormal matrix of the same dimension with the same column space, and \({\bf R}\) ends up being a square upper triangular matrix which maps the columns of \({\bf Q}\) back onto the original matrix \({\bf X}\).

As we can see, Graham Schmidt can actually be considered an algorithm for computing the \({\bf QR}\) decomposition of a matrix.

Assignment

  1. If you refer to the reading material, you’ll see that there are two principal versions of the Graham Schmidt algorithm: classical, and modified Graham Schmidt. Complete the following functions:
CGS <- function(X){
  # Computes the orthonormal matrix U with the same column
  # space as X, using the classical Graham Schmidt algorithm
  U <- X
  return(U)
}

UGS <- function(X){
  # Computes the orthonormal matrix U with the same column
  # space as X, using the modified Graham Schmidt algorithm
  U <- X
  return(U)
}
  1. The literature indicates that the classical form of the algorithm is numerically unstable. Complete a regression analysis on the iris data using design matrices constructed with both classical and modified forms of the algorithm. Use the model below:
X <- model.matrix(Sepal.Width ~ Sepal.Length +  Petal.Length + 
                    Petal.Width + Species + Petal.Length:Petal.Width + Sepal.Length:Petal.Width, data = iris)

In order to examine the numerical stability, compare the fitted values resulting from the regression analyses. Also, note that the Graham Schmidt algorithm is supposed to produce orthogonal columns. That indicates that the matrix \({\bf U}^T {\bf{U}}\) should be diagonal, with 1’s on the diagonal and zeros everywhere else. Compare the rounding errors between CGS and MGS:

U <- CGS(X)
U2 <- MGS(X)

# Look at off-diagonals:
max(abs(t(U) %*% U - diag(ncol(U))))
max(abs(t(U2) %*% U2 - diag(ncol(U2))))
  1. Knowing, as we do, that floating point numbers are a tradeoff between magnitude and precision, we might expect data with different average magnitudes to affect the CGS and MGS functions differently. Create a graph demonstrating this.Feel free to use the following as a template, but don’t feel obligated to do so.
for (meanVal in c(0,1,10,100,1000,10000)){
  X <- matrix(rnorm(10000*100, mean = meanVal), ncol = 100)
  U <- CGS(X)
  U2 <- MGS(X)
  e1 <- max(abs(t(U) %*% U - diag(ncol(U))))
  e2 <- max(abs(t(U2) %*% U2 - diag(ncol(U2))))
  # Do something with e1 and e2
}