如何沿特定维度向 PyTorch 张量添加元素?

新手上路,请多包涵

I have a tensor inps , which has a size of [64, 161, 1] and I have some new data d which has a size of [64, 161] .我如何添加 dinps 这样新的大小是 [64, 161, 2]

原文由 Shamoon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 857
2 个回答

使用 .unsqueeze()torch.cat() 有一种更简洁的方法,它直接使用 PyTorch 接口:

 import torch

# create two sample vectors
inps = torch.randn([64, 161, 1])
d = torch.randn([64, 161])

# bring d into the same format, and then concatenate tensors
new_inps = torch.cat((inps, d.unsqueeze(2)), dim=-1)
print(new_inps.shape)  # [64, 161, 2]

本质上,取消压缩第二维已经使两个张量具有相同的形状;你只需要小心沿着正确的维度解压。类似地,不幸的是, 串联 与其他类似命名的 NumPy 函数的命名不同,但行为相同。请注意,不是让 torch.cat 通过提供 dim=-1 来计算维度,您还可以显式提供要连接的维度,在这种情况下,将其替换为 dim=2

请记住 concatenation 和 stacking 之间的区别,这有助于解决张量维度的类似问题。

原文由 dennlinger 发布,翻译遵循 CC BY-SA 4.0 许可协议

您必须首先重塑 d 以便它具有第三个维度,沿着该维度可以进行串联。当它有了第三维并且两个张量的维数相同之后,就可以使用torch.cat((inps, d),2)来堆叠它们了。

 old_shape = tuple(d.shape)
new_shape = old_shape + (1,)
inps_new = torch.cat( (inps, d.view( new_shape ), 2)

原文由 Conor 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题