Java – How do I provide boolean value placeholders through TensorFlowInferenceInterface.java?

How do I provide boolean value placeholders through TensorFlowInferenceInterface.java?… here is a solution to the problem.

How do I provide boolean value placeholders through TensorFlowInferenceInterface.java?

I’m trying to launch a graph trained in Keras Tensorflow via the Java Tensorflow API.
In addition to the standard input image placeholder, the figure contains a ‘keras_learning_phase’ placeholder that requires a boolean value.

The problem is, There is no method in TensorFlowInferenceInterface for boolean values – you can only use float, double, int, or byte to provide it with strong > value.

Apparently when I try to pass int to this tensor via the following code:

inferenceInterface.fillNodeInt("keras_learning_phase",  
                               new int[]{1}, new int[]{0});

I see

tensorflow_inference_jni.cc:207 Error during inference: Internal:
Output 0 of type int32 does not match declared output type bool for
node _recv_keras_learning_phase_0 = _Recvclient_terminated=true,
recv_device=”/job:localhost/replica:0/task:0/cpu:0″,
send_device=”/job:localhost/replica:0/task:0/cpu:0″,
send_device_incarnation=4742451733276497694,
tensor_name=”keras_learning_phase”, tensor_type=DT_BOOL,
_device=”/job:localhost/replica:0/task:0/cpu:0″

Is there a way to circumvent it?
Maybe it’s possible to somehow explicitly convert the Placeholder node in the graph to Constant?
Or maybe you can avoid creating this Placeholder in the chart initially?

Solution

The TensorFlowInferenceInterface class is inherently complete convenience wrapper for the TensorFlow Java API, which does support boolean Value.

You might be able to add a method to TensorFlowInferenceInterface to do what you want. Similar to >fillNodeInt and you can add the following (note that the boolean value in TensorFlow is represented as one byte):

public void fillNodeBool(String inputName, int[] dims, bool[] src) {
  byte[] b = new byte[src.length];
  for (int i = 0; i < src.length; ++i) {
    b[i] = src[i] ? 1 : 0;
  }
  addFeed(inputName, Tensor.create(DatType.BOOL, mkDims(dims), ByteBuffer.wrap(b)));
}

Hope this helps. If feasible, I encourage you to contribute back to the TensorFlow codebase.

Related Problems and Solutions