简体   繁体   English

使用R进行马尔可夫链模拟

[英]markov chain simulation using R

I want to plot a graph of probability distributions of states in different time t. 我想绘制不同时间t下状态的概率分布图。 I have the transition matrix 我有转换矩阵

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) 

To plot a graph from p1 to p50, I use the following code. 要绘制从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))

But the result is very strange, can anyone find out where I went wrong in my code? 但是结果却很奇怪,有人能找出我的代码出了错吗?

The problem is your calculation of P1^k . 问题是您对P1^k计算。 In R, using ^ takes the power element by element, not through matrix multiplication. 在R中,使用^逐个获取幂,而不是通过矩阵乘法。 To calculate the matrix power of P1 , you need to multiply it out, or use the %^% operator from the expm package. 要计算P1的矩阵乘方,您需要将其乘以或使用expm包中的%^%运算符。 (There may be other implementations of this operation in other packages, too.) (在其他软件包中也可能有此操作的其他实现。)

So write your loop like this: 因此,像这样编写循环:

# 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]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM