How can I print the values of Keras tensors?

ronroo picture ronroo · Apr 17, 2017 · Viewed 26.6k times · Source

I am implementing own Keras loss function. How can I access tensor values?

What I've tried

def loss_fn(y_true, y_pred):
    print y_true

It prints

Tensor("target:0", shape=(?, ?), dtype=float32)

Is there any Keras function to access y_true values?

Answer

nroulet picture nroulet · Apr 18, 2018

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.