有没有办法让tensorflow tf.打印输出显示在Jupyter笔记本输出中

有没有办法让tensorflow tf.打印输出显示在Jupyter笔记本输出中,tensorflow,jupyter-notebook,Tensorflow,Jupyter Notebook,我用的是Jupyter笔记本上的tf.Print操作。它可以根据需要工作,但只将输出打印到控制台,而不在笔记本中打印。有没有办法绕过这个问题 下面是一个示例(在笔记本中): 该代码将在控制台中打印“hi[1]”,但在笔记本中不会打印任何内容 2017年2月3日更新 我已经把这个包好了。示例用法 # install memory util import urllib.request response = urllib.request.urlopen("https://raw.githubuserc

我用的是Jupyter笔记本上的tf.Print操作。它可以根据需要工作,但只将输出打印到控制台,而不在笔记本中打印。有没有办法绕过这个问题

下面是一个示例(在笔记本中):


该代码将在控制台中打印“hi[1]”,但在笔记本中不会打印任何内容

2017年2月3日更新 我已经把这个包好了。示例用法

# install memory util
import urllib.request
response = urllib.request.urlopen("https://raw.githubusercontent.com/yaroslavvb/memory_util/master/memory_util.py")
open("memory_util.py", "wb").write(response.read())

import memory_util

sess = tf.Session()
a = tf.random_uniform((1000,))
b = tf.random_uniform((1000,))
c = a + b
with memory_util.capture_stderr() as stderr:
    sess.run(c.op)

print(stderr.getvalue())
**老东西**

您可以重新使用IPython core。(马克·桑德勒的想法)


我遇到了同样的问题,并通过在笔记本中使用这样的函数来解决它:

def tf_print(tensor, transform=None):

    # Insert a custom python operation into the graph that does nothing but print a tensors value 
    def print_tensor(x):
        # x is typically a numpy array here so you could do anything you want with it,
        # but adding a transformation of some kind usually makes the output more digestible
        print(x if transform is None else transform(x))
        return x
    log_op = tf.py_func(print_tensor, [tensor], [tensor.dtype])[0]
    with tf.control_dependencies([log_op]):
        res = tf.identity(tensor)

    # Return the given tensor
    return res


# Now define a tensor and use the tf_print function much like the tf.identity function
tensor = tf_print(tf.random_normal([100, 100]), transform=lambda x: [np.min(x), np.max(x)])

# This will print the transformed version of the tensors actual value 
# (which was summarized to just the min and max for brevity)
sess = tf.InteractiveSession()
sess.run([tensor])
sess.close()

仅供参考,在我的自定义函数中使用记录器而不是调用“print”对我来说非常有用,因为stdout通常由jupyter缓冲,在“Loss is Nan”之前不会显示一种错误——在我的例子中,这是使用该功能的第一个要点。

您可以检查启动jupyter笔记本的终端,以查看消息

import tensorflow as tf

tf.InteractiveSession()

a = tf.constant(1)
b = tf.constant(2)

opt = a + b
opt = tf.Print(opt, [opt], message="1 + 2 = ")

opt.eval()
在终端,我可以看到:

2018-01-02 23:38:07.691808: I tensorflow/core/kernels/logging_ops.cc:79] 1 + 2 = [3]

这是一种简单的方法,在常规python中进行了尝试,但还没有使用jupyter。

os.dup2(sys.stdout.fileno(),1)
os.dup2(sys.stdout.fileno(),2)


解释如下:

我面临的问题是,不能在Tensorflow图中运行会话,如在培训或评估中。 这就是为什么使用
sess.run(opt)
opt.eval()
的选项不是我的解决方案。 最好是使用
tf.Print()
并将日志重定向到外部文件。 我使用一个临时文件完成了这项工作,并将其传输到如下常规文件:

STDERR=2
import os
import sys
import tempfile

class captured:
    def __init__(self, fd=STDERR):
        self.fd = fd
        self.prevfd = None
    def __enter__(self):
        t = tempfile.NamedTemporaryFile()
        self.prevfd = os.dup(self.fd)
        os.dup2(t.fileno(), self.fd)
        return t
    def __exit__(self, exc_type, exc_value, traceback):
        os.dup2(self.prevfd, self.fd)

with captured(fd=STDERR) as tmp:
    ...
    classifier.evaluate(input_fn=input_fn, steps=100)

with open('log.txt', 'w') as f:
    print(open(tmp.name).read(), file=f)
在我的评估中,我会:

a = tf.constant(1)
a = tf.Print(a, [a], message="a: ")

请在这里粘贴一些您尝试过的代码。您可以使用TF2.0为我捕获sys.stdoutWorks
STDERR=2
import os
import sys
import tempfile

class captured:
    def __init__(self, fd=STDERR):
        self.fd = fd
        self.prevfd = None
    def __enter__(self):
        t = tempfile.NamedTemporaryFile()
        self.prevfd = os.dup(self.fd)
        os.dup2(t.fileno(), self.fd)
        return t
    def __exit__(self, exc_type, exc_value, traceback):
        os.dup2(self.prevfd, self.fd)

with captured(fd=STDERR) as tmp:
    ...
    classifier.evaluate(input_fn=input_fn, steps=100)

with open('log.txt', 'w') as f:
    print(open(tmp.name).read(), file=f)
a = tf.constant(1)
a = tf.Print(a, [a], message="a: ")