将不同长度的 2D 张量列表转换为一个 3D 张量

发布于 2025-01-13 21:27:55 字数 239 浏览 3 评论 0原文

我有一个包含 3 个张量的列表,其形状为: (8, 2), (8, 4), (8, 6)

我想将此列表转换为以下形状: ( 8, 3, x)

我该怎么做?我知道我需要使用 torch.cattorch.stacktorch.transpose 的某种组合,但我无法弄清楚。

提前致谢!

I have a list of 3 tensors with the shape: (8, 2), (8, 4), (8, 6)

And I want to turn this list into this shape: (8, 3, x)

How do I do this? I know I need to use some combination of torch.cat, torch.stack and torch.transpose, but I can't figure it out.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空城旧梦 2025-01-20 21:27:55

正如您所说,您需要使用torch.cat,还需要torch.reshape。假设如下:

a = torch.rand(8,2)
b = torch.rand(8,4)
c = torch.rand(8,6)

并假设确实可以将张量重塑为 (8,3,-1) 形状,其中 -1 代表只要需要的话:

d = torch.cat((a,b,c), dim=1)
e = torch.reshape(d, (8,3,-1))

我会解释一下。由于 a,b,c 中的第一维不同,因此串联必须沿第一维进行,如变量 d 中所示。然后,您可以重塑张量,如 e 中所示,其中 -1 代表“只要需要”。

As you said, you need to use torch.cat, but also torch.reshape. Assume the following:

a = torch.rand(8,2)
b = torch.rand(8,4)
c = torch.rand(8,6)

And assume that it is indeed possible to reshape the tensors to a (8,3,-1) shape, where -1 stands for as long as it need to be, then:

d = torch.cat((a,b,c), dim=1)
e = torch.reshape(d, (8,3,-1))

I'll explain. Because the 1st dimension if different in a,b,c the concatenation has to be along the 1st dimension, as seen in variable d. Then, you can reshape the tensor as seen in e where the -1 stands for "as long as it needs to be".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文