问题
Consider a Markov chain with state space S = {1, 2, 3, 4}
and transition matrix
P = 0.1 0.2 0.4 0.3
0.4 0.0 0.4 0.2
0.3 0.3 0.0 0.4
0.2 0.1 0.4 0.3
And, take a look at the following source code:
# markov function
markov <- function(init,mat,n,labels)
{
if (missing(labels))
{
labels <- 1:length(init)
}
simlist <- numeric(n+1)
states <- 1:length(init)
simlist[1] <- sample(states,1,prob=init)
for (i in 2:(n+1))
{
simlist[i] <- sample(states, 1, prob = mat[simlist[i-1],])
}
labels[simlist]
}
# matrixpower function
matrixpower <- function(mat,k)
{
if (k == 0) return (diag(dim(mat)[1]))
if (k == 1) return(mat)
if (k > 1) return( mat %*% matrixpower(mat, k-1))
}
tmat = matrix(c(0.1, 0.2, 0.4, 0.3,
0.4, 0.0, 0.4, 0.2,
0.3, 0.3, 0.0, 0.4,
0.2, 0.1, 0.4, 0.3), nrow=4, ncol=4, byrow=TRUE)
p10 = matrixpower(mat = tmat, k=10)
rowMeans(p10)
nn <- 10
alpha <- c(0.25, 0.25, 0.25, 0.25)
set.seed(1)
steps <- markov(init=alpha, mat=tmat, n=nn)
table(steps)/(nn + 1)
Output
> rowMeans(p10)
[1] 0.25 0.25 0.25 0.25
>
.
.
.
> table(steps)/(nn + 1)
steps
1 2 3 4
0.09090909 0.18181818 0.18181818 0.54545455
> ?rowMeans
Why are results so different?
What is the difference between using matrixpower()
and markov()
when it come to compute Pn?
回答1:
Currently you are comparing completely different things. First, I'll focus not on computing Pn, but rather A*Pn, where A is the initial distribution. In that case matrixpower
does the job:
p10 <- matrixpower(mat = tmat, k = 10)
alpha <- c(0.25, 0.25, 0.25, 0.25)
alpha %*% p10
# [,1] [,2] [,3] [,4]
# [1,] 0.2376945 0.1644685 0.2857105 0.3121265
those are the true probabilities of being in states 1, 2, 3, 4, respectively, after 10 steps (after the initial draw made using A).
Meanwhile, markov(init = alpha, mat = tmat, n = nn)
is only a single realization of length nn + 1
and only the last number of this realization is relevant for A*Pn. So, as to try to get similar numbers to the theoretical ones, we need many realizations with nn <- 10
, as in
table(replicate(markov(init = alpha, mat = tmat, n = nn)[nn + 1], n = 10000)) / 10000
#
# 1 2 3 4
# 0.2346 0.1663 0.2814 0.3177
where I simulate 10000 realizations and take only the last state of each realization.
来源:https://stackoverflow.com/questions/56079265/what-is-the-difference-between-matrixpower-and-markov-when-it-comes-to-compu