[英]How to pad a tensor
我如何通過在末尾添加元素 100 來填充這個張量
a = tensor([[ 101, 103],
[ 101, 1045, 223],
[ 101, 777, 665 , 889],
[ 101, 888]])
所以結果是:
b = tensor([[ 101, 103, 100, 100],
[ 101, 1045, 223, 100],
[ 101, 777, 665 , 889],
[ 101, 888, 100, 100]])
我知道這些函數是 torch.nn.functional.pad(),但我無法使用像這樣可能是二維張量的張量的任何簡單示例。
這是令人驚訝的,因為這是(最)典型的填充。
類似於numpy
的情況,請參閱將 Python 序列轉換為 NumPy 數組,填充缺失值,您可以使用itertools.zip_longest
調整子列表的大小。
from itertools import zip_longest
tensor_lists = [
[ 101, 103],
[ 101, 1045, 223],
[ 101, 777, 665 , 889],
[ 101, 888]
]
fillvalue = 100
padded_list = list(zip(*zip_longest(*tensor_lists, fillvalue=fillvalue)))
... # convert to tensor and use it
在這里, zip_longest
添加缺失值,第二個zip
再次轉置結果。 您當然可以先創建張量,然后轉置。
您可以使用torch.nested.to_padded_tensor
( docs ):
import torch
a = [
[101, 103],
[101, 1045, 223],
[101, 777, 665, 889],
[101, 888]
]
a = torch.nested.nested_tensor(list(map(torch.tensor, a)))
torch.nested.to_padded_tensor(a, 100)
tensor([[ 101, 103, 100, 100],
[ 101, 1045, 223, 100],
[ 101, 777, 665, 889],
[ 101, 888, 100, 100]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.