我正在试验斯坦和高斯过程。经过一些错误之后,我发现所有事情的根源都是函数cov_exp_quad的奇怪行为。
特别是,我不明白为什么它返回的矩阵是不对称的。
在这里,斯坦脚本:
data {
int<lower=1> N;
real x[N];
real y[N];
}
transformed data {
matrix[N,N] K = cov_exp_quad(x, y, 1, 1);
}
generated quantities {
matrix[N, N] Cov = K;
}在这里,R代码:
library(rstan)
x <- seq(0, 1, length.out = 3)
X <- expand.grid(x, x)
data_stan <- list(N = dim(X)[1],
x = X[, 1],
y = X[, 2])
fit <- stan(file = "./stan_script.stan",
data = data_stan,
algorithm = "Fixed_param",
warmup = 0,
chains = 1,
iter = 1)
samples <- rstan::extract(fit)
drop(samples$Cov)这是,而不是输出
> drop(samples$Cov)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 1.0000000 1.0000000 1.0000000 0.8824969 0.8824969 0.8824969 0.6065307 0.6065307 0.6065307
[2,] 0.8824969 0.8824969 0.8824969 1.0000000 1.0000000 1.0000000 0.8824969 0.8824969 0.8824969
[3,] 0.6065307 0.6065307 0.6065307 0.8824969 0.8824969 0.8824969 1.0000000 1.0000000 1.0000000
[4,] 1.0000000 1.0000000 1.0000000 0.8824969 0.8824969 0.8824969 0.6065307 0.6065307 0.6065307
[5,] 0.8824969 0.8824969 0.8824969 1.0000000 1.0000000 1.0000000 0.8824969 0.8824969 0.8824969
[6,] 0.6065307 0.6065307 0.6065307 0.8824969 0.8824969 0.8824969 1.0000000 1.0000000 1.0000000
[7,] 1.0000000 1.0000000 1.0000000 0.8824969 0.8824969 0.8824969 0.6065307 0.6065307 0.6065307
[8,] 0.8824969 0.8824969 0.8824969 1.0000000 1.0000000 1.0000000 0.8824969 0.8824969 0.8824969
[9,] 0.6065307 0.6065307 0.6065307 0.8824969 0.8824969 0.8824969 1.0000000 1.0000000 1.0000000为什么这个不对称?谢谢
发布于 2022-08-30 16:20:36
它用每个向量的元素之间的距离来构造一个协方差矩阵,而不是使用[x,y]中点之间的欧几里德距离。例如:
#Squared distance between first element of x and all elements of y
(distSq <- (data_stan$x[1] - data_stan$y)^2)
#Function to create covariance matrix
#Taken from https://mc-stan.org/docs/2_22/functions-reference/covariance.html
cov_exp_quad <- function(alpha,rho,dist2) (alpha^2)*exp((-1/2*(rho^2))*dist2)
#Compare to first row of covariance matrix from Stan - identical
cbind(samples$Cov[1,1,],cov_exp_quad(1,1,distSq))https://stackoverflow.com/questions/69368453
复制相似问题