LoginSignup
9
6

More than 5 years have passed since last update.

[numpy] 時系列データから移動窓行列を作成

Posted at

時系列データに対して、移動平均を計算するということはよくあり、このためにpandasのrolling関数などは非常に有用です。

その一方で、より複雑な処理のために、ある時点で移動窓の中に入っているデータを列とする行列を生成したいという状況もしばしば起こります。つまり、時系列データ{$x_1,x_2,\ldots,x_n$}が与えられた時に、次のような行列
$$\begin{pmatrix}
x_1 & x_2 & \ldots & x_m \\
x_2 & x_3 & \ldots & x_{m+1} \\
\vdots & \vdots & \vdots & \vdots \\
x_{n-m+1} & x_{n-m+1} & \ldots & x_n

\end{pmatrix}$$
を作りたいということです。ここで$m$は移動窓のサイズです。このような作業は、時系列データをRNNに入力する際にも必要になってきます。

これを簡単に行うための関数があることを最近見つけたので、ここでシェアしておきます。

def moving_window_matrix(x,window_size):
    n = x.shape[0]
    stride = x.strides[0]
    return np.lib.stride_tricks.as_strided(x, shape=(n-window_size+1, window_size), strides=(stride,stride) ).copy()

以下は簡単な動作例です。

moving_window_matrix(np.arange(10),3)

>>> array([[0, 1, 2],
           [1, 2, 3],
           [2, 3, 4],
           [3, 4, 5],
           [4, 5, 6],
           [5, 6, 7],
           [6, 7, 8],
           [7, 8, 9]])

keyword: moving window, sliding window, rolling, matrix

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6