7

The documentation https://keras.io/models/model/#predict says that model.predict returns Numpy array(s) of predictions. In the Keras API, is there is a way to distinguishing which of these arrays are which? How about in the TF implementation?

At the top of the same page of documentation, they say that "models can specify multiple inputs and outputs using lists". It seems that nothing breaks if instead, one passes dictionaries:

my_model = tf.keras.models.Model(inputs=my_inputs_dict, outputs=my_outputs_dict)

When calling model.fit the same documentation says "If input layers in the model are named, you can also pass a dictionary mapping input names to Numpy arrays."

It would be nice if either the keys from my_output_dict or the names of the dictionary values (layers) in my_output_dict were attached to the outputs of my_model.predict(...)

If I save the model to TensorFlow's saved_model format protobuf using tf.keras.model.save the tf.serving API works this way-- with named inputs and outputs...

nbro
  • 15,395
  • 32
  • 113
  • 196
James McKeown
  • 1,284
  • 1
  • 9
  • 14
  • 1
    I suspect that the answer may just be " use lists, not dictionaries in your model definition and the outputs will have the same ordering as in the model definition." If this is the case, I would think that passing dictionaries for input and output should raise an exception, unless there is an implicit reliance on this https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6/39980744 – James McKeown Jul 30 '19 at 18:27
  • When I try passing a dictionary to the `outputs` argument, I get the following exception: `ValueError: Output tensors to a Model must be the output of a Keras 'Layer'`. I agree that, if this option is not documented, it should throw an exception as otherwise the outputs would have an arbitrary order. – rvinas Jul 30 '19 at 21:05
  • @rvinas which keras version are you using? I've tried with both tf.keras for 2.0.0-beta1 and 1.14 and neither throws an exception. – James McKeown Jul 30 '19 at 21:25
  • I am using keras 2.2.4 – rvinas Jul 30 '19 at 21:29
  • Tensorflow.keras has an example of `dict` as both input and output of `model.fit()`: https://www.tensorflow.org/guide/keras/train_and_evaluate#passing_data_to_multi-input_multi-output_models. Nothing about `model.predict()`, sadly. I would also prefer it. – Ronald Luc Feb 27 '20 at 08:30

1 Answers1

2

Use my_model.output_names

Given

my_model = tf.keras.models.Model(inputs=my_inputs_dict, outputs=my_outputs_dict)

create the dict yourself from my_model.output_names, which is a list of name attributes of your output layers in the order of prediction

prediction_list = my_model.predict(my_test_input_dict)
prediction_dict = {name: pred for name, pred in zip(my_model.output_names, prediction_list)}
Ronald Luc
  • 1,088
  • 7
  • 17