tensorflow c ++批处理推断

dan*_*nny 5 c++ inference neural-network keras tensorflow

我使用c ++ tensorflow api对batchsize大于1进行推断时遇到问题。网络输入平面为8x8x13,输出为单个浮点。当我尝试如下推断多个样本时,结果仅对第一个样本正确。我使用keras2tensorflow工具将图形转换为.pb格式。

node {
  name: "main_input"
  op: "Placeholder"
  attr {
    key: "dtype"
    value {
      type: DT_FLOAT
    }
  }
  attr {
    key: "shape"
    value {
      shape {
        dim {
          size: -1
        }
        dim {
          size: 8
        }
        dim {
          size: 8
        }
        dim {
          size: 12
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:输出节点是一个标量。罪魁祸首可能是我用来将keras hdf5文件转换为pb的keras2tensorflow代码吗?也许输出应该是-1x1以接受任意数量的样本,就像输入平面一样)。我从以下链接获得了转换器代码:keras_to_tensorflow

node {
  name: "value_0"
  op: "Identity"
  input: "strided_slice"
  attr { 
    key: "T"
    value {
      type: DT_FLOAT
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

输入平面尺寸正确设置为-1 x 8 x 8 x 13。

void test() {

    //input planes
    const int nmoves = pstack->count; //This is the number of samples
    TensorShape input_shape({nmoves, 8, 8, CHANNELS});
    Tensor inputs(DT_FLOAT, input_shape);

    //.... Initialize input planes

    //output
    std::vector<Tensor> outputs;

    //run session
    TF_CHECK_OK( session->Run(
        {{input_layer, inputs}}, {output_layer}, {}, &outputs) 
    );

    //get results
    auto outd = outputs[0].flat<float>().data(); //is this correct way to access the data for multiple samples ?
    for(int i = 0;i < nmoves; i++) {
        float p = outd[i];    //The value of p is wrong for all but the first one
        std::cout << "I" << i << " == " << p << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

下面显示了每个样本的示例输出(p),假定结果在0到1之间。只有I0是正确的,而I16和I18的值却很大。我认为问题在于,运行会话后,输出的维数仍为1,应该为20。使用c ++ api是否可以对多个样本进行推断?

I0 == 0.434162
I1 == 0
I2 == 0
I3 == 0.0640963
I4 == 0.0718748
I5 == 0.325485
I6 == 0
I7 == 0
I8 == 0
I9 == 0
I10 == 0.141193
I11 == 0.398055
I12 == 0.237758
I13 == 0.530693
I14 == 2.44527e-42
I15 == 0
I16 == -5.62959e+14
I17 == 4.56697e-41
I18 == -5.62959e+14
I19 == 4.56697e-41
Run Code Online (Sandbox Code Playgroud)

use*_*302 0

事实证明,问题是由于我用于转换的 keras_to_tensorflow 的错误造成的。我在这里报告了这个问题。该错误仍然存​​在于keras_to_tensorflow中

第 68 行:

pred[i] = tf.identity(net_model.output[i], name=pred_node_names[i])
Run Code Online (Sandbox Code Playgroud)

“输出”应该是“输出”

pred[i] = tf.identity(net_model.outputs[i], name=pred_node_names[i])
Run Code Online (Sandbox Code Playgroud)