简体   繁体   English

如何在 pytorch 中连接两个不同尺寸的张量

[英]how to concate two tensors with different dimensions in pytorch

I have two tensors in pytorch with these shapes:我在 pytorch 中有两个具有这些形状的张量:

torch.Size([64, 100]) and torch.Size([64, 100, 256]) torch.Size([64, 100]) 和 torch.Size([64, 100, 256])

I want to concate them by torch.cat but they should be in the same shape and size.我想通过torch.cat连接它们,但它们的形状和大小应该相同。 So I get this error:所以我得到这个错误:

RuntimeError: Tensors must have same number of dimensions: got 2 and 3 RuntimeError:张量必须具有相同的维数:得到 2 和 3

what should I do to fix this problem?我应该怎么做才能解决这个问题? how can I convert 2d PyTorch tensor into 3d tensor OR how can I convert 3d PyTorch tensor to 2d tensor without losing any data? how can I convert 2d PyTorch tensor into 3d tensor OR how can I convert 3d PyTorch tensor to 2d tensor without losing any data? or any other idea?或任何其他想法?

Depending on what you are looking to do with those two tensors, you could consider concatenating on the last axis such that the resulting tensor is shaped (64, 100, 257) .根据您要对这两个张量做什么,您可以考虑在最后一个轴上进行连接,以便生成的张量形状为(64, 100, 257) This requires you first unsqueeze a singleton dimensions on the first tensor:这需要您首先在第一个张量上解压 singleton 尺寸:

>>> x, y = torch.rand(64, 100), torch.rand(64, 100, 256)
>>> z = torch.cat((x[..., None], y), -1)

>>> z.shape
torch.Size([64, 100, 257])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM