【问题标题】:markov chain simulation using R使用 R 进行马尔可夫链模拟
【发布时间】:2018-10-20 07:35:49
【问题描述】:

我想绘制不同时间 t 内状态的概率分布图。我有转换矩阵

P1 <- matrix(c(0, 1, 0, 0, 0, 0, 2/3, 1/3, 0, 1, 0, 0, 0, 0, 0, 1), 4, 4, byrow=TRUE) 

要绘制从 p1 到 p50 的图形,我使用以下代码。

library(ggplot2)

initState <- c(1,0,0,0) # The initial state will be state 1

# Initiate probability vectors
one <- c()
two <- c()
three <- c()
four <- c()

# Calculate probabilities for 50 steps.
for(k in 1:50){
  nsteps <- initState*P1^k
  one[k] <- nsteps[1,1]
  two[k] <- nsteps[1,2]
  three[k] <- nsteps[1,3]
  four[k] <- nsteps[1,4]
}

# Make dataframes and merge them
one <- as.data.frame(one)
one$Group <- 'one'
one$Iter <- 1:50
names(one)[1] <- 'Value'

two <- as.data.frame(two)
two$Group <- 'two'
two$Iter <- 1:50
names(two)[1] <- 'Value'

three <- as.data.frame(three)
three$Group <- 'three'
three$Iter <- 1:50
names(three)[1] <- 'Value'

four <- as.data.frame(four)
four$Group <- 'four'
four$Iter <- 1:50
names(four)[1] <- 'Value'

steps <- rbind(one,two,three,four)

# Plot the probabilities using ggplot
ggplot(steps, aes(x = Iter, y = Value, col = Group))+
  geom_line() +
  xlab('Chain Step') +
  ylab('Probability') +
  ggtitle('50 Step Chain Probability Prediction')+
  theme(plot.title = element_text(hjust = 0.5))

但是结果很奇怪,谁能找出我的代码哪里出错了?

【问题讨论】:

    标签: r ggplot2 markov-chains


    【解决方案1】:

    问题在于您对P1^k 的计算。在 R 中,使用 ^ 逐个元素获取幂,而不是通过矩阵乘法。要计算P1 的矩阵幂,您需要将其相乘,或使用expm 包中的%^% 运算符。 (其他包中也可能有此操作的其他实现。)

    所以这样写你的循环:

    # Calculate probabilities for 50 steps.
    P1tok <- diag(4)   # the identity matrix
    for(k in 1:50){
      P1tok <- P1tok %*% P1     # multiply by another P1
      nsteps <- initState*P1tok
      one[k] <- nsteps[1,1]
      two[k] <- nsteps[1,2]
      three[k] <- nsteps[1,3]
      four[k] <- nsteps[1,4]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 2019-09-13
      • 2019-10-20
      • 1970-01-01
      • 2023-03-30
      • 2015-11-15
      相关资源
      最近更新 更多