使用markovchain包来比较两个经验估计的马尔可夫链

时间:2016-11-24 06:48:39

标签: r markov-chains markov

我需要比较两个概率矩阵来知道链的接近程度,所以我会使用测试得到的P值。

我尝试使用markovchain r包,更具体地说是divergenceTest函数。但是,问题是功能没有得到正确实施。它是基于第139页的“Statistical Inference Based on Divergence Measures”一书的测试,我联系了软件包开发人员,但他们仍然没有更正,所以我试图实现,但我遇到了麻烦,任何人都可以帮助我找到错误?

参数:freq_matrix:是用于估计概率矩阵的频率矩阵。假设:用于与估计矩阵进行比较的矩阵。

divergenceTest3 <- function(freq_matrix, hypothetic){  
  n <- sum(freq_matrix)
  empirical = freq_matrix
  for (i in 1:length(hypothetic)){
    empirical[i,] <- freq_matrix[i,]/rowSums(freq_matrix)[i]
  }
  M <- nrow(empirical)
  v <- numeric()
  out <- 2 * n / .phi2(1)
  sum <- 0
  c <- 0  
  for(i in 1:M){    
    sum2 <- 0
    sum3 <- 0    
    for(j in 1:M){
      if(hypothetic[i, j] > 0){
        c <- c + 1
      }      
      sum2 <- sum2 + hypothetic[i, j] * .phi(empirical[i, j] / hypothetic[i, j])
    }    
    v[i] <- rowSums(freq_matrix)[i]
    sum <- sum + ((v[i] / n) * sum2)
  }
  TStat <- out * sum
  pvalue <- 1 - pchisq(TStat, c-M)  
  cat("The Divergence test statistic is: ", TStat, " the Chi-Square d.f. are: ", c-M," the p-value is: ", pvalue,"\n")
  out <- list(statistic = TStat, p.value = pvalue)  
  return(out)
}
# phi function for divergence test
.phi <- function(x) {
  out <- x*log(x) - x + 1
  return(out)
}
# another phi function for divergence test
.phi2 <- function(x) {
  out <- 1/x
  return(out)
}

1 个答案:

答案 0 :(得分:3)

分歧测试已被verifyHomogeneity函数取代。它需要并输入可以强制转换为原始转换矩阵的元素列表(从createSequenceMatrix开始)。然后它测试它们是否属于同一个未知的DTMC。

请参阅以下示例:

myMatr1<-matrix(c(0.2,.8,.5,.5),byrow=TRUE, nrow=2)
myMatr2<-matrix(c(0.5,.5,.4,.6),byrow=TRUE, nrow=2)
mc1<-as(myMatr1,"markovchain")
mc2<-as(myMatr2,"markovchain")
mc
mc2
sample1<-rmarkovchain(n=100, object=mc1)
sample2<-rmarkovchain(n=200, object=mc2)
# should reject
verifyHomogeneity(inputList = list(sample1,sample2))
#should accept
sample2<-rmarkovchain(n=200, object=mc1)
verifyHomogeneity(inputList = list(sample1,sample2))