如何访问 tensorflow::Tensor C++

cod*_*pro 4 c++ eigen tensorflow

我正在使用其 C++ API 运行 Tensorflow。

我有以下调用在 finalOutput 中返回四个张量:

        std::string str1 = "detection_boxes";
        std::string str2 = "detection_scores";
        std::string str3 = "detection_classes";
        std::string str4 = "num_detections";

        std::vector<Tensor> finalOutput;
        status = session->Run({ {InputName, inputTensor} }, { str1, str2, str3, str4 }, {}, &finalOutput);
        std::cout << finalOutput[0].DebugString() << std::endl;
Run Code Online (Sandbox Code Playgroud)

打印语句输出以下内容:

“张量<类型:浮点形状:[1,100,4]值:[[0.00710274419 0.766219556 0.0347728245]]...>”

现在我有一个包含 100 个元素的张量,每个元素有 4 个值,我如何遍历元素和值?

似乎我必须调用一个函数来返回 Eigen::TensorMap 然后以某种方式访问​​元素。我只是不太确定该怎么做。

非常感谢您的帮助!

Tom*_*sun 5

我可以这样做

// tensor<float, 3>: 3 here because it's a 3-dimension tensor
auto output_detection_boxes = outputs[0].tensor<float, 3>();
std::cout << "detection boxes" << std::endl;
for (int i = 0; i < 100; ++i) {
  for (int j = 0; j < 4; ++j)
    // using (index_1, index_2, index_3) to access the element in a tensor
    std::cout << output_detection_boxes(0, i, j)
              << "\t";
  std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这是输出

detection boxes
0.0370  0.0465  0.8914  0.3171
0.0924  0.3944  0.9344  0.9769
0.0155  0.2988  0.8812  0.5263
0.1518  0.3817  0.9316  1.0000
0.0000  0.3285  0.8447  0.6669
0.0389  0.2030  0.8504  0.4749
...

(100 in total)
Run Code Online (Sandbox Code Playgroud)