How can I print the values of Keras tensors?

Keras’ backend has print_tensor which enables you to do this. You can use it this way:

import keras.backend as K

def loss_fn(y_true, y_pred):
    y_true = K.print_tensor(y_true, message="y_true = ")
    y_pred = K.print_tensor(y_pred, message="y_pred = ")

The function returns an identical tensor. When that tensor is evaluated, it will print its content, preceded by message.
From the Keras docs:

Note that print_tensor returns a new tensor identical to x which should be used in the following code. Otherwise the print operation is not taken into account during evaluation.

So, make sure to use the tensor afterwards.

Leave a Comment