You are on page 1of 3

Worksheet4_solution

2023-01-14

set.seed(2023)
f <- function(x){
a <- 0.75*exp(-((9*x[1]-2)ˆ2)/4 - ((9*x[2]-2)ˆ2)/4)
b <- 0.75*exp(-((9*x[1]+1)ˆ2)/49 - (9*x[2]+1)/10)
c <- 0.5*exp(-((9*x[1]-7)ˆ2)/4 - ((9*x[2]-3)ˆ2)/4)
d <- 0.2*exp(-((9*x[1]-4)ˆ2) - ((9*x[2]-7)ˆ2))
a + b + c - d
}

#Latin Hypercube Design


m <- 2
n <- 40
mylhs <- function(n, m){
## generate the Latin hypercube
l <- (-(n - 1)/2):((n - 1)/2)
L <- matrix(NA, nrow=n, ncol=m)
for(j in 1:m) L[,j] <- sample(l, n)

## draw the random uniforms and turn the hypercube into a sample
U <- matrix(runif(n*m), ncol=m)
X <- (L + (n - 1)/2 + U)/n
colnames(X) <- paste0("x", 1:m)

## return the design and the grid it lives on for visualization


return(list(X=X, g=c((l + (n - 1)/2)/n,1)))
}

X.lhs <- mylhs(n = 40, m = 2)$X


y.lhs <- apply(X.lhs, 1, f)
colnames(X.lhs) <- paste0("x", 1:m)

#Random Design
X.ran <- matrix(runif(n*m), ncol=m)
colnames(X.ran) <- paste0("x", 1:m)
y.ran <- apply(X.ran, 1, f)

par(mfrow = c(1, 2))


plot(X.lhs)
plot(X.ran)

1
1.0
1.0

0.8
0.8

0.6
0.6
x2

x2

0.4
0.4
0.2

0.2
0.0

0.0 0.2 0.4 0.6 0.8 1.0 0.0 0.0 0.2 0.4 0.6 0.8 1.0

x1 x1

library(DiceKriging)
model.lhs <- km(formula=~1, design = X.lhs, response = y.lhs, covtype="gauss", nugget = 10ˆ(-11), contro

model.ran <- km(formula=~1, design = X.ran, response = y.ran, covtype="gauss", nugget = 10ˆ(-11), contro

library(randtoolbox)

## Warning: package ’randtoolbox’ was built under R version 4.1.3

## Loading required package: rngWELL

## Warning: package ’rngWELL’ was built under R version 4.1.3

## This is randtoolbox. For an overview, type ’help("randtoolbox")’.

testing=sobol(1000,2)
colnames(testing) <- c("x1", "x2")
y.test <- apply(testing, 1, f)

pred.lhs <- predict(model.lhs, testing, type = "SK")


mspe.lhs <- sqrt(mean((y.test - pred.lhs$mean)ˆ2))
pred.ran <- predict(model.ran, testing, type = "SK")
mspe.ran <- sqrt(mean((y.test - pred.ran$mean)ˆ2))

c(mspe.lhs, mspe.ran)

2
## [1] 0.02868812 0.03060818

model.1 <- km(formula=~1, design = X.lhs, response = y.lhs, covtype="gauss", nugget = 10ˆ(-11), control
pred.1 <- predict(model.1, testing, type = "SK")
mspe.1 <- sqrt(mean((y.test - pred.1$mean)ˆ2))

model.2 <- km(formula=~1+x1, design = X.lhs, response = y.lhs, covtype="gauss", nugget = 10ˆ(-11), contr
pred.2 <- predict(model.2, testing, type = "SK")
mspe.2 <- sqrt(mean((y.test - pred.2$mean)ˆ2))

model.3 <- km(formula=~1+x1+x2, design = X.lhs, response = y.lhs, covtype="gauss", nugget = 10ˆ(-11), co
pred.3 <- predict(model.3, testing, type = "SK")
mspe.3 <- sqrt(mean((y.test - pred.3$mean)ˆ2))

model.4 <- km(formula=~1+I(x2ˆ2), design = X.lhs, response = y.lhs, covtype="gauss", nugget = 10ˆ(-11),
pred.4 <- predict(model.4, testing, type = "SK")
mspe.4 <- sqrt(mean((y.test - pred.4$mean)ˆ2))

c(mspe.1, mspe.2, mspe.3, mspe.4)

## [1] 0.02868813 0.02419216 0.02962772 0.21121924

You might also like