在 Torch C++ 中创建 BoolTensor Mask

Creating BoolTensor Mask in torch C++

我正在尝试用 BoolTensor 类型的 C++ 为火炬创建掩码。维度 one 中的前 n 个元素需要 False,其余元素需要 True.

这是我的尝试,但我不知道这是否正确(大小是元素的数量):

src_mask = torch::BoolTensor({6, 1});
src_mask[:size,:] = 0;
src_mask[size:,:] = 1;

我不确定是否完全理解您的目标,因此这是我将您的伪代码转换为 C++ 的最佳尝试。

首先,使用 libtorch,您可以通过 torch::TensorOptions 结构声明张量的类型(类型名称以小写字母 k 作为前缀)

其次,由于 torch::Tensor::slice 函数(参见 here and ),您的 python 式切片成为可能。

最后,这会给你类似的东西:

// Creates a tensor of boolean, initially all ones
auto options = torch::TensorOptions().dtype(torch::kBool));
torch::Tensor bool_tensor = torch::ones({6,1}, options);
// Set the slice to 0
int size = 3;
bool_tensor.slice(/*dim=*/0, /*start=*/0, /*end=*/size) = 0;

std::cout << bool_tensor << std::endl;

请注意,这会将前 size 行设置为 0。我假设这就是“维度 x 中的第一个元素”的意思。

另一种方法:

using namespace torch::indexing; //for using Slice(...) function

at::Tensor src_mask = at::empty({ 6, 1 }, at::kBool); //empty bool tensor 
src_mask.index_put_({ Slice(None, size), Slice() }, 0); //src_mask[:size,:] = 0
src_mask.index_put_({ Slice(size, None), Slice() }, 1); //src_mask[size:,:] = 0