BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / NumPy foundations12 of 23 in topic

12. 将 token 序列切割为重叠的固定大小窗口

MediumNumPy foundations

在进行 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,则会丢失最后一个窗口。

Worked example

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 以及构建时间序列特征。
主题
NumPy foundations
相似题目
  • 在填充的 batch 中仅对真实 token 求平均Medium
  • 使用前缀和在常数时间内回答多个区间和查询Medium
  • 使用 searchsorted 和计数 padding 将序列分配到长度桶中Medium
  • 从二进制矩阵计算所有成对的 Jaccard 相似度Medium
所有 NumPy foundations 道题目
反馈
12 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def sliding_windows(x, size, step):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 5 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS