在keras的model.fit中没有tf.Print的结果

Evg*_*ova 3 keras tensorflow

我写了这个损失(用于测试keras中的自定义损失):

def loss(y_true, y_pred):
  loss = -tf.reduce_sum(y_true * tf.log(y_pred))
  loss = tf.Print(loss, [loss], 'loss = ')
return loss
Run Code Online (Sandbox Code Playgroud)

然后:

model.compile(loss=loss, 
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
model.fit(x_train, y_train)
Run Code Online (Sandbox Code Playgroud)

而且没有tf.Print结果:

Epoch 1/12 
60000/60000 [==============================] - 12s 198us/step - loss: 25.3197 - acc: 0.9384 - val_loss: 5.6927 - val_acc: 0.9857
Epoch 2/12
60000/60000 [==============================] - 11s 187us/step - loss: 8.7803 - acc: 0.9798 - val_loss: 4.6938 - val_acc: 0.9888
Run Code Online (Sandbox Code Playgroud)

为什么?

Pet*_*dan 6

我想您正在Jupyter Notebook中运行它。tf.Print()打印到从调用Jupyter Notebook的终端。看看那里,看看是否有输出。

请参阅tf.Print()手册页上的蓝色注释。

从下面Evgeniya的评论中:您可以编写自己的版本tf.Print()来打印所需的数据(Vihari Piratla编写的代码):

"""
The default tf.Print op goes to STDERR
Use the function below to direct the output to stdout instead
Usage: 
> x=tf.ones([1, 2])
> y=tf.zeros([1, 3])
> p = x*x
> p = tf_print(p, [x, y], "hello")
> p.eval()
hello [[ 0.  0.]]
hello [[ 1.  1.]]
"""
def tf_print(op, tensors, message=None):
    def print_message(x):
        sys.stdout.write(message + " %s\n" % x)
        return x

    prints = [tf.py_func(print_message, [tensor], tensor.dtype) for tensor in tensors]
    with tf.control_dependencies(prints):
        op = tf.identity(op)
    return op
Run Code Online (Sandbox Code Playgroud)

  • 我找到了解决方案,需要重定向stderr:https://gist.github.com/vihari/f9b361058825e16d390f0e443bfdffc7 (2认同)