在 Pytorch 中连接两个张量 [英] Concatenate Two Tensors in Pytorch

查看:27
本文介绍了在 Pytorch 中连接两个张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

RuntimeError:无效参数 0:张量的大小必须匹配,但维度 2 除外.在/pytorch/aten/src/THC/generic/THCTensorMath.cu:87 的维度 0 中得到 32 和 71

我有一个形状为 [71 32 1] 的张量.

我想通过填充零向量使其成为 [100 32 1] 形状.

我尝试连接形状为零的填充向量 [29 32 1].我收到上述错误.

我尝试使用形状为 [29 32 1] 的零填充向量,但仍然出现错误.

如何创建所需的张量?

解决方案

为了更好的帮助你,需要贴出代码 导致错误,没有它我们只是在这里猜测...

从您收到的错误消息中猜测:

1.

<块引用>

张量的大小必须匹配,维度 2 除外

pytorch 尝试沿第 2 个维度进行连接,而您尝试沿第一个维度进行连接.

2.

<块引用>

在维度 0 中得到 32 和 71

看起来你想要连接的张量的维度并不像你期望的那样,你有一个大小为 (72, ...) 而另一个是 (32,...).
你也需要检查一下.

工作代码

这是一个concat的例子

导入火炬x = 火炬.rand((71, 32, 1))# x.shape = torch.Size([71, 32, 1])px = torch.cat((torch.zeros(29, 32, 1, dtype=x.dtype, device=x.device), x), dim=0)# px.shape = torch.Size([100, 32, 1])

或者,您可以使用 functional.pad:

from torch.nn import 函数为 Fpx = F.pad(x, (0, 0, 0, 0, 29, 0))

RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 2. Got 32 and 71 in dimension 0 at /pytorch/aten/src/THC/generic/THCTensorMath.cu:87

I have a tensor of shape [71 32 1].

I want to make it of shape [100 32 1] by padding zero vectors.

I tried by concatenating a padding vector of zeros of shape [29 32 1]. I get the error above.

I try with a padding vector of zeros of shape [29 32 1], I still get an error.

How could I create the required tensor?

解决方案

In order to help you better, you need to post the code that caused the error, without it we are just guessing here...

Guessing from the error message you got:

1.

Sizes of tensors must match except in dimension 2

pytorch tries to concat along the 2nd dimension, whereas you try to concat along the first.

2.

Got 32 and 71 in dimension 0

It seems like the dimensions of the tensor you want to concat are not as you expect, you have one with size (72, ...) while the other is (32, ...).
You need to check this as well.

Working code

Here's an example of concat

import torch

x = torch.rand((71, 32, 1))
# x.shape = torch.Size([71, 32, 1])
px = torch.cat((torch.zeros(29, 32, 1, dtype=x.dtype, device=x.device), x), dim=0)
# px.shape = torch.Size([100, 32, 1])

Alternatively, you can use functional.pad:

from torch.nn import functional as F

px = F.pad(x, (0, 0, 0, 0, 29, 0))

这篇关于在 Pytorch 中连接两个张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆