How can I print the values of Keras tensors?

后端 未结 7 1428
梦毁少年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:19

    Usually, y_true you know in advance - during preparation of your train corpora...

    However, there's one trick to see the values inside y_true and/or y_pred. Keras gives you an opportunity to write respective callback for printing the neural network's output. It will look something like this:

    def loss_fn(y_true, y_pred):
        return y_true # or y_pred
    ...
    import keras.callbacks as cbks
    class CustomMetrics(cbks.Callback):
    
        def on_epoch_end(self, epoch, logs=None):
            for k in logs:
                if k.endswith('loss_fn'):
                   print logs[k]
    

    Here the loss_fn is name of your loss function when you pass it into the model.compile(...,metrics=[loss_fn],) function during model's compilation.

    So, finally, you have to pass this CustomMetrics callback as the argument into the model.fit():

    model.fit(x=train_X, y=train_Y, ... , callbacks=[CustomMetrics()])
    

    P.S.: If you use Theano (or TensorFlow) like here in Keras, you write a python program, and then you compile it and execute. So, in your example y_true - is just a tensor variable which is used for further compilation and loss function counting.

    It means that there's no way to see the values inside it. In Theano, for example, you can look inside the only so-called shared variable after the execution of respective eval() function. See this question for more info.

提交回复
热议问题