有没有办法让tensorflow tf.Print输出出现在Jupyter Notebook输出中

fjh*_*hj2 11 tensorflow jupyter-notebook

我在Jupyter笔记本中使用tf.Print操作.它可以根据需要工作,但只会将输出打印到控制台,而无需在笔记本中打印.有没有办法解决这个问题?

一个例子如下(在笔记本中):

导入张量流为tf

a = tf.constant(1.0)

a = tf.Print(a,[a],'hi')

sess = tf.Session()

a.eval(会话= SESS)

该代码将在控制台中打印"hi [1]",但笔记本中没有任何内容.

Yar*_*tov 8

2017年2月3日更新 我已将其包装到memory_util包中.用法示例

# 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())
Run Code Online (Sandbox Code Playgroud)

**老东西**

您可以从IPython核心重用FD重定向器.(Mark Sandler的想法)

import os
import sys

STDOUT = 1
STDERR = 2

class FDRedirector(object):
    """ Class to redirect output (stdout or stderr) at the OS level using
        file descriptors.
    """ 

    def __init__(self, fd=STDOUT):
        """ fd is the file descriptor of the outpout you want to capture.
            It can be STDOUT or STERR.
        """
        self.fd = fd
        self.started = False
        self.piper = None
        self.pipew = None

    def start(self):
        """ Setup the redirection.
        """
        if not self.started:
            self.oldhandle = os.dup(self.fd)
            self.piper, self.pipew = os.pipe()
            os.dup2(self.pipew, self.fd)
            os.close(self.pipew)

            self.started = True

    def flush(self):
        """ Flush the captured output, similar to the flush method of any
        stream.
        """
        if self.fd == STDOUT:
            sys.stdout.flush()
        elif self.fd == STDERR:
            sys.stderr.flush()

    def stop(self):
        """ Unset the redirection and return the captured output. 
        """
        if self.started:
            self.flush()
            os.dup2(self.oldhandle, self.fd)
            os.close(self.oldhandle)
            f = os.fdopen(self.piper, 'r')
            output = f.read()
            f.close()

            self.started = False
            return output
        else:
            return ''

    def getvalue(self):
        """ Return the output captured since the last getvalue, or the
        start of the redirection.
        """
        output = self.stop()
        self.start()
        return output

import tensorflow as tf
x = tf.constant([1,2,3])
a=tf.Print(x, [x])

redirect=FDRedirector(STDERR)

sess = tf.InteractiveSession()
redirect.start();
a.eval();
print "Result"
print redirect.stop()
Run Code Online (Sandbox Code Playgroud)