R中的KL距离

时间:2011-03-09 08:14:27

标签: r integration

我想用R计算两个伽玛分布的KL距离。

enter image description here

这是我的R代码:

theta1 <- 0.2
theta2 <- 2

f <- function(u)
{
     dgamma(u, shape=1/theta1, scale=theta1) * 
      (dgamma(u, shape=1/theta1, scale=theta1, log=TRUE) -
       dgamma(u, shape=1/theta2, scale=theta2, log=TRUE)) 
}

f <- Vectorize(f)
integrate(f, lower=0, upper=Inf)

您对我的R代码有任何评论吗?你认为这是计算KL距离的好方法吗?

任何建议都将不胜感激,

THX, 马可

2 个答案:

答案 0 :(得分:2)

我将定义函数中使用的所有参数。我的意思是:

my.theta1 <- 0.2
my.theta2 <- 2

f <- function(u, theta1, theta2)
{
     dgamma(u, shape=1/theta1, scale=theta1) * 
      (dgamma(u, shape=1/theta1, scale=theta1, log=TRUE) -
       dgamma(u, shape=1/theta2, scale=theta2, log=TRUE)) 
}


f <- Vectorize(f)
integrate(f, lower=0, upper=Inf, theta1 = my.theta1, theta2 = my.theta2)

更明确地防止“意外”,因为您的函数在较高(全局)环境中搜索theta1theta2(如果您将此函数深埋在程序中,则可能会变得混乱)。 / p>

答案 1 :(得分:1)