[英]optimizing markov chain transition matrix calculations?
作為R的中級用戶,我知道for循環通常可以通過使用諸如apply
或其他功能來優化。 但是,我不知道可以優化當前代碼以生成markov鏈矩陣的函數,該矩陣運行速度非常慢。 我是否已盡速而為,還是有我要忽略的事情? 我正在嘗試通過計算給定警報之前24小時內出現的次數來查找馬爾可夫鏈的轉換矩陣。 矢量ids
包含所有可能的ID(大約1700)。
原始矩陣如下所示:
>matrix
id time
1 1376084071
1 1376084937
1 1376023439
2 1376084320
2 1372983476
3 1374789234
3 1370234809
這是我的代碼來嘗試解決這個問題:
matrixtimesort <- matrix[order(-matrix$time),]
frequency = 86400 #number of seconds in 1 day
# Initialize matrix that will contain probabilities
transprobs <- matrix(data=0, nrow=length(ids), ncol=length(ids))
# Loop through each type of event
for (i in 1:length(ids)){
localmatrix <- matrix[matrix$id==ids[i],]
# Loop through each row of the event
for(j in 1:nrow(localmatrix)) {
localtime <- localmatrix[j,]$time
# Find top and bottom row number defining the 1-day window
indices <- which(matrixtimesort$time < localtime & matrixtimesort$time >= (localtime - frequency))
# Find IDs that occur within the 1-day window
positiveids <- unique(matrixtimesort[c(min(indices):max(indices)),]$id)
# Add one to each cell in the matrix that corresponds to the occurrence of an event
for (l in 1:length(positiveids)){
k <- which(ids==positiveids[l])
transprobs[i,k] <- transprobs[i,k] + 1
}
}
# Divide each row by total number of occurrences to determine probabilities
transprobs[i,] <- transprobs[i,]/nrow(localmatrix)
}
# Normalize rows so that row sums are equal to 1
normalized <- transprobs/rowSums(transprobs)
誰能提出建議以優化速度?
使用嵌套循環似乎不是一個好主意。 您的代碼可以向量化以加快速度。
例如,為什么要查找行號的頂部和底部? 您可以簡單地將時間值與“ time_0 + frequency”進行比較:這是矢量化操作。
HTH。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.