Sequence Padding
Pad or truncate a batch of integer sequences to a fixed length.
Given a list of sequences (lists of integers) and a target length:
- If a sequence is shorter than the target, pad it with 0s at the end
- If a sequence is longer than the target, truncate it to the target length
- If a sequence is exactly the target length, leave it unchanged
Function: pad_sequences(sequences, target_len)
- sequences: a list of N integer lists (they may have different lengths)
- target_len: the target length L
Output: The padded/truncated sequences as a list of lists, in the same order as the input.
Example
4 3 1 2 3 5 6 7 8 9 1 2 3 4
[[1, 2, 3, 0], [5, 6, 7, 8], [1, 2, 3, 4]]
- Inputs:
sequencesis a batch of three integer lists with lengths , and ;target_lenis , the length every row must end up with. - The row has length , so it is element short. One goes on the end, giving
[1, 2, 3, 0]. - The row has length , one element too many. Keeping the first elements and dropping the trailing
9gives[5, 6, 7, 8]. [1, 2, 3, 4]already has length exactly , so it passes through unchanged.- Output: a list of lists, each of length , so the batch now forms a regular grid. Notice the original values always keep their positions at the front; padding and truncation only ever touch the end of a row, and the number of zeros added to a row is for a row of length .
Constraints
- Pad with 0s at the END (post-padding)
- Truncate from the END (keep first L elements)
- L >= 1
- Sequences contain non-negative integers