[\ numpy ] Erstellen Sie eine sich bewegende Fenstermatrix aus Zeitreihendaten - Qiita Ich habe versucht, dies auf mehrdimensionale Daten auszudehnen.
Bei ndarray x
wird die letzte Dimension als Zeit betrachtet und ein ndarray y
mit den Daten erstellt, die in einem sich bewegenden Fenster mit einer Breite von $ w $ enthalten sind.
Wenn x
eindimensional ist
x =
\begin{pmatrix}
x_0 & x_1 & \cdots & x_{n-1}
\end{pmatrix}
Dann
y =
\begin{pmatrix}
x_0 & x_1 & \cdots & x_{n-w} \\
x_1 & x_2 & \cdots & x_{n-w+1} \\
\vdots & \vdots & & \vdots \\
x_{w-1} & x_w & \cdots & x_{n-1} \\
\end{pmatrix}
Es wird sein. Auch wenn x
zweidimensional ist
x =
\begin{pmatrix}
x_{0,0} & x_{0,1} & \cdots & x_{0,n-1} \\
\vdots & \vdots & & \vdots \\
x_{m-1,0} & x_{m-1,1} & \cdots & x_{m-1,n-1}
\end{pmatrix}
Dann beim Schneiden in der dritten Dimension
y_{:,:,t} =
\begin{pmatrix}
x_{0,t} & x_{0,t+1} & \cdots & x_{0,t+w-1} \\
\vdots & \vdots & & \vdots \\
x_{m-1,t} & x_{m-1,t+1} & \cdots & x_{m-1,t+w-1}
\end{pmatrix}
Erstellen Sie ein ndarray y
so, dass Dies ist auch dann der Fall, wenn mehr Dimensionen vorhanden sind.
import numpy as np
def moving_window_matrix(x, window_size):
n = x.shape[-1]
new_shape = tuple(x.shape[0:-1]) + (window_size, n-window_size+1)
stride = x.strides[-1]
return np.lib.stride_tricks.as_strided(
x,
shape=new_shape,
strides=x.strides + (stride,)).copy()
x = np.arange(30).reshape((3,10))
print(x)
window_size = 3
y = moving_window_matrix(x, window_size)
print(y[:, :, 0])
print(y[:, :, 1])
print(y[:, :, 2])
print(y[:, :, 7])