Numpy Strides实现滑动窗口时左侧填充不符合预期的问题
Let's fix your strided_axis0_overlap function step by step. The core issues with your left-padding logic are incorrect padding length calculation, wrong shape parameter in as_strided, and unnecessary index slicing that's misaligned with your desired window positions.
What's Wrong With the Original Code
- Fixed padding length: Adding
L-1fill values unconditionally doesn't account for the actual number of windows needed. For your example, this leads to extra padding that breaks the last window's alignment with the end of your input array. - Incorrect
shapeinas_strided: Settingshape=(a.shape[0], L)creates way more windows than needed (182 windows instead of 7 for your example), which is inefficient and leads to incorrect slicing. - Misaligned window indices: Slicing with
np.arange(0, len(a), L-overlap)doesn't account for the padding length or the correct number of windows, resulting in the first window missing the second element (1) and the last window not ending at 181.
Fixed Implementation
import numpy as np def strided_axis0_overlap(a, fillval, L, overlap, pad='left'): # a is 1D array assert overlap < L, "Overlap must be less than window size L" step = L - overlap n = len(a) # Calculate number of windows (ceil division to cover all elements) n_windows = (n + step - 1) // step # Calculate total length needed to fit all windows with the given step total_len = L + (n_windows - 1) * step padding_len = total_len - n # Pad the array correctly based on the specified direction if pad == 'left': a_ext = np.concatenate([np.full(padding_len, fillval), a]) elif pad == 'right': a_ext = np.concatenate([a, np.full(padding_len, fillval)]) else: raise ValueError("pad must be either 'left' or 'right'") # Generate strided windows directly with correct stride parameters stride = a_ext.strides[0] return np.lib.stride_tricks.as_strided( a_ext, shape=(n_windows, L), strides=(step * stride, stride) )
Test Your Example
v = np.arange(182) result = strided_axis0_overlap(v, np.nan, L=30, overlap=0, pad='left') # Check first window (should end with 0, 1 as expected) print("First window last 2 elements:", result[0, -2:]) # Output: [0 1] # Check last window (should end with 181) print("Last window last element:", result[-1, -1]) # Output: 181 # Verify total number of windows print("Number of windows:", len(result)) # Output: 7
Key Fixes Explained
- Dynamic padding calculation: We calculate exactly how much padding is needed to ensure the last window ends at the final element of your input array, instead of using a fixed
L-1padding. - Correct window shape: We set
shape=(n_windows, L)to generate only the necessary number of windows, avoiding unnecessary computations. - Direct stride setup: By setting the first stride to
step * stride, we skip directly to the start of each subsequent window, eliminating the need for post-slicing and ensuring proper alignment with your padding direction.
内容的提问来源于stack exchange,提问作者00__00__00
相关产品推荐
相关产品推荐

