In many regression and classification problems, even with very complex dependence structures, a simple model with the appropriate basis performs very well. In the normal case, we move from the basic regression approach by expanding our covariates.
MLR:
\(\bf{Y} = {\bf X}\boldsymbol{\beta} + \boldsymbol{\epsilon}\)
Projected into a larger space:
\(\bf{Z} = f(\bf{X})\)
\(\bf{Y} = {\bf Z}\boldsymbol{\beta} + \boldsymbol{\epsilon}\)
This transformation can be simple, or very complex - in any case, it’s problem dependent.
# f(Y|X)
set.seed(124124)
N <- 10
X <- runif(N, -10,10)
Y <- 1 + 0.04*X + 0.15*cos(X/2) - 0.005*X^2
plot(X,Y)
# SLR
lm.out.linear <- lm(Y ~ X)
plot(X,Y); abline(reg = lm.out.linear)
# Poly reg
lm.out.poly <- lm(Y ~ poly(X,degree = 4))
plot(X,Y)
xvals <- seq(-10,10, 0.1)
yvals <- predict(lm.out.poly, newdata = data.frame(X=xvals))
lines(xvals, yvals)
# Spline reg
library(splines)
lm.out.ns <- lm(Y ~ ns(X,df = 4))
plot(X,Y)
xvals <- seq(-10,10, 0.1)
yvals <- predict(lm.out.ns, newdata = data.frame(X=xvals))
lines(xvals, yvals)
# Classification Example
set.seed(123123)
X.class <- rnorm(100, mean = 0, sd = 1)
Y.class <- rnorm(100, mean = 0, sd = 1)
Z <- ifelse(apply(cbind(X.class, Y.class), 1, function(x){sqrt(sum(x^2))}) < 1,0,1)
# Fudge: not quite perfect fit:
Z[1] <- 0
plot(X.class, Y.class, col = Z + 1)
D <- apply(cbind(X.class, Y.class), 1, function(x){sqrt(sum(x^2))})
glm.out <- glm(Z ~ D, family = binomial(link = "logit"))
preds <- ifelse(glm.out$fitted.values > 0.5, 1, 0)
table(preds, Z)
## Z
## preds 0 1
## 0 44 1
## 1 1 54
All of these examples translate immediately to a Bayesian context:
library(rstan)
## Loading required package: StanHeaders
## Loading required package: ggplot2
## rstan (Version 2.19.2, GitRev: 2e1f913d3ca3)
## For execution on a local, multicore CPU with excess RAM we recommend calling
## options(mc.cores = parallel::detectCores()).
## To avoid recompilation of unchanged Stan programs, we recommend calling
## rstan_options(auto_write = TRUE)
## For improved execution time, we recommend calling
## Sys.setenv(LOCAL_CPPFLAGS = '-march=native')
## although this causes Stan to throw an error on a few processors.
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)
stanmodel <- "
data{
int N;
int P;
vector[N] Y;
matrix[N,P] X;
}
parameters{
vector[P] beta;
real ssq;
}
model {
Y ~ normal(X*beta, ssq);
beta ~ normal(0,100);
ssq ~ gamma(0.1,0.1);
}
"
cat(stanmodel, file="stanmodel1.stan")
standata <- list(N = length(X),
P = 5,
Y = Y,
X=cbind(1,ns(X, df = 4)))
smod <- stan_model(file = "stanmodel1.stan", auto_write = TRUE)
result <- sampling(smod,
data = standata,
chains = 3,
pars = c("beta", "ssq"),
warmup = 500,
iter = 2000, verbose = FALSE)
samps <- extract(result, permute=FALSE)
library(RColorBrewer)
tracePlot <- function(parname, obj){
nch <-dim(obj)[2]
if (nch < 2){stop("I'm expecting at least two chains")}
colors <- brewer.pal(nch, name = "Set1")
parIdx <- which(dimnames(obj)[[3]] == parname)
if (length(parIdx) == 0){stop(paste0("No such parameter: ", parname))}
X1 <- obj[,1,parIdx]
ymax = max(as.numeric(obj[,,parIdx]))
ymin = min(obj[,,parIdx])
plot(1:length(X1), X1, type = "l",
col = colors[1],
main = paste0("Trace Plot: ", parname),
xlab = "Iteration", ylab = "Value", ylim = c(ymin,ymax))
for (chNum in 2:nch){
lines(1:length(X1), obj[,chNum,parIdx], col = colors[chNum])
}
}
# Make Trace Plots:
for (parname in dimnames(samps)$parameters[1:5]){
tracePlot(parname, samps)
}
# Formally Check Convergence:
library(coda)
##
## Attaching package: 'coda'
## The following object is masked from 'package:rstan':
##
## traceplot
library(knitr)
mcl <- as.mcmc.list(lapply(1:(dim(samps)[2]), function(i){as.mcmc(x = samps[,i,-dim(samps)[3]])}))
diags <- gelman.diag(mcl, multivariate = FALSE)
if (any(diags$psrf[,2] > 1.1)){
stop("Diagnose Convergence")
}
For some problems, it makes more sense to specify things in terms of a Gaussian Process rather than a simple, finite dimensional Gaussian Distribution.
This shows up in:
There are also deep connections between working with Gaussian processes and many other methods, and they form the basis of many more advanced methods.
Definition: “A Gaussian process is a collection of random variables, any finite number of which have a joint Gaussian distribution” (GPML Ch 2)
Much as the normal distribution is completely determined by its mean and variance, and the multivariate normal is completely determined by its mean vector and covariance matrix, a Gaussian stochastic process is determined by its mean function and covariance function. Instead of thinking about a particular density (which we may evaluate at various points in the parameter space), we instead think about a Gaussian process as generating a distribution for a given configuration of inputs. One way to express this is a covariance function - for example, a one dimensional exponential covariance function describing the covariance between points with distance \(d\) is:
\(\sigma^2exp(-\phi d)\) (Banerjee et. al. 2015)
These functions are often called “kernels”, and are also sometimes represented on a different scale (variogram, semivariogram)
C <- function(d, sigma_sq = 1, phi = 0.5){
sigma_sq*exp(-phi*d)
}
xv <- seq(0,100,length = 100)
covs <- sapply(xv, C, phi = 0.5)
plot(xv, covs)
Important concepts for Gaussian Processes: stationarity and isotropy.
This isn’t just an abstract concept - we can generate samples from Gaussian Processes at given points.
xvals <- seq(0.1, 10, length = 100)
K <- matrix(NA, nrow = 100, ncol = 100)
diag(K) <- 2
for (i in 1:(nrow(K)-1)){
for (j in (i+1):ncol(K)){
K[i,j] <- C(abs(xvals[i] - xvals[j]), phi = 0.25, sigma_sq = 2)
K[j,i] <- K[i,j]
}
}
image(K)
library(mvtnorm)
y <- rmvnorm(n = 1, mean = rep(0, ncol(K)), sigma = K)
plot(xvals, y, type = "l")
# f(phi, sigmaSq. Y'| Y, X)
Here’s STAN code for simulating from the gaussian process with mean zero and the specified covariance function (from here):
gaussian_process <- function(X, meanFunc, varFunc){
mean = meanFunc(X)
variance = varFunc(X)
function(X){dmvnorm(X, mean = mean, sigma = variance)}
}
gp1 <- "
data {
int<lower=1> N;
real x[N];
}
transformed data {
matrix[N, N] K;
vector[N] mu = rep_vector(0, N);
for (i in 1:(N - 1)) {
K[i, i] = 2;
for (j in (i + 1):N) {
K[i, j] = 2*exp(-0.1 * square(x[i] - x[j]));
K[j, i] = K[i, j];
}
}
K[N, N] = 1 + 0.1;
}
parameters {
vector[N] y;
}
model {
y ~ multi_normal(mu, K);
}"
cat(gp1, file= "stanmodel2.stan")
smod <- stan_model(file = "stanmodel2.stan", auto_write = TRUE)
## Warning in readLines(file, warn = TRUE): incomplete final line found on 'H:
## \Courses\BIOS-7330 (Fall 2019)\gh-pages\Labs\Lab_11\stanmodel2.stan'
result <- stan(file = "stanmodel2.stan",
data = list(N = 5, x = c(1,4,5,9,10)),
iter = 10, verbose = FALSE)
## Warning in readLines(file, warn = TRUE): incomplete final line found on 'H:
## \Courses\BIOS-7330 (Fall 2019)\gh-pages\Labs\Lab_11\stanmodel2.stan'
## Warning in .local(object, ...): some chains had errors; consider specifying
## chains = 1 to debug
## here are whatever error messages were returned
## [[1]]
## Stan model 'stanmodel2' does not contain samples.
##
## [[2]]
## Stan model 'stanmodel2' does not contain samples.
##
## [[3]]
## Stan model 'stanmodel2' does not contain samples.
##
## [[4]]
## Stan model 'stanmodel2' does not contain samples.
samps <- extract(result)
## Stan model 'stanmodel2' does not contain samples.
for(i in 1:10){
plot(c(1,4,5,9,10), samps$y[i,], type = "b")
}
result <- stan(file = "stanmodel2.stan",
data = list(N = 100, x = 1:100),
iter = 10, verbose = FALSE)
## Warning in readLines(file, warn = TRUE): incomplete final line found on 'H:
## \Courses\BIOS-7330 (Fall 2019)\gh-pages\Labs\Lab_11\stanmodel2.stan'
## Warning in readLines(file, warn = TRUE): some chains had errors; consider
## specifying chains = 1 to debug
## here are whatever error messages were returned
## [[1]]
## Stan model 'stanmodel2' does not contain samples.
##
## [[2]]
## Stan model 'stanmodel2' does not contain samples.
##
## [[3]]
## Stan model 'stanmodel2' does not contain samples.
##
## [[4]]
## Stan model 'stanmodel2' does not contain samples.
samps <- extract(result)
## Stan model 'stanmodel2' does not contain samples.
for(i in 1:10){
plot(1:100, samps$y[i,], type = "b")
}
result <- stan(model_code = gp1,
data = list(N = 100, x = seq(0,10000,length = 100)),
iter = 10, verbose = FALSE)
## Warning: There were 3 transitions after warmup that exceeded the maximum treedepth. Increase max_treedepth above 10. See
## http://mc-stan.org/misc/warnings.html#maximum-treedepth-exceeded
## Warning: Examine the pairs() plot to diagnose sampling problems
## Warning: The largest R-hat is 3.47, indicating chains have not mixed.
## Running the chains for more iterations may help. See
## http://mc-stan.org/misc/warnings.html#r-hat
## Warning: Bulk Effective Samples Size (ESS) is too low, indicating posterior means and medians may be unreliable.
## Running the chains for more iterations may help. See
## http://mc-stan.org/misc/warnings.html#bulk-ess
## Warning: Tail Effective Samples Size (ESS) is too low, indicating posterior variances and tail quantiles may be unreliable.
## Running the chains for more iterations may help. See
## http://mc-stan.org/misc/warnings.html#tail-ess
samps <- extract(result)
for(i in 1:10){
plot(samps$y[i,], type = "b")
}
In practice, there are optimizations we can make to ensure things run faster.
First, in STAN, the “cov_exp_quad” implements the exponential covariance kernel. (More Info).
Second, we can use the Cholesky decomposition to generate random normals with appropriate structure - depending on where this fits in the algorithm, we might only have to compute it once (or at least infrequently).
For example:
rmultnorm.chol <- 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)
}
covmat <- toeplitz(c(2,0.5,0.4,0.2,0,0,0,0,0,0))
mu <- rep(0, ncol(covmat))
system.time({n1 <- rmultnorm.chol(1000, mu, covmat)})
## user system elapsed
## 0 0 0
library(mvtnorm)
system.time({n2 <- rmvnorm(1000, mu, covmat)})
## user system elapsed
## 0 0 0
plot(n1[,1], n1[,2], col = rgb(0,0,1,0.1), pch = 16)
points(n2[,1], n2[,2], col = rgb(1,0,0,0.1), pch = 16)
In the GP example above, the covariance matrix is fixed, so we don’t need to recompute it on every iteration.
The true utility of GP approaches becomes clearer when we condition on observed data - in other words, when we fit the models.
set.seed(124124)
N <- 100
X <- runif(N, -20,20)
Y <- 1 + 0.04*X + 0.15*cos(X/2) - 0.005*X^2 + rnorm(N, sd = 0.1)
smod <- stan_model(file = "gpfit1.stan",save_dso = TRUE, auto_write = TRUE)
result <- sampling(smod, data = list(N = length(Y), x=X, y = Y),
chains = 1, iter = 1000, warmup = 500, pars = "f")
##
## SAMPLING FOR MODEL 'gpfit1' NOW (CHAIN 1).
## Chain 1:
## Chain 1: Gradient evaluation took 0.002 seconds
## Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 20 seconds.
## Chain 1: Adjust your expectations accordingly!
## Chain 1:
## Chain 1:
## Chain 1: Iteration: 1 / 1000 [ 0%] (Warmup)
## Chain 1: Iteration: 100 / 1000 [ 10%] (Warmup)
## Chain 1: Iteration: 200 / 1000 [ 20%] (Warmup)
## Chain 1: Iteration: 300 / 1000 [ 30%] (Warmup)
## Chain 1: Iteration: 400 / 1000 [ 40%] (Warmup)
## Chain 1: Iteration: 500 / 1000 [ 50%] (Warmup)
## Chain 1: Iteration: 501 / 1000 [ 50%] (Sampling)
## Chain 1: Iteration: 600 / 1000 [ 60%] (Sampling)
## Chain 1: Iteration: 700 / 1000 [ 70%] (Sampling)
## Chain 1: Iteration: 800 / 1000 [ 80%] (Sampling)
## Chain 1: Iteration: 900 / 1000 [ 90%] (Sampling)
## Chain 1: Iteration: 1000 / 1000 [100%] (Sampling)
## Chain 1:
## Chain 1: Elapsed Time: 102.73 seconds (Warm-up)
## Chain 1: 65.624 seconds (Sampling)
## Chain 1: 168.354 seconds (Total)
## Chain 1:
samps <- extract(result, permute = FALSE)
dimnames(samps)
## $iterations
## NULL
##
## $chains
## [1] "chain:1"
##
## $parameters
## [1] "f[1]" "f[2]" "f[3]" "f[4]" "f[5]" "f[6]" "f[7]"
## [8] "f[8]" "f[9]" "f[10]" "f[11]" "f[12]" "f[13]" "f[14]"
## [15] "f[15]" "f[16]" "f[17]" "f[18]" "f[19]" "f[20]" "f[21]"
## [22] "f[22]" "f[23]" "f[24]" "f[25]" "f[26]" "f[27]" "f[28]"
## [29] "f[29]" "f[30]" "f[31]" "f[32]" "f[33]" "f[34]" "f[35]"
## [36] "f[36]" "f[37]" "f[38]" "f[39]" "f[40]" "f[41]" "f[42]"
## [43] "f[43]" "f[44]" "f[45]" "f[46]" "f[47]" "f[48]" "f[49]"
## [50] "f[50]" "f[51]" "f[52]" "f[53]" "f[54]" "f[55]" "f[56]"
## [57] "f[57]" "f[58]" "f[59]" "f[60]" "f[61]" "f[62]" "f[63]"
## [64] "f[64]" "f[65]" "f[66]" "f[67]" "f[68]" "f[69]" "f[70]"
## [71] "f[71]" "f[72]" "f[73]" "f[74]" "f[75]" "f[76]" "f[77]"
## [78] "f[78]" "f[79]" "f[80]" "f[81]" "f[82]" "f[83]" "f[84]"
## [85] "f[85]" "f[86]" "f[87]" "f[88]" "f[89]" "f[90]" "f[91]"
## [92] "f[92]" "f[93]" "f[94]" "f[95]" "f[96]" "f[97]" "f[98]"
## [99] "f[99]" "f[100]" "lp__"
# Rho:
plot(samps[,,3])
s2 <- extract(result)
plot(X,Y)
points(X, apply(s2$f,2 , mean), col = "red")
lines(X[order(X)], apply(s2$f, 2 , mean)[order(X)], col = "red")
lines(X[order(X)], apply(s2$f, 2 , quantile, probs = 0.025)[order(X)], col = "red", lty = 2)
lines(X[order(X)], apply(s2$f, 2 , quantile, probs = 0.975)[order(X)], col = "red", lty = 2)
We’re not usually just interested in estimating these covariance terms and interpolating, however. Often we want to forecast outside the range of the data. The easiest way to code this is to simply break our data up into two parts - observed and unobserved. This is implemented in this STAN file.
One drawback to such an approach is that it involves working with large matrices - if we have \(N_1\) observations and \(N_2\) points at which we want forecasts, this involves working with an \(N\times N\) kernel matrix, where \(N=N_1+N_2\).
In contrast, if we’re working with Gaussians, the conditional distribution for a subset of the observations has a closed form. We can use this fact to simply sample from the conditional distribution of our prediction points, given the observed data. This process is implemented in this STAN file, which we apply below:
set.seed(124124)
N <- 20
X <- c(runif(N, -10,10),25)
Y <- 1 + 0.04*X + 0.15*cos(X/2) - 0.1*X^2 +0.0008*X^4 + rnorm(N+1, sd = 0.5)
Y[length(Y)] <- -3
# Center Y:
ymean <- mean(Y)
Y <- Y - mean(Y)
plot(X,Y)
if (!file.exists("results_2.rda")){
smod2 <- stan_model(file = "gpfit2_5.stan",save_dso = TRUE, auto_write = TRUE)
result.extrap <- sampling(smod2, data = list(N1 = length(Y),
x1 = X, y1=Y,
N2 = 100,
x2 = seq(-50,160, length = 100)),
chains = 1, iter = 3000, warmup = 2000, pars = c("y2", "f2"))
save("result.extrap", file= "results_2.rda", compress ="bzip2")
} else{
load("results_2.rda")
}
samps <- extract(result.extrap, permute = FALSE)
s2 <- extract(result.extrap)
plot(X, Y, ylim = c(-5,10))
lines(seq(-50,160, length = 100), apply(s2$f2, 2, mean), col = "red")
lines(seq(-50,160, length = 100), apply(s2$f2, 2, quantile, probs = 0.025), col = "red", lty = 2)
lines(seq(-50,160, length = 100), apply(s2$f2, 2, quantile, probs = 0.975), col = "red", lty = 2)
#lines(seq(-50,160, length = 100), apply(s2$y2, 2, mean), col = "blue")
lines(seq(-50,160, length = 100), apply(s2$y2, 2, quantile, probs = 0.025), col = "blue", lty = 2)
lines(seq(-50,160, length = 100), apply(s2$y2, 2, quantile, probs = 0.975), col = "blue", lty = 2)
Certainly, working with Gaussian Processes in a full Bayesian framework can come with some serious computational costs. One can also apply these concepts in a frequentist framework:
library(GauPro)
gp <- GauPro(X,Y)
plot(X,Y)
curve(gp$predict(x), add=T, col=2)
curve(gp$predict(x)+2*gp$predict(x, se=T)$se, add=T, col=4)
curve(gp$predict(x)-2*gp$predict(x, se=T)$se, add=T, col=4)
The concept of modeling the covariance among observations separated by distances generalizes immediately to the spatial case - we intuitively expect that observations which are closer together should be more correlated than those which are far apart, though we’re now measuring distance in two dimension.
Notably, the assumptions underlying the covariance function become very important in real world spatial examples - see the reading material from Banerjee et. al. on ICON for more discussion.
These ideas have also gained traction beyond traditional statistical modeling; just as we can model variation in an outcome over one, two, or three dimensional space using covariance functions, we can model variation in an outcome over a generalized covariate space. It is in this role that Gaussian Processes have found application in predictive models. In the next lab, we’ll explore these applications to spatial and predictive problems.
STAN Code here
library(parallel)
set.seed(12123)
N <- 100
X <- cbind(runif(N,-10,10),
runif(N,-10,10))
d1 <- log(apply(t(X)-c(5,5), 2, function(x){sqrt(sum(x^2))}))
d2 <- log(apply(t(X)-c(-10,-5), 2, function(x){sqrt(sum(x^2))}))
Y <- 1+dnorm(d1)*2 +
dnorm(d2)*(-0.75) + rnorm(N, sd = 0.5)
# Center Y:
Y <- Y - mean(Y)
plot(X[,1], X[,2],cex = Y)
if (!file.exists("results_spatial1.rda")){
smod4 <- stan_model(file = "gpfit4_spatial_pars.stan",save_dso = TRUE, auto_write = TRUE)
result.extrap <- sampling(smod4, data = list(N = length(Y),
D = 2,
x = X,
y = Y),
chains = 1, iter = 5000, warmup = 4000, pars = c("rho", "alpha", "sigma"))
save("result.extrap", file= "results_spatial1.rda", compress ="bzip2")
} else{
load("results_spatial1.rda")
}
s2 <- extract(result.extrap)
plot(X[,1], X[,2],cex = Y)
xgd <- as.matrix(expand.grid(seq(-10,10, length = 100),
seq(-10,10, length = 100)))
Xcomb <- rbind(X,xgd)
Ycomb <- c(Y, rep(NA, nrow(xgd)))
sqDist <- as.matrix(dist(Xcomb)^2)
getCov <- function(a, rho, sigma, D){
a^2*exp(-1/(2*rho)*D) + diag(ncol(D))*sigma^2
}
if (!file.exists("latent_means_spatial.rda")){
cl <- makeCluster(4)
clusterExport(cl, c("Y","Ycomb", "s2", "getCov", "sqDist"))
means <- Reduce("rbind", parLapply(cl,
sample(1:nrow(s2$alpha), size = 100), function(idx){
Cv <- getCov(a = s2$alpha[idx], rho = s2$rho[idx], sigma = s2$sigma[idx], D = sqDist)
idx1 <- 1:length(Y)
idx2 <- (length(Y) + 1):length(Ycomb)
Sgi <- solve(Cv[idx1,idx1])
K <- Cv[idx1,idx2]
# Latent mean:
c(t(K) %*% Sgi %*% Y)
}))
stopCluster(cl)
save(means, file = "latent_means_spatial.rda", compress = "bzip2")
} else{
load("latent_means_spatial.rda")
}
mm <- apply(means,2,mean)
imat <- matrix(heat.colors(10)[as.numeric(cut(mm, breaks = 10))], nrow = 100,
byrow=TRUE)
imat <- imat[nrow(imat):1,]
plot(X[,1], X[,2],cex = Y, xlab = "Coord 1", ylab = "Coord 2", main = "")
rasterImage(imat, xleft = -10, xright = 10, ybottom = -10, ytop = 10)
points(X[,1], X[,2], cex = Y)
### Frequentist Example
plot(X[,1], X[,2],cex = Y, xlab = "Coord 1", ylab = "Coord 2", main = "")
gp <- GauPro(X,Y, type = Exponential)
preds <- gp$predict(xgd)
imat <- matrix(heat.colors(10)[as.numeric(cut(preds, breaks = 10))], nrow = 100,
byrow=TRUE)
imat <- imat[nrow(imat):1,]
rasterImage(imat, xleft = -10, xright = 10, ybottom = -10, ytop = 10)
points(X[,1], X[,2], cex = Y)
## Manual Approach:
expandX <- function(X){
cbind(X[,1], X[,2], X[,1]*X[,2], X[,1]^2, X[,2]^2)
}
lm.out <- lm(Y ~ expandX(X))
preds <- cbind(1,expandX(xgd))%*%lm.out$coefficients
imat <- matrix(heat.colors(10)[as.numeric(cut(preds, breaks = 10))], nrow = 100,
byrow=TRUE)
imat <- imat[nrow(imat):1,]
plot(X[,1], X[,2], cex = Y)
rasterImage(imat, xleft = -10, xright = 10, ybottom = -10, ytop = 10)
points(X[,1], X[,2], cex = Y)
Stan code here.
set.seed(125178)
X <- model.matrix(Sepal.Length ~ ., data =iris)
Y <- iris$Sepal.Length
test.idx <- sample(1:nrow(X), size = 30)
train.idx <- setdiff(1:nrow(X), test.idx)
X.test <- X[test.idx,]
Y.test <- Y[test.idx]
X.train <- X[train.idx,]
Y.train <- Y[train.idx]
if (!file.exists("results_generalreg.rda")){
smod5 <- stan_model(file = "gpfit5_General.stan",save_dso = TRUE, auto_write = TRUE)
result.extrap <- sampling(smod5, data = list(N1 = length(Y.train),
N2 = length(Y.test),
D = ncol(X.train),
x1 = X.train,
x2 = X.test,
y1 = Y.train),
chains = 1, iter = 1000, warmup = 500,
pars = c("f2"))
save("result.extrap", file= "results_generalreg.rda", compress ="bzip2")
} else{
load("results_generalreg.rda")
}
s2 <- extract(result.extrap)
test.preds <- apply(s2$f2, 2, mean)
plot(test.preds, Y.test)
cor(test.preds, Y.test)
## [1] 0.8586801
## What patterns is it learning?
for (i in 2:ncol(X.test)){
plot(test.preds ~ X.test[,i], xlab = colnames(X.test)[i])
}
Compare to LM:
lm.out <- lm(Y.train ~ X.train -1)
preds.lm <- X.test %*%lm.out$coefficients
plot(preds.lm, Y.test)
cor(preds.lm, Y.test)
## [,1]
## [1,] 0.8495142
## What patterns is it learning?
for (i in 2:ncol(X.test)){
plot(preds.lm ~ X.test[,i], xlab = colnames(X.test)[i])
}
Find a data set with georeferenced data (latitude and longitude) and a continuous outcome, and put together a Gaussian Process model of the data. Illustrate the fitted surface. Extra bonus points: fit your model using a Matérn covariance structure.