@@ -3,36 +3,35 @@ eps <- 1e-8
3
3
4
4
# fit a Gaussian process model
5
5
GP.fit <- function (X , y , k , g = eps ,
6
- init = rep(10 , ncol(X )),
7
- lower = 0.1 , upper = 1000 ){
6
+ init = rep(10 , ncol(X )),
7
+ lower = 0.1 , upper = 1000 ){
8
8
# X is the input
9
9
# y is output
10
10
# k is the smoothness parameter in matern kernel
11
11
# g is the nugget effect
12
12
# init is the initial value of lengthscale parameter when performing optimization
13
13
# lower is the lower bound of lengthscale parameter when performing optimization
14
14
# upper is the upper bound of lengthscale parameter when performing optimization
15
-
16
15
if (is.null(dim(X ))) X <- matrix (X , ncol = 1 )
17
16
18
17
y <- scale(y , scale = FALSE )
19
18
20
19
n <- length(y )
21
20
if (! is.null(k )){ # if the smoothness is given
22
- nlsep <- function (par , X , Y )
21
+ obj <- function (par , X , Y )
23
22
{
24
23
theta <- par
25
24
R <- sqrt(distance(t(t(X )* theta )))
26
25
K <- matern.kernel(R , k = k )
27
26
Ki <- solve(K + diag(g ,n ))
28
- ldetK <- determinant( K , logarithm = TRUE ) $ modulus
29
- ll <- - ( n / 2 ) * log(t( Y ) %*% Ki %*% Y ) - ( 1 / 2 ) * ldetK
30
- return (- ll )
27
+
28
+ loocv <- mean((diag( 1 / diag( Ki )) %*% Ki %*% Y )^ 2 )
29
+ return (loocv )
31
30
}
32
31
33
32
tic <- proc.time()[3 ]
34
33
35
- outg <- optim(init , nlsep ,
34
+ outg <- optim(init , obj ,
36
35
method = " L-BFGS-B" , lower = lower , upper = upper , X = X , Y = y )
37
36
toc <- proc.time()[3 ]
38
37
@@ -43,30 +42,25 @@ GP.fit <- function(X, y, k, g=eps,
43
42
loocv.save <- rep(0 ,length(k.candidate ))
44
43
45
44
for (i in 1 : length(k.candidate )){
46
- nlsep <- function (par , X , Y )
45
+ obj <- function (par , X , Y )
47
46
{
48
47
theta <- par
49
48
R <- sqrt(distance(t(t(X )* theta )))
50
49
K <- matern.kernel(R , k = k.candidate [i ])
51
50
Ki <- solve(K + diag(g ,n ))
52
- ldetK <- determinant(K , logarithm = TRUE )$ modulus
53
- ll <- - (n / 2 )* log(t(Y ) %*% Ki %*% Y ) - (1 / 2 )* ldetK
54
- return (- ll )
51
+ loocv <- mean((diag(1 / diag(Ki )) %*% Ki %*% Y )^ 2 )
52
+ return (loocv )
55
53
}
56
54
57
55
tic <- proc.time()[3 ]
58
56
59
- outg <- optim(init , nlsep ,
57
+ outg <- optim(init , obj ,
60
58
method = " L-BFGS-B" , lower = lower , upper = upper , X = X , Y = y )
61
59
toc <- proc.time()[3 ]
62
60
63
61
theta.save [i ,] <- outg $ par
64
62
65
- R <- sqrt(distance(t(t(X )* theta.save [i ,])))
66
- K <- matern.kernel(R , k = k.candidate [i ])
67
- Ki <- solve(K + diag(g ,n ))
68
-
69
- loocv.save [i ] <- mean((diag(1 / diag(Ki )) %*% Ki %*% y )^ 2 )
63
+ loocv.save [i ] <- outg $ value
70
64
}
71
65
k <- k.candidate [which.min(loocv.save )]
72
66
theta <- theta.save [which.min(loocv.save ),]
0 commit comments