在Pytorch中并置两个张量 [英] Concatenate Two Tensors in Pytorch

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

问题描述

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

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

我想通过填充零个矢量来使其形状为[100 32 1].

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

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

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

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

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

如何创建所需的张量?

推荐答案

为了更好地帮助您,您需要发布代码导致了错误,没有它,我们只是在这里猜测...

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:

Sizes of tensors must match except in dimension 2

pytorch尝试沿第二维连接,而您尝试沿第一维连接.

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

Got 32 and 71 in dimension 0

似乎要连接的张量的尺寸与您预期的不一样,您有一个尺寸为(72, ...)的张量,而另一个尺寸为(32, ...).
您还需要检查一下.

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.

这是concat的示例

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])

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

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天全站免登陆