Answers:
使用二状态马尔可夫链。
如果状态被称为0和1,则链可以由2x2矩阵表示,给出状态之间的转移概率,其中P i j是从状态i迁移到状态j的概率。在此矩阵中,每一行的总和应为1.0。
根据陈述2,我们得到,然后简单守恒说P 10 = 0.7。
根据陈述1,您希望长期概率(也称为平衡或稳态)为。这表示P 1 = 0.05 = 0.3 P 1 + P 01(1 - P 1) 求解得出P 01 = 0.0368421和转换矩阵P = (0.963158 0.0368421 0.7 0.3)
(您可以通过将转换矩阵提高到较高的幂来检查转换矩阵的正确性(在本例中为14)—结果的每一行都给出相同的稳态概率)
我在R中编码@Mike Anderson答案时遇到了麻烦。我无法弄清楚如何使用sapply做到这一点,所以我使用了一个循环。我稍微修改了概率以获得更有趣的结果,然后用“ A”和“ B”表示状态。让我知道你的想法。
set.seed(1234)
TransitionMatrix <- data.frame(A=c(0.9,0.7),B=c(0.1,0.3),row.names=c('A','B'))
Series <- c('A',rep(NA,99))
i <- 2
while (i <= length(Series)) {
Series[i] <- ifelse(TransitionMatrix[Series[i-1],'A']>=runif(1),'A','B')
i <- i+1
}
Series <- ifelse(Series=='A',1,0)
> Series
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1
[38] 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[75] 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1
/ edit:为了回应Paul的评论,这是一个更为优雅的表述
set.seed(1234)
createSeries <- function(n, TransitionMatrix){
stopifnot(is.matrix(TransitionMatrix))
stopifnot(n>0)
Series <- c(1,rep(NA,n-1))
random <- runif(n-1)
for (i in 2:length(Series)){
Series[i] <- TransitionMatrix[Series[i-1]+1,1] >= random[i-1]
}
return(Series)
}
createSeries(100, matrix(c(0.9,0.7,0.1,0.3), ncol=2))
我刚学习R时就写了原始代码,所以有点懈怠。;-)
给定序列,这是估算过渡矩阵的方法:
Series <- createSeries(100000, matrix(c(0.9,0.7,0.1,0.3), ncol=2))
estimateTransMatrix <- function(Series){
require(quantmod)
out <- table(Lag(Series), Series)
return(out/rowSums(out))
}
estimateTransMatrix(Series)
Series
0 1
0 0.1005085 0.8994915
1 0.2994029 0.7005971
与我原来的转换矩阵交换了订单,但是得到了正确的概率。
for
在这里,循环会更干净一些,您知道的长度Series
,因此只需使用即可for(i in 2:length(Series))
。这消除了对的需要i = i + 1
。另外,为什么要先采样A
,然后转换为0,1
?您可以直接采样0
和1
。
createAutocorBinSeries = function(n=100,mean=0.5,corr=0) { p01=corr*(1-mean)/mean createSeries(n,matrix(c(1-p01,p01,corr,1-corr),nrow=2,byrow=T)) };createAutocorBinSeries(n=100,mean=0.5,corr=0.9);createAutocorBinSeries(n=100,mean=0.5,corr=0.1);
以允许任意的,预先指定的滞后1自相关
这是一个基于markovchain
程序包的答案,可以概括为更复杂的依赖关系结构。
library(markovchain)
library(dplyr)
# define the states
states_excitation = c("steady", "excited")
# transition probability matrix
tpm_excitation = matrix(
data = c(0.2, 0.8, 0.2, 0.8),
byrow = TRUE,
nrow = 2,
dimnames = list(states_excitation, states_excitation)
)
# markovchain object
mc_excitation = new(
"markovchain",
states = states_excitation,
transitionMatrix = tpm_excitation,
name = "Excitation Transition Model"
)
# simulate
df_excitation = data_frame(
datetime = seq.POSIXt(as.POSIXct("01-01-2016 00:00:00",
format = "%d-%m-%Y %H:%M:%S",
tz = "UTC"),
as.POSIXct("01-01-2016 23:59:00",
format = "%d-%m-%Y %H:%M:%S",
tz = "UTC"), by = "min"),
excitation = rmarkovchain(n = 1440, mc_excitation))
# plot
df_excitation %>%
ggplot(aes(x = datetime, y = as.numeric(factor(excitation)))) +
geom_step(stat = "identity") +
theme_bw() +
scale_y_discrete(name = "State", breaks = c(1, 2),
labels = states_excitation)
这给您: