文章目录
- 1. description
- 2. code
1. description
假设我们有三个张量 a,b,c 表示如下:
a = [ 1 2 3 7 ] ; b = [ 4 5 ] ; c = [ 6 ] \begin{equation} a= \begin{bmatrix}1&2&3&7\end{bmatrix};b= \begin{bmatrix}4&5\end{bmatrix};c=\begin{bmatrix}6\end{bmatrix} \end{equation} a=[1237];b=[45];c=[6]
- pad_sequence填充后表示如下:
- p a d _ s e q u e n c e = [ 1 2 3 7 4 5 0 0 6 0 0 0 ] \begin{equation} pad\_sequence= \begin{bmatrix} 1&2&3&7\\\\ 4&5&0&0\\\\ 6&0&0&0\end{bmatrix} \end{equation} pad_sequence= 146250300700
2. code
- pytorch
import torch
from torch.nn.utils import rnnif __name__ == "__main__":run_code = 0a = torch.tensor([1, 2, 3, 7])b = torch.tensor([4, 5])c = torch.tensor([6])padded_sequence = rnn.pad_sequence([a, b, c], batch_first=True)print(f"padded_sequence=\n{padded_sequence}")
- result
padded_sequence=
tensor([[1, 2, 3, 7],[4, 5, 0, 0],[6, 0, 0, 0]])