簡體   English   中英

R中的KL距離

[英]The KL-distance in R

我想用R計算兩個伽瑪分布的KL距離。

在此輸入圖像描述

這是我的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距離的好方法嗎?

任何建議將不勝感激,

謝謝,馬可

我將定義函數中使用的所有參數。 我的意思是:

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 (如果你將這個函數深埋在程序中,這可能會變得混亂)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM