【问题标题】:Visualizing a TensorFlow graph in Jupyter doesn't work在 Jupyter 中可视化 TensorFlow 图不起作用
【发布时间】:2017-05-14 07:24:00
【问题描述】:

我在 question 看到了关于如何在 Jupyter 笔记本中可视化张量流图的内容。我发现这个答案来自this 示例,其中只有一处修改(tensor.tensor_content = bytes("<stripped %d bytes>"%size, 'utf-8')tensor.tensor_content = "<stripped %d bytes>"%size 替换)。但是,如果我尝试在 tensorflow_inception_graph.pb 上重新运行它,则可视化不起作用:iframe 是白色的,并且没有显示任何节点。

如果您能解释一下我做错了什么,我将不胜感激。这里有一个简单的例子来重现这个问题。

进口:

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import tensorflow as tf
import numpy as np

from IPython.display import clear_output, Image, display, HTML

创建图表:

graph = tf.Graph()
sess = tf.InteractiveSession(graph=graph)

x = tf.placeholder(tf.float32, shape=[None, 25, 25, 3], name='x')
y_true = tf.placeholder(tf.float32, shape=[None, 10], name='y_true')
y_true_cls = tf.argmax(y_true, dimension=1, name='y_true_cls')

print graph.get_operations()

输出:

[<tensorflow.python.framework.ops.Operation at 0x115902850>,
 <tensorflow.python.framework.ops.Operation at 0x115902690>,
 <tensorflow.python.framework.ops.Operation at 0x115902b10>,
 <tensorflow.python.framework.ops.Operation at 0x1159029d0>]

可视化功能:

def strip_consts(graph_def, max_const_size=32):
    """Strip large constant values from graph_def."""
    strip_def = tf.GraphDef()
    for n0 in graph_def.node:
        n = strip_def.node.add() 
        n.MergeFrom(n0)
        if n.op == 'Const':
            tensor = n.attr['value'].tensor
            size = len(tensor.tensor_content)
            if size > max_const_size:
                tensor.tensor_content = bytes("<stripped %d bytes>"%size, "utf-8")
    return strip_def

def show_graph(graph_def, max_const_size=32):
    """Visualize TensorFlow graph."""
    if hasattr(graph_def, 'as_graph_def'):
        graph_def = graph_def.as_graph_def()
    strip_def = strip_consts(graph_def, max_const_size=max_const_size)
    code = """
        <script>
          function load() {{
            document.getElementById("{id}").pbtxt = {data};
          }}
        </script>
        <link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()>
        <div style="height:600px">
          <tf-graph-basic id="{id}"></tf-graph-basic>
        </div>
    """.format(data=repr(str(strip_def)), id='graph'+str(np.random.rand()))

    iframe = """
        <iframe seamless style="width:1200px;height:620px;border:0" srcdoc="{}"></iframe>
    """.format(code.replace('"', '&quot;'))
    display(HTML(iframe))

结果:

UPD我尝试了一个更简单的例子:

tf.reset_default_graph()
x = tf.ones((), name="x")
y = tf.ones((), name="y")
z = tf.add(x, y, name="z")
show_graph()

但它仍然不起作用。我怀疑问题与生成的 Javascript/HTML 代码有关:

    <script>
      function load() {
        document.getElementById(&quot;graph0.746875762596&quot;).pbtxt = 'node {\n  name: &quot;x&quot;\n  op: &quot;Const&quot;\n  attr {\n    key: &quot;dtype&quot;\n    value {\n      type: DT_FLOAT\n    }\n  }\n  attr {\n    key: &quot;value&quot;\n    value {\n      tensor {\n        dtype: DT_FLOAT\n        tensor_shape {\n        }\n        float_val: 1.0\n      }\n    }\n  }\n}\nnode {\n  name: &quot;y&quot;\n  op: &quot;Const&quot;\n  attr {\n    key: &quot;dtype&quot;\n    value {\n      type: DT_FLOAT\n    }\n  }\n  attr {\n    key: &quot;value&quot;\n    value {\n      tensor {\n        dtype: DT_FLOAT\n        tensor_shape {\n        }\n        float_val: 1.0\n      }\n    }\n  }\n}\nnode {\n  name: &quot;z&quot;\n  op: &quot;Add&quot;\n  input: &quot;x&quot;\n  input: &quot;y&quot;\n  attr {\n    key: &quot;T&quot;\n    value {\n      type: DT_FLOAT\n    }\n  }\n}\n';
      }
    </script>
    <link rel=&quot;import&quot; href=&quot;https://tensorboard.appspot.com/tf-graph-basic.build.html&quot; onload=load()>
    <div style=&quot;height:600px&quot;>
      <tf-graph-basic id=&quot;graph0.746875762596&quot;></tf-graph-basic>
    </div>

也许有 &amp;quot' 的东西?

【问题讨论】:

    标签: tensorflow ipython jupyter graph-visualization tensorboard


    【解决方案1】:

    这是我使用的版本right now

    你应该可以做这样的事情:

    【讨论】:

    • 感谢您的及时回复!它仍然不起作用。你知道可能是什么原因吗?我将 anaconda 用于 python 2.7。昨天我将它与 tensorflow 和所有其他软件包一起更新。
    • 也许 Jupyter 中的某些东西阻止了外部页面的加载?您可以尝试修改 show_graph 以将其生成的页面保存为独立的 html 并打开它
    • 如果我下载“DeapDreaming with Tensorflow”并使用 Jupyter 渲染它,则不会渲染图形。但是,它确实使用 nbviewer 进行渲染。我还检查了我是否可以嵌入iframe,例如从这里:stackoverflow.com/questions/17619964/…。我想问题可能与javascript函数有关?你能看看吗?我更新了问题。
    • 这听起来像是 jupyter 问题,也许您的版本出于安全原因不想显示具有外部依赖项的 iframe?
    • 可以在 Chrome 中渲染。这也可能与Firefox有关。我检查了它的控制台,它没有抱怨安全性......嗯
    【解决方案2】:

    失败的原因是导入 (&lt;link rel="import" ...) 是 only supported under ChromeFirefox 和 Safari 中失败,并且在 WebComponents 定义到来之前看不到被其他人采用。所以,你最好在 Chrome 中运行 Jupyter。

    如果您反对 Chrome,那么有个好消息。您可以使用 Polyfill(在不支持该功能的 Web 浏览器上实现该功能的一段代码)使其工作:

    <script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.3.3/platform.js"></script>
    

    我已经在 Firefox 和 Safari 中对其进行了测试,并且可以正常工作,但并不完全正常。加载 Polypill 有点慢,并且图形画布缩小到一英寸宽(我不知道为什么,TensorBoard 内部)。然后我意识到platform.js 一直是deprecated,但是新的实现包含了新的错误(未处理的事件和 XML 解析)。

    以下是修改后的代码:

    # TensorFlow Graph visualizer code
    import numpy as np
    from IPython.display import clear_output, Image, display, HTML
    
    def strip_consts(graph_def, max_const_size=32):
        """Strip large constant values from graph_def."""
        strip_def = tf.GraphDef()
        for n0 in graph_def.node:
            n = strip_def.node.add() 
            n.MergeFrom(n0)
            if n.op == 'Const':
                tensor = n.attr['value'].tensor
                size = len(tensor.tensor_content)
                if size > max_const_size:
                    tensor.tensor_content = "<stripped %d bytes>"%size
        return strip_def
    
    def show_graph(graph_def, max_const_size=32):
        """Visualize TensorFlow graph."""
        if hasattr(graph_def, 'as_graph_def'):
            graph_def = graph_def.as_graph_def()
        strip_def = strip_consts(graph_def, max_const_size=max_const_size)
        code = """
            <script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.3.3/platform.js"></script>
            <script>
              function load() {{
                document.getElementById("{id}").pbtxt = {data};
              }}
            </script>
            <link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()>
            <div style="height:600px">
              <tf-graph-basic id="{id}"></tf-graph-basic>
            </div>
        """.format(data=repr(str(strip_def)), id='graph'+str(np.random.rand()))
    
        iframe = """
            <iframe seamless style="width:1200px;height:620px;border:0" srcdoc="{}"></iframe>
        """.format(code.replace('"', '&quot;'))
        display(HTML(iframe))
    

    请注意,code = """ 块的开头只添加了一行。它必须在那里,因为 Polyfill 需要它。

    可以在here找到原始源代码。您可以要求他在 Google 中改进它以涵盖 Chrome 以外的其他浏览器,但我认为这不会发生。

    【讨论】:

    • 嗨!感谢你的回复。它几乎就在那里!一个svg有问题:它的宽度很小..我猜有可能用js增加?
    猜你喜欢
    • 2016-11-06
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多