'tf.print gives TypeSpec TypeError

What does this error message mean?

TypeError: Could not build a TypeSpec for name: "tf.print/PrintV2"
op: "PrintV2"
input: "tf.print/StringFormat"
attr {
  key: "end"
  value {
    s: "\n"
  }
}
attr {
  key: "output_stream"
  value {
    s: "stdout"
  }
}
 of unsupported type <class 'google3.third_party.tensorflow.python.framework.ops.Operation'>

I'm printing the shape of a tensor. My code "works" without the print, so I'm sure it is this statement, and the tensor is valid. I can print the shape of a tensor in a test colab. I'm clueless how to narrow this down and debug this. My failure is in a big hairy program.

I can't find any information on the web about what might be causing this error.

What does it mean when I get a TypeSpec error from a tf.print?

-- Malcolm (TF 2.7.0)



Solution 1:[1]

I'm sorry for the tardy followup.

Turns out that the output from Keras layers is not a regular tf.tensor. I still don't understand the reason, the error message, or how to give a better message. :-(

Here is a simple example of the problem (and the error message) and an (undocumented) solution.

import tensorflow as tf
keras_input = tf.keras.layers.Input([10])
tf.print(keras_input)
==> TypeError: Could not build a TypeSpec for name: "tf.print_2/PrintV2"


tf.keras.backend.print_tensor(keras_input)
==> <KerasTensor: shape=(None, 10) dtype=float32 (created by layer 'tf.keras.backend.print_tensor')>

So the moral of the story is use tf.keras.backend.print_tensor when working with Keras models.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Malcolm Slaney