如何在 libtorch 中堆叠形状为 (n, k) 的张量和形状为 (k) 的张量?

How to stack a tensor of shape (n, k) with tensors of shape (k) in libtorch?

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

更具体地说,假设我们有 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 相同的行为,这是允许的并且有效。 我该怎么办?

您可以使用 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});