【问题标题】:How to stack a tensor of shape (n, k) with tensors of shape (k) in libtorch?如何在libtorch中将形状(n,k)的张量与形状(k)的张量堆叠在一起?
【发布时间】:2020-12-07 17:31:30
【问题描述】:

torch::stack 接受 c10::TensorList 并在给出相同形状的张量时工作得很好。但是,当您尝试发送以前的 torch::stacked 张量的输出时,它会失败并导致内存访问冲突。

更具体地说,假设我们有 3 个形状为 4 的张量,例如:

torch::Tensor x1 = torch::randn({4});
torch::Tensor x2 = torch::randn({4});
torch::Tensor x3 = torch::randn({4});
torch::Tensor y = torch::randn({4});

第一轮堆叠很琐碎:

torch::Tensor stacked_xs = torch::stack({x1,x2,x3});

但是,尝试做:

torch::Tensor stacked_result = torch::stack({y, stacked_xs});

会失败。 我希望在 Python 中获得与np.vstack 相同的行为,这是允许的并且有效的。 我该怎么办?

【问题讨论】:

  • 我想不出更好的标题!什么是更好的标题?请提出建议,使其更清晰

标签: c++ torch libtorch


【解决方案1】:

您可以使用torch::unsqueezey 添加维度。然后与cat 连接(不是stack,与numpy 不同,但结果将是您所要求的):

torch::Tensor x1 = torch::randn({4});
torch::Tensor x2 = torch::randn({4});
torch::Tensor x3 = torch::randn({4});
torch::Tensor y = torch::randn({4});

torch::Tensor stacked_xs = torch::stack({x1,x2,x3});
torch::Tensor stacked_result = torch::cat({y.unsqueeze(0), stacked_xs});

也可以根据您的喜好将您的第一个堆栈展平然后重新整形:

torch::Tensor stacked_xs = torch::stack({x1,x2,x3});
torch::Tensor stacked_result = torch::cat({y, stacked_xs.view({-1}}).view({4,4});

【讨论】:

  • 非常感谢。第二种方法对我来说似乎更实用。无论如何,非常感谢您的时间和善意的回应
  • trialNerror:视图解决方案似乎不起作用,因为它导致以下异常:stack expects each tensor to be equal size, but got [4] at entry 0 and [12] at entry 1
  • 是的小错误,将堆栈与猫混淆,感谢您指出。它现在可以工作了:)
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 2018-12-13
  • 2019-09-01
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多