【问题标题】:No result of tf.Print in keras's model.fitkeras 的 model.fit 中没有 tf.Print 的结果
【发布时间】:2018-10-02 19:08:12
【问题描述】:

我写了那个损失(用于测试 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

然后:

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

并且没有 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

为什么?

【问题讨论】:

    标签: tensorflow keras


    【解决方案1】:

    我想你是在 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
    

    【讨论】:

    • 而在 Jupyter Notebook 中没有办法做到这一点?
    • 您能控制 Jupyter Notebook 环境吗?
    • 我找到了解决方案,需要重定向stderr:gist.github.com/vihari/f9b361058825e16d390f0e443bfdffc7
    • 没想到,正在寻找 Jupyter 细胞魔法……不过运气不好。
    • @EvgeniyaTveritinova 在调用tf_print 时,您通过什么代替op
    【解决方案2】:

    我以前见过这个。从 python 命令行运行 py 文件,你会看到 tf.打印()。

    【讨论】:

      【解决方案3】:

      我发现了

      print("foo = " + str(foo.eval()))
      

      (其中 foo 是你的张量)工作得很好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 2023-01-05
        • 1970-01-01
        • 2020-09-03
        • 1970-01-01
        • 2018-10-16
        相关资源
        最近更新 更多