【问题标题】:Convert at::Tensor to double in C++ when using LibTorch (PyTorch)使用 LibTorch (PyTorch) 时在 C++ 中将 at::Tensor 转换为 double
【发布时间】:2021-09-10 01:36:14
【问题描述】:

在下面的代码中,我想将loss(数据类型at::Tensor)与lossThreshold(数据类型double)进行比较。在进行比较之前,我想将 loss 转换为 double。我该怎么做?

int main() {
    auto const input1(torch::randn({28*28});
    auto const input2(torch::randn({28*28});
    double const lossThreshold{0.05};
    auto const loss{torch::nn::functional::mse_loss(input1, input2)}; // this returns an at::Tensor datatype
    return loss > lossThreshold ? EXIT_FAILURE : EXIT_SUCCESS;
}

【问题讨论】:

    标签: c++ pytorch libtorch


    【解决方案1】:

    感谢 GitHub CoPilot 推荐了这个解决方案。我想我现在应该辞职了。 :(

    解决方法是使用item<T>()模板函数如下:

    int main() {
        auto const input1(torch::randn({28*28}); // at::Tensor
        auto const input2(torch::randn({28*28}); // at::Tensor
        double const lossThreshold{0.05}; // double
        auto const loss{torch::nn::functional::mse_loss(input1, input2).item<double>()}; // the item<double>() converts at::Tensor to double
        return loss > lossThreshold ? EXIT_FAILURE : EXIT_SUCCESS;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 2020-05-20
      • 2023-04-06
      • 2020-12-07
      • 1970-01-01
      • 2014-07-08
      • 2011-09-28
      • 2012-06-01
      • 2015-02-07
      相关资源
      最近更新 更多