简体   繁体   English

如何填充张量

[英]How to pad a tensor

How would I pad this tensor by adding element 100 on the end我如何通过在末尾添加元素 100 来填充这个张量

a = tensor([[ 101,  103],
    [ 101, 1045, 223],
    [ 101,  777, 665 , 889],
    [ 101,  888]])

So the result would be:所以结果是:

 b = tensor([[ 101,  103, 100, 100],
    [ 101, 1045, 223, 100],
    [ 101,  777, 665 , 889],
    [ 101,  888, 100, 100]])

I know the functions is torch.nn.functional.pad(), but i could not any simple example with a tensor like this that is probably a 2d tensor.我知道这些函数是 torch.nn.functional.pad(),但我无法使用像这样可能是二维张量的张量的任何简单示例。

Which was surprising, because this is what a (most) typical padding is.这是令人惊讶的,因为这是(最)典型的填充。

Similar to the numpy case, see Convert Python sequence to NumPy array, filling missing values , you could adjust the size of your sub lists using itertools.zip_longest .类似于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

Here, zip_longest adds the missing value, and the second zip transposes the result again.在这里, zip_longest添加缺失值,第二个zip再次转置结果。 You could of cause first create the tensor and then transpose.您当然可以先创建张量,然后转置。

You can use torch.nested.to_padded_tensor ( docs ):您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM