12. 将 token 序列切割为重叠的固定大小窗口
在进行 embedding 或训练之前,长文档通常会被切分为重叠的 token chunk,以确保没有句子会在缺乏上下文的情况下被切断。对于长序列,使用 Python 循环处理速度较慢。通过 index arithmetic 可以一次性完成。
编写 sliding_windows(x, size, step) 函数,输入长度为 n 的 1D 数组 x。返回一个 shape 为 (num_windows, size) 的 2D 数组。第 i 个窗口从 index i * step 开始。仅保留完整的窗口。如果 n < size,返回一个 shape 为 (0, size) 且 dtype 与 x 相同的空数组。
def sliding_windows(x, size, step)示例 1
输入: sliding_windows([1, 2, 3, 4, 5], 3, 2)
输出: [[1, 2, 3], [3, 4, 5]]
示例 2
输入: x = np.arange(6), size = 4, step = 1
输出: [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
示例 3
输入: x = np.arange(10), size = 2, step = 3
输出: [[0, 1], [3, 4], [6, 7]]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
提示 1
当 n >= size 时,完整窗口的数量为 (n - size) // step + 1。
提示 2
构建一个 index matrix starts[:, None] + np.arange(size) 并用它来索引 x。
理解思路
滑动窗口会对序列进行固定大小的切片,每个窗口的起始位置比前一个窗口向后移动 step 个位置。与其使用 Python 循环,不如构建一个 2D index array:一列起始位置加上一行 offset,通过 broadcasting 相加。这就像沿着一条带子以固定的间距盖上相同的模板。仅保留完整的窗口。窗口数量为 (n - size) // step + 1;如果漏掉 + 1,则会丢失最后一个窗口。
x = [0, 1, 2, 3, 4, 5, 6], size 3, step 2. Count = (7 - 3) // 2 + 1 = 3. Starts [0, 2, 4], offsets [0, 1, 2]. Index array [[0, 1, 2], [2, 3, 4], [4, 5, 6]], 因此窗口正是这些值。如果 n < size,返回一个 shape 为 (0, size) 且 dtype 与 x 相同的空数组。
starts = arange(count) x step; idx = starts[:, None] + arange(size)[None, :]; return x[idx]. 此方法常用于 embedding 的 token chunking 以及构建时间序列特征。