library(RColorBrewer)
data(iris)
vproj <- function(x, y){
c(x %*% y)/c(y %*% y)*y
}
vnorm <- function(x){
c(sqrt(x%*%x))
}
# Classical Graham Schmidt Algorithm
# (numerically unstable)
CGS <- function(X){
# Create a matrix to hold out outcome
Q <- NA*X
# Start with the first column (normalized)
Q[,1] <- X[,1]/vnorm(X[,1])
# Iterate over the rest of the columns
for (i in 2:ncol(X)){
# Start with column from X
Q[,i] <- X[,i]
# Get the projections of X[,i] onto the previous columns of q
to_subtract <- lapply(1:(i-1), function(j){
vproj(Q[,i], Q[,j])
})
# Subtract the projections
Q[,i] <- Q[,i] - Reduce("+", to_subtract)
# Normalize the result
Q[,i] <- Q[,i]/vnorm(Q[,i])
}
# Return Q
Q
}
X <-model.matrix(Sepal.Length ~ ., data = iris)
Q <- CGS(X)
zapsmall(t(Q) %*% Q)
## (Intercept) Sepal.Width Petal.Length Petal.Width
## (Intercept) 1 0 0 0
## Sepal.Width 0 1 0 0
## Petal.Length 0 0 1 0
## Petal.Width 0 0 0 1
## Speciesversicolor 0 0 0 0
## Speciesvirginica 0 0 0 0
## Speciesversicolor Speciesvirginica
## (Intercept) 0 0
## Sepal.Width 0 0
## Petal.Length 0 0
## Petal.Width 0 0
## Speciesversicolor 1 0
## Speciesvirginica 0 1
beta <- t(Q) %*% iris$Sepal.Length
lm.out <- lm(iris$Sepal.Length ~ Q -1)
cbind(beta, lm.out$coefficients)
## [,1] [,2]
## (Intercept) 71.56592532 71.56592532
## Sepal.Width -1.18837601 -1.18837601
## Petal.Length 9.18843467 9.18843467
## Petal.Width -1.37235537 -1.37235537
## Speciesversicolor -0.05867043 -0.05867043
## Speciesvirginica -0.94099820 -0.94099820
This kind of basis is also much better for constructing projection matrices (instability of CGS notwithstanding):
P_GS <- Q %*% diag(ncol(Q)) %*% t(Q)
P <- X %*% solve(t(X) %*% X) %*% t(X)
yhat1 <- P_GS %*% iris$Sepal.Width
yhat2 <- P %*% iris$Sepal.Width
“The image of the unit sphere under any \(m\times n\) matrix is a hyperelipse” - Trefethen and Bau, Ch. 4
A <- matrix(c(1,0.5,
0.5,1), nrow = 2, byrow= TRUE)
radii <- seq(0,2*pi, length = 1000)
my.circle <- data.frame(x=cos(radii),
y=sin(radii))
with(my.circle, plot(x, y, asp=1, type = "l"))
my.elipse <- as.matrix(my.circle)%*%A
plot(my.elipse[,1], my.elipse[,2], asp=1, type = "l")
More typical data analysis example.
library(mvtnorm)
addVector <- function(vec, ...){
lines(x = c(0,vec[1]), y = c(0, vec[2]), ...)
points(x = c(vec[1]), y = c(vec[2]), pch = 16, ...)
}
Y <- rmvnorm(1000, mean = c(0,0), sigma = A)
decomp <- svd(Y)
Visualize the data in the new basis - these are the “left singular vectors”
plot(decomp$u[,1], decomp$u[,2])
abline(h = 0)
abline(v = 0)
Visualize the transformation
diffvec <- decomp$u %*% diag(decomp$d) - Y
for (i in seq(0,1,length = 100)){
plot(Y + i*diffvec, xlim = c(-4,4), ylim = c(-4,4))
abline(h = 0)
abline(v = 0)
}
Visualize the “right singular vectors” - the preimages in the original
plot(Y[,1], Y[,2], asp=1, pch = 16, col = rgb(0,0,0.2,0.3), main = "Visualization of 'right singular vectors'")
addVector(decomp$v[,1], col = "red", lwd = 2)
addVector(decomp$v[,2], col = "red", lwd = 2)
library(jpeg)
oaks <- readJPEG("./OakleyWoods.jpg")
plot(0,0,xlim = c(0, dim(oaks)[2]), ylim = c(0,dim(oaks)[1]),
asp = 1, type = "n", xlab = "", ylab = "")
rasterImage(oaks, 0, 0, dim(oaks)[2], dim(oaks)[1],
interpolate = FALSE)
This is a histogram of my dog:
hist(oaks)
Transform the image into tiles, each of which will be considered one “observation”:
tileSize <- 20
colkeep <- dim(oaks)[2] - (dim(oaks)[2] %% 20)
rowkeep <- dim(oaks)[1] - (dim(oaks)[1] %% 20)
oaks <- oaks[1:rowkeep, 1:colkeep, ]
ncol_tiles <- colkeep / tileSize
nrow_tiles <- rowkeep / tileSize
# number of "observations"
ncol_tiles*nrow_tiles
## [1] 2142
# Number of "covariates"
(tileSize^2) * 3 # 3 is for RGB
## [1] 1200
gd <- expand.grid(1:nrow_tiles, 1:ncol_tiles)
X <- t(apply(gd, 1,
function(idx){
rowstart <- (idx[1]-1)*tileSize + 1
rowstop <- rowstart + tileSize - 1
colstart <- (idx[2]-1)*tileSize + 1
colstop <- colstart + tileSize - 1
c(oaks[rowstart:rowstop, colstart:colstop,])
}))
plotTile <- function(idx, tile_dat){
tile <- array(tile_dat[idx,], dim = c(tileSize, tileSize,3))
plot(0,0,xlim = c(0, dim(tile)[2]), ylim = c(0,dim(tile)[1]),
asp = 1, type = "n")
rasterImage(tile, 0, 0, dim(tile)[2], dim(tile)[1],
interpolate = FALSE)
}
set.seed(123123)
# Fur
for (idx in sample(1:nrow(X), 10)){
plotTile(idx, X)
}
## Read the help page!!
system.time({decomp <- svd(X, nv = 0, nu = 0)})
## user system elapsed
## 2.91 0.00 2.91
system.time({decomp <- svd(X)})
## user system elapsed
## 6.95 0.02 6.99
plot(decomp$d[1:100])
# Visualize
visualize_component <- function(idx, U, breaks = 10, ...){
# Map the column of U onto a set of indices
y <- as.numeric(cut(U[,i], breaks))
# Configure the color pallette
pal <- brewer.pal(breaks, name = "RdYlGn")
# Create a color matrix
imgMat <- matrix(pal[y], nrow = nrow_tiles, ncol = ncol_tiles)
plot(0,0,xlim = c(1, ncol_tiles), ylim = c(1, nrow_tiles),
asp = 1, type = "n", xlab = "", ylab = "", ...)
rasterImage(imgMat, 1,1, ncol_tiles, nrow_tiles)
}
for (i in 1:5){
visualize_component(i, U = decomp$u, main = paste0("Component ", i))
}
What if we normalize the “variables”?
standardize <- function(x){(x-mean(x))/sd(x)}
X.std <- apply(X, 2, standardize)
decomp <- svd(X.std, nv = 0)
plot(decomp$d)
for (i in 1:5){
visualize_component(i, U = decomp$u, main = paste0("Component ", i))
}