converting list of tensors to tensors pytorch(将张量列表转换为张量 pytorch)

本文介绍了将张量列表转换为张量 pytorch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有张量列表,每个张量都有不同的大小,如何使用 pytroch 将此张量列表转换为张量

I have list of tensor each tensor has different size how can I convert this list of tensors into a tensor using pytroch

有关更多信息,我的列表包含张量,每个张量都有不同的大小例如第一个张量大小是 torch.Size([76080, 38])

for more info my list contains tensors each tensor have different size for example the first tensor size is torch.Size([76080, 38])

其他张量的形状在第二个元素中会有所不同,例如列表中的第二个张量是 torch.Size([76080, 36])

the shape of the other tensors would differ in the second element for example the second tensor in the list is torch.Size([76080, 36])

当我使用火炬张量(x)我收到一个错误ValueError:只有一个元素张量可以转换为 Python 标量

when I use torch.tensor(x) I get an error ValueError: only one element tensors can be converted to Python scalars

推荐答案

张量不能容纳变长数据.您可能正在寻找 cat

tensors cant hold variable length data. you might be looking for cat

例如,这里我们有一个包含两个不同大小的张量的列表(在它们的最后一个dim(dim=2)中),我们想创建一个由它们组成的更大的张量,所以我们可以使用 cat 并创建包含两个数据的更大张量.

for example, here we have a list with two tensors that have different sizes(in their last dim(dim=2)) and we want to create a larger tensor consisting of both of them, so we can use cat and create a larger tensor containing both of their data.

还要注意,从 现在起,您不能在 cpu 上使用带有半张量的 cat 所以你应该将它们转换为浮点数,进行连接,然后再转换回一半

also note that you can't use cat with half tensors on cpu as of right now so you should convert them to float, do the concatenation and then convert back to half

import torch

a = torch.arange(8).reshape(2, 2, 2)
b = torch.arange(12).reshape(2, 2, 3)
my_list = [a, b]
my_tensor = torch.cat([a, b], dim=2)
print(my_tensor.shape) #torch.Size([2, 2, 5])

你还没有解释你的目标,所以另一种选择是使用 pad_sequence 像这样:

you haven't explained your goal so another option is to use pad_sequence like this:

from torch.nn.utils.rnn import pad_sequence
a = torch.ones(25, 300)
b = torch.ones(22, 300)
c = torch.ones(15, 300)
pad_sequence([a, b, c]).size() #torch.Size([25, 3, 300])

在这种特殊情况下,您可以使用 torch.cat([x.float() for x in sequence], dim=1).half()

edit: in this particular case, you can use torch.cat([x.float() for x in sequence], dim=1).half()

这篇关于将张量列表转换为张量 pytorch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!