我可以使用Google Colab来使用TensorBoard吗?

109

在Google Colab训练TensorFlow模型时,有没有办法使用TensorBoard?


4
官方文档链接:https://colab.research.google.com/github/tensorflow/tensorboard/blob/master/docs/tensorboard_in_notebooks.ipynb - EFreak
现在,您可以简单地使用TensorBoard魔法。%tensorboard --logdir your_path - Hissaan Ali
22个回答

96
编辑:你可能想要尝试一下官方的%tensorboard magic,它从TensorFlow 1.13版本开始可用。
在存在%tensorboard魔术命令之前,实现这一点的标准方法是使用ngrok将网络流量代理到Colab VM。可以在这里找到一个Colab示例。
以下是步骤(代码片段表示Colab中的“代码”类型单元格):
  1. 在后台运行TensorBoard。
    受到this answer的启发。

    LOG_DIR = '/tmp/log'
    get_ipython().system_raw(
        'tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'
        .format(LOG_DIR)
    )
    
  2. 下载并解压缩ngrok
    将传递给wget的链接替换为适用于您的操作系统的正确下载链接。

    ! wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
    ! unzip ngrok-stable-linux-amd64.zip
    
  3. 启动ngrok后台进程...

    get_ipython().system_raw('./ngrok http 6006 &')
    
...并获取公共网址。 来源
    ! curl -s http://localhost:4040/api/tunnels | python3 -c \
        "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])"

我正在尝试在我的ColabVM中运行Tensorboard,并且需要将事件和检查点存储在我的Google Drive中。您的解决方案是否可以帮助我实现这一点?此外,如果您能更详细地说明一下您在Colab中编写的方法如何实现这一点,那将非常有帮助。您是否使用此方法将事件从ColabVM带到本地桌面? - Anu
1
@anu 这些用例有示例笔记本:Drive IO系统别名 - Joppe Geluykens

80

这里的许多答案现在已经过时了,我相信我的答案几周后也会过时。但是在撰写本文时,我所要做的就是从Colab运行这些代码,并且Tensorboard正常打开。

%load_ext tensorboard
%tensorboard --logdir logs

2
嗨,感谢评论。你在colab笔记本中运行这两行代码了吗?我已经运行过了,在我的笔记本中得到了一个TensorBoard窗口,并显示“当前数据集不存在任何仪表板”的消息。你能帮我吗? - desmond13
注意:在Firefox中无法使用,但在Chrome中可以。直接在单元格中打开Tensorboard。 - Knipser
1
不要使用%tensorboard --logdir logs,而应该使用%tensorboard --logdir=logs,这将解决“当前数据集没有活动的仪表板”的问题。同时,在=./path/to/your/directory之间不应该有空格,否则tensorboard将无法正确显示。 - Yashasvi Bhatt

26

这里有一个更简单的方法在Google Colab上进行相同的ngrok隧道方法。

!pip install tensorboardcolab

那么,

from tensorboardcolab import TensorBoardColab, TensorBoardColabCallback

tbc=TensorBoardColab()

假设您正在使用Keras:

model.fit(......,callbacks=[TensorBoardColabCallback(tbc)])

你可以在这里阅读原始文章


1
嗨,这看起来真的很酷,但我在 Colab 中遇到了这个错误:FailedPreconditionError: Error while reading resource variable conv_dw_8/depthwise_kernel from Container: localhost. This could mean that the variable was uninitialized. - Austin
@Austin tensorboardcolab的作者已经找到了解决方法:“我发现这种情况偶尔会发生,可以通过以下方式解决:1.等待 2.重新启动Colab服务器 3.更改Colab服务器类型(CPU/GPU/TPU),然后再改回来”。请参见他在此处的评论。 - NeStack
另外,请确保您的模型是直接由Keras构建而不是嵌入TensorFlow中。例如,使用model.add(keras.layers.LSTM(...))代替model.add(tf.keras.layers.LSTM(....))。否则可能会出现错误消息。 - NeStack

12

使用tensorboardcolab在Google Colab上运行的TensorFlow中的TensorBoard。这在内部使用ngrok进行通信。

  1. 安装TensorBoardColab

!pip install tensorboardcolab

  1. 创建一个tensorboardcolab对象

tbc = TensorBoardColab()

这将自动创建一个可以使用的TensorBoard链接。该Tensorboard正在读取'./Graph'处的数据。

  1. 创建指向此位置的FileWriter

summary_writer = tbc.get_writer()

tensorboardcolab库具有返回FileWriter对象的方法,该对象指向上述'./Graph'位置。

  1. 使用summary_writer对象开始将摘要信息添加到事件文件中,该文件位于'./Graph'位置

您可以添加标量信息或图形或直方图数据。

参考: https://github.com/taomanwai/tensorboardcolab


7

我尝试过,但没有得到结果。但是当按照以下方式使用时,得到了结果。

import tensorboardcolab as tb
tbc = tb.TensorBoardColab()

在此之后打开输出中的链接。

import tensorflow as tf
import numpy as np

显式创建一个图形对象

graph = tf.Graph()
with graph.as_default()

完整示例:

完整示例:

with tf.name_scope("variables"):
    # Variable to keep track of how many times the graph has been run
    global_step = tf.Variable(0, dtype=tf.int32, name="global_step")
    
    # Increments the above `global_step` Variable, should be run whenever the graph is run
    increment_step = global_step.assign_add(1)
    
    # Variable that keeps track of previous output value:
    previous_value = tf.Variable(0.0, dtype=tf.float32, name="previous_value")

# Primary transformation Operations
with tf.name_scope("exercise_transformation"):
    
    # Separate input layer
    with tf.name_scope("input"):
        # Create input placeholder- takes in a Vector 
        a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a")

    # Separate middle layer
    with tf.name_scope("intermediate_layer"):
        b = tf.reduce_prod(a, name="product_b")
        c = tf.reduce_sum(a, name="sum_c")
    
    # Separate output layer
    with tf.name_scope("output"):
        d = tf.add(b, c, name="add_d")
        output = tf.subtract(d, previous_value, name="output")
        update_prev = previous_value.assign(output)

# Summary Operations
with tf.name_scope("summaries"):
    tf.summary.scalar('output', output)  # Creates summary for output node
    tf.summary.scalar('product of inputs', b, )
    tf.summary.scalar('sum of inputs', c)

# Global Variables and Operations
with tf.name_scope("global_ops"):
    # Initialization Op
    init = tf.initialize_all_variables()
    # Collect all summary Ops in graph
    merged_summaries = tf.summary.merge_all()

# Start a Session, using the explicitly created Graph
sess = tf.Session(graph=graph)

# Open a SummaryWriter to save summaries
writer = tf.summary.FileWriter('./Graph', sess.graph)

# Initialize Variables
sess.run(init)

def run_graph(input_tensor):
    """
    Helper function; runs the graph with given input tensor and saves summaries
    """
    feed_dict = {a: input_tensor}
    output, summary, step = sess.run([update_prev, merged_summaries, increment_step], feed_dict=feed_dict)
    writer.add_summary(summary, global_step=step)


# Run the graph with various inputs
run_graph([2,8])
run_graph([3,1,3,3])
run_graph([8])
run_graph([1,2,3])
run_graph([11,4])
run_graph([4,1])
run_graph([7,3,1])
run_graph([6,3])
run_graph([0,2])
run_graph([4,5,6])

# Writes the summaries to disk
writer.flush()

# Flushes the summaries to disk and closes the SummaryWriter
writer.close()

# Close the session
sess.close()

# To start TensorBoard after running this file, execute the following command:
# $ tensorboard --logdir='./improved_graph'

5

下面是一个非常简单的示例,演示如何在Google Colab上内联显示模型。以下是显示占位符的方法:

from IPython.display import clear_output, Image, display, HTML
import tensorflow as tf
import numpy as np
from google.colab import files

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>
          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))


"""Create a sample tensor"""
sample_placeholder= tf.placeholder(dtype=tf.float32) 
"""Show it"""
graph_def = tf.get_default_graph().as_graph_def()
show_graph(graph_def)

目前,您无法像在本地计算机上运行Tensorboard服务一样在Google Colab上运行。此外,您也不能通过类似于summary_writer = tf.summary.FileWriter('./logs', graph_def=sess.graph_def)的方式将整个日志导出到Drive,以便随后下载并在本地查看。


4
我使用谷歌云盘的备份和同步功能https://www.google.com/drive/download/backup-and-sync/。在训练期间,定期保存在我的谷歌云盘中的事件文件会自动同步到我自己电脑上的一个文件夹中。我们称这个文件夹为logs。要访问tensorboard中的可视化,我打开命令提示符,导航到同步的谷歌云盘文件夹,并键入:tensorboard --logdir=logs
因此,通过使用备份和同步自动将我的云盘与计算机同步,我可以像在自己的计算机上训练一样使用tensorboard。
编辑:这里有一个可能有用的笔记本。https://colab.research.google.com/gist/MartijnCa/961c5f4c774930f4bdd32d51829da6f6/tensorboard-with-google-drive-backup-and-sync.ipynb

你能否在Colab中编写你的方法并在帖子中分享呢?这将非常有帮助且快捷! - Anu
1
通过遵循您的建议,我只能通过Colab访问“My Drive”中的文件,而无法访问“计算机”中同步计算机所在的文件。而且您的笔记本电脑也无法登录到同步计算机,而是登录到“My Drive”文件夹 - 请参见行os.chdir('/content/drive/My Drive')。您能否进一步解释如何访问同步计算机? - NeStack
1
@NeStack,你说得对,我的解决方案只使用了“我的云端硬盘”文件夹。抱歉让你感到困惑,我不使用“计算机”。你可以使用备份和同步程序将“我的云端硬盘”文件夹与你自己的计算机同步。这样,你就可以在自己的计算机上通过文件浏览器访问事件文件了。 - Martijn Cazemier
@MartijnCazemier 好的,这很有道理。这也是对我有用的选项。 - NeStack
@MartijnCazemier,它不允许我这样做,因为我的驱动器有一个空格,也不允许转义。 - technazi

4
截至2022年5月22日,在最新版本的Colab中,以下是我实验后得出的最佳快捷方式:
# Load the TensorBoard notebook extension
%load_ext tensorboard

# Directly put the log path in the logdir param
%tensorboard --logdir="vision_model/Xception/20220522-120512/"

4

2.0 兼容答案:是的,您可以在Google Colab中使用Tensorboard。请查找下面的代码,其中显示了完整的示例。

!pip install tensorflow==2.0

import tensorflow as tf
# The function to be traced.
@tf.function
def my_func(x, y):
  # A simple hand-rolled layer.
  return tf.nn.relu(tf.matmul(x, y))

# Set up logging.
logdir = './logs/func'
writer = tf.summary.create_file_writer(logdir)

# Sample data for your function.
x = tf.random.uniform((3, 3))
y = tf.random.uniform((3, 3))

# Bracket the function call with
# tf.summary.trace_on() and tf.summary.trace_export().
tf.summary.trace_on(graph=True, profiler=True)
# Call only one tf.function when tracing.
z = my_func(x, y)
with writer.as_default():
  tf.summary.trace_export(
      name="my_func_trace",
      step=0,
      profiler_outdir=logdir)

%load_ext tensorboard
%tensorboard --logdir ./logs/func

关于Google Colab的工作副本,请参考此链接。更多信息,请查看此链接


3
使用summary_writer在每个epoch中写入日志到一个文件夹,然后运行下面的命令可以让我成功。
%load_ext tensorboard 
%tensorboard --logdir=./logs 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接