【问题标题】:Torch C++: Getting the value of a int tensor by using *.data<int>()Torch C++:使用 *.data<int>() 获取 int 张量的值
【发布时间】:2019-06-09 13:53:31
【问题描述】:

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

bool 类型也有同样的问题。

【问题讨论】:

    标签: c++ pytorch torch libtorch


    【解决方案1】:

    使用 item&lt;dtype&gt;() 从张量中获取标量。

    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(在 Linux 上使用稳定的 libtorch 测试):

    #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;
    }
    

    【讨论】:

    • 感谢您的回复。我有auto indx =torch::zeros({batch_size},at::dtype(at::kLong));,然后p indx[0].item&lt;long&gt;() 给了我Couldn't find method at::Tensor::item&lt;long&gt;。另外,它带有Byte 之类的类型,我什至在C++ 中没有相同的类型,而bool 只是不起作用。
    • 这些命令在 Linux 和稳定的 libtorch 上运行良好。
    • 所以,你是说auto indx =torch::zeros({batch_size},at::dtype(at::kLong));p indx[0].item&lt;long&gt;() 很适合你,对吧?我也在 Linux 上使用稳定版。那么,有什么区别呢?
    • 我明白了。现在,我还有另一个问题。 cout 工作正常,在调试期间,gdb 无法执行此代码,这很奇怪。你有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2023-02-15
    • 2023-03-14
    相关资源
    最近更新 更多