How can I print the values of Keras tensors?

后端 未结 7 1441
梦毁少年i
梦毁少年i 2020-12-14 00:43

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
         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 01:36

    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.

提交回复
热议问题