Torch C++:使用 *.data<int>() 获取 int 张量的值

Torch C++: Getting the value of a int tensor by using *.data<int>()

在 Libtorch 的 C++ 版本中,我发现我可以通过 *tensor_name[0].data<float>() 获取浮点张量的值,其中我可以使用任何其他有效索引来代替 0。但是,当我通过在张量创建中添加选项 at::kInt 来定义 int 张量时,我无法使用此结构来获取张量的值,即 *tensor_name[0].data<at::kInt>()*tensor_name[0].data<int>() 不起作用,调试器一直说 Couldn't find method at::Tensor::data<at::kInt>Couldn't find method at::Tensor::data<int>。 我可以通过 auto value_array = tensor_name=accessor<int,1>() 获取值,但使用 *tensor_name[0].data<int>() 更容易。你能告诉我如何使用 data<>() 来获取 int 张量的值吗?

我对 bool 类型也有同样的问题。

使用item<dtype>()从张量中获取标量。

int main() {
  torch::Tensor tensor = torch::randint(20, {2, 3});
  std::cout << tensor << std::endl;
  int a = tensor[0][0].item<int>();
  std::cout << a << std::endl;
  return 0;
}

~/l/build ❯❯❯ ./example-app
  3  10   3
  2   5   8
[ Variable[CPUFloatType]{2,3} ]
3

以下代码打印 0(使用稳定的 libtorch 在 Linux 上测试):

#include <torch/script.h>
#include <iostream>                                     

int main(int argc, const char* argv[])                  
{
    auto indx = torch::zeros({20},at::dtype(at::kLong));
    std::cout << indx[0].item<long>() << std::endl;

    return 0;
}