Python 在 Pytorch 中连接两个张量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53512281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:18:33  来源:igfitidea点击:

Concatenate Two Tensors in Pytorch

pythonmachine-learningdeep-learningpytorchtensor

提问by tstseby

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

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

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

我想[100 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.

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

How could I create the required tensor?

我怎样才能创建所需的张量?

回答by Shai

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

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

Guessing from the error message you got:

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

1.

1.

Sizes of tensors must match except in dimension 2
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.

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

2.

2.

Got 32 and 71 in dimension 0
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.

看起来您想要连接的张量的尺寸并不像您期望的那样,您有一个 size(72, ...)而另一个是(32, ...).
你也需要检查这个。

Working code

工作代码

Here's an example of concat

这是 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:

或者,您可以使用functional.pad

from torch.nn import functional as F

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