How to access tensorflow::Tensor C++

2020-07-24 09:02发布

问题:

I am running Tensorflow using its C++ API.

I have the following call that returns four tensors in 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;

The print statement outputs the following:

"Tensor< type: float shape: [1,100,4] values: [[0.00710274419 0.766219556 0.0347728245]]...>"

Now that I have a Tensor with 100 elements and each element has 4 values, how can I iterate through the elements and values?

It seems like I have to call a function to return a Eigen::TensorMap then somehow access the elements. I am just not sure quite how to do that.

Thank you very much for your help!

回答1:

I'm able to do like this

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

and here is the output

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)