[英]How to stack a tensor of shape (n, k) with tensors of shape (k) in libtorch?
torch::stack
接受c10::TensorList
並且在給出相同形狀的張量時工作得很好。 但是,當您嘗試發送之前torch::stack
ed Tensor 的 output 時,它會失敗並給出 memory 訪問沖突。
更具體地說,假設我們有 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});
將失敗。 我希望獲得與np.vstack
中的 np.vstack 相同的行為,這是允許的並且有效。 我該怎么辦?
您可以使用torch::unsqueeze
為y
添加維度。 然后與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});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.