簡體   English   中英

R:有效地將具有最大互相關的時間序列段定位到輸入段?

[英]R: Efficiently locating time series segments with maximal cross-correlation to input segment?

我有一個大約200,000行的長數值時間序列數據(我們稱之為Z )。

在循環中,我一次從Z中對x (約30)個連續行進行子集化,並將它們視為查詢點q

我想在Z中定位y (~300)長度為x的最相關的時間序列段 (與q最相關)。

有效的方法是什么?

下面的代碼找到了你正在尋找的300個細分,並且在我的功能非常強大的Windows筆記本電腦上運行8秒鍾,所以它應該足夠快到達你的目的。

首先,它構造了一個30×by-199971矩陣( Zmat ),其列包含您要檢查的所有長度為30的“時間序列段”。 對矢量q和矩陣Zmat單次調用cor() ,然后計算所有所需的相關系數。 最后,檢查所得的矢量以識別具有最高相關系數的300個序列。

# Simulate data
nZ <- 200000
nq <- 30
Z <- rnorm(nZ)
q <- seq_len(nq)

# From Z, construct a 30 by 199971 matrix, in which each column is a
# "time series segment". Column 1 contains observations 1:30, column 2
# contains observations 2:31, and so on through the end of the series.
Zmat <- sapply(seq_len(nZ - nq + 1),  
               FUN = function(X) Z[seq(from = X, length.out = nq)])

# Calculate the correlation of q with every column/"time series segment.
Cors <- cor(q, Zmat)

# Extract the starting position of the 300 most highly correlated segments    
ids <- order(Cors, decreasing=TRUE)[1:300]

# Maybe try something like the following to confirm that you have
# selected the most highly correlated segments.
hist(Cors, breaks=100)
hist(Cors[ids], col="red", add=TRUE)

天真的解決方案確實很慢(至少幾分鍾 - 我不夠耐心):

library(zoo)
n <- 2e5
k <- 30
z <- rnorm(n)
x <- rnorm(k) # We do not use the fact that x is a part of z
rollapply(z, k, function(u) cor(u,x), align="left")

您可以從最初的時刻和小組中手動計算相關性,但仍需要幾分鍾。

y <- zoo(rnorm(n), 1:n)
x <- rnorm(k)
exy <- exx <- eyy <- ex <- ey <- zoo( rep(0,n), 1:n )
for(i in 1:k) {
  cat(i, "\n")
  exy <- exy + lag(y,i-1) * x[i]
  ey  <- ey  + lag(y,i-1) 
  eyy <- eyy + lag(y,i-1)^2 
  ex  <- ex  + x[i]    # Constant time series
  exx <- exx + x[i]^2  # Constant time series
}
exy <- exy/k
ex <- ex/k
ey <- ey/k
exx <- exx/k
eyy <- eyy/k
covxy <- exy - ex * ey
vx <- exx - ex^2
vy <- eyy - ey^2
corxy <- covxy / sqrt( vx * vy )

一旦你有相關的時間序列,很容易提取前300的位置。

i <- order(corxy, decreasing=TRUE)[1:300]
corxy[i]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM