使用四种不同的包和绘图进行模拟:
# variance-covariance matrix :
Sigma <- matrix(rbind(c(2,1),
c(1,3)),
nrow=2)
# mean
Mu <- c(0,0)
# degrees of freedom
df <- 30
# number of simulations
nsims <- 1000
# sampling function
sampling <- function(pkg){
switch(pkg,
"mnormt" = mnormt::rmt(nsims, mean=Mu, S=Sigma, df=df),
"mvtnorm" = mvtnorm::rmvt(nsims, sigma=Sigma, df=df) +
matrix(rep(Mu,nsims), ncol=2, byrow=TRUE),
"LaplacesDemon" = LaplacesDemon::rmvt(nsims, mu=Mu, S=Sigma, df=df),
"mixAK" = mixAK::rMVT(nsims, df=df, mu=Mu, Sigma=Sigma)$x
)
}
# sampling
pkgs <- c("mnormt", "mvtnorm", "LaplacesDemon", "mixAK")
sims <- vapply(pkgs,
FUN=sampling, FUN.VALUE=matrix(0, nrow=nsims, ncol=2))
# dataframe for ggplot2
dat <- setNames(cbind(rep(pkgs,each=nsims),
data.frame(do.call(rbind, plyr::alply(sims, 3)))),
c("pkg", "x", "y"))
# plot
library(ggplot2)
ggplot(dat, aes(x=x, y=y)) +
geom_point() +
facet_grid(.~pkg)
笔记:
mvtnorm::rmvt
允许非中心参数向量。
基准
> library(microbenchmark)
> microbenchmark(
+ mnormt = sampling("mnormt"),
+ mvtnorm = sampling("mvtnorm"),
+ LaplacesDemon = sampling("LaplacesDemon"),
+ mixAK = sampling("mixAK"),
+ times=100
+ )
Unit: microseconds
expr min lq mean median uq max neval cld
mnormt 327.989 346.509 402.5122 360.5655 383.9930 3537.376 100 a
mvtnorm 518.982 554.235 615.9864 571.4160 604.8840 3814.493 100 b
LaplacesDemon 375.737 408.536 461.7511 422.5930 437.5425 3646.705 100 a
mixAK 875.530 911.677 938.2057 927.0720 948.2685 1237.434 100 c
更新
我刚刚发现了这个mvnfast
包裹,它是赢家。
df <- 5
p <- 6
Mu <- rep(1, p)
Sigma <- toeplitz(p:1)
sampling <- function(pkg, nsims=1000){
switch(pkg,
"mnormt" = mnormt::rmt(nsims, mean=Mu, S=Sigma, df=df),
"mvtnorm" = sweep(mvtnorm::rmvt(nsims, sigma=Sigma, df=df), 2, Mu, "+"),
"mvnfast" = mvnfast::rmvt(nsims, mu=Mu, sigma=Sigma, df=df)
)
}
> microbenchmark(
+ mnormt = sampling("mnormt"),
+ mvtnorm = sampling("mvtnorm"),
+ mvnfast = sampling("mvnfast"),
+ times=1000
+ )
Unit: microseconds
expr min lq mean median uq max neval
mnormt 757.723 858.573 1156.3124 908.5530 1377.555 5285.759 1000
mvtnorm 1240.112 1408.346 1956.2496 1527.7160 2253.086 98021.043 1000
mvnfast 493.099 528.799 599.8516 554.4585 673.828 3693.114 1000