代码之家  ›  专栏  ›  技术社区  ›  Damien Picard

在C中使用张量浮点值++

  •  0
  • Damien Picard  · 技术社区  · 7 年前

    我正在使用C++中的TensorFlow,使用自定义的训练模型进行预测。我可以加载此模型,对单个图像进行预测,这将返回张量类型:

    Tensor<type: float shape: [1,22] values: [0.00760295521 9.67324567e-08 4.19238063e-07]...>
    

    我可以通过使用另一个TensorFlow会话从该表中创建最大值指标来提取预测类,如中所述 this tutorial

    现在,我尝试批处理图像,总是进行预测,一切都很好,但我有一个输出张量:

    Tensor<type: float shape: [2,22] values: [0.00760294124 9.6732272e-08 4.19237637e-07]...>
    

    事实上,形状现在是[2,22],因为我有2个图像和22个类。现在,我知道了如何从这个张量中提取两个22元素的浮点向量,而不用在经典的C++代码中使用Tensorflow。我发现有些函数在 API doc ,但我不知道如何使用它。

    有没有人有一点关于如何处理这种情况的代码片段?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Damien Picard    7 年前

    我可以这样做:

    std::vector<Tensor> outputs;
        Status run_status = session->Run(feed_dict, {"fc2/Softmax"}, {}, &outputs);
        if (!run_status.ok()) {
            cout << "Running model failed: " << run_status;
            return -1;
        }
        for (auto &t : outputs) // access by reference to avoid copying
        {  
            cout << t.DebugString() + "\n";
            tensorflow::TTypes<float, 2>::Tensor scores = t.flat_inner_dims<float>();
            auto dims = scores.dimensions();
            int imgCount = dims[0];
            int classesCount = dims[1];
            for(int i = 0; i<imgCount; i++) {
                float maxVal = scores(i,0);
                int maxIndex = 0;
                for(int j = 1; j<classesCount; j++) {
                    float val = scores(i,j);
                    if(val > maxVal) {
                        maxVal = val;
                        maxIndex = j;
                    }
                }
                cout << "Img" + to_string(i) + " prediction: " + to_string(maxIndex) + ", score: " + to_string(maxVal) + "\n";
            }
        }
    

    功能 flat_inner_dims() 允许检索给定形状的特征::张量 <float, 2> 表示一个二维浮点数数组。然后,我运行了这个数组。

    您可以找到有关如何使用特征::张量的更多信息 here

    希望这能有所帮助。