converting list of tensors to tensors 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将张量列表转换为张量 pytorch
基础教程推荐
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
