[英]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.