如何在virtualenv中从python scipt运行Tensorboard?

时间:2017-02-10 11:49:45

标签: python virtualenv anaconda tensorboard

Tensorboard应该从commnad行开始:

tensorboard --logdir=path

我需要从代码中运行它。到现在为止我用这个:

import os
os.system('tensorboard --logdir=' + path)

但是,由于未包含在系统路径中,因此张贴板无法启动。我在Windows上使用PyCharm和virtualenv。我不想改变系统路径,因此唯一的选择是从virtualenv运行它。这该怎么做?

12 个答案:

答案 0 :(得分:9)

答案可能有点晚了,但这对我来说在Python 3.6.2中是有用的:

import tensorflow as tf
from tensorboard import main as tb
tf.flags.FLAGS.logdir = "/path/to/graphs/"
tb.main()

使用默认配置运行tensorboard,并在" / path / to / graphs /"中查找图表和摘要。您当然可以使用以下命令更改日志目录并设置任意数量的变量:

tf.flags.FLAGS.variable = value

希望它有所帮助。

答案 1 :(得分:6)

您应该在单独的帖子中启动tensorBoard

def launchTensorBoard():
    import os
    os.system('tensorboard --logdir=' + tensorBoardPath)
    return

import threading
t = threading.Thread(target=launchTensorBoard, args=([]))
t.start()

答案 2 :(得分:5)

当我遇到同样的问题时,您可以使用受tensorboard\main.py启发的以下行:

from tensorboard import default
from tensorboard import program

tb = program.TensorBoard(default.PLUGIN_LOADERS, default.get_assets_zip_provider())
tb.configure(argv=['--logdir', my_directory])
tb.main()

使用my_directory作为您要检查的文件夹。如果您要避免在tb.main()之后被阻塞,请不要忘记创建单独的线程。 最好的问候

编辑Tensorboard V1.10:

出于某些个人原因,我用另一种方式写它:

class TensorBoardTool:

    def __init__(self, dir_path):
        self.dir_path = dir_path

    def run(self):
        # Remove http messages
        log = logging.getLogger('werkzeug')
        log.setLevel(logging.ERROR)
        # Start tensorboard server
        tb = program.TensorBoard(default.PLUGIN_LOADERS, default.get_assets_zip_provider())
        tb.configure(argv=['--logdir', self.dir_path])
        url = tb.launch()
        sys.stdout.write('TensorBoard at %s \n' % url)

编辑Tensorboard V1.12:

根据Elad Weiss和tsbertalan的张量板1.12版本。

    def run(self):
        # Remove http messages
        log = logging.getLogger('werkzeug').setLevel(logging.ERROR)
        # Start tensorboard server
        tb = program.TensorBoard(default.get_plugins(), default.get_assets_zip_provider())
        tb.configure(argv=[None, '--logdir', self.dir_path])
        url = tb.launch()
        sys.stdout.write('TensorBoard at %s \n' % url)

然后运行它即可:

# Tensorboard tool launch
tb_tool = TensorBoardTool(work_dir)
tb_tool.run()

这将允许您在不干扰http请求的情况下与主进程同时运行Tensorboard服务器!

答案 3 :(得分:3)

对于Tensorboard 2.1.0,这对我有效:

python -m tensorboard.main --logdir $PWD/logs

您必须先激活您的环境。 (就我而言,conda install出现致命错误,因此我需要通过tf内的pip重新安装conda。)

答案 4 :(得分:2)

使用Tensorboard 2 API(2019):

from tensorboard import program
tb = program.TensorBoard()
tb.configure(argv=[None, '--logdir', tracking_address])
url = tb.launch()

注意:tb.launch()创建一个守护进程线程,该线程将在进程完成后自动终止

答案 5 :(得分:1)

针对Tensorboard 2(2019)的完整解决方案,并自动打开适用于Windows和Linux的Chrome浏览器。适用于两种环境:conda和virtualenv。 此解决方案会抑制Tensorboard输出,因此不会(恼人地)在stdout中显示

from multiprocessing import Process
import sys
import os

class TensorboardSupervisor:
    def __init__(self, log_dp):
            self.server = TensorboardServer(log_dp)
            self.server.start()
            print("Started Tensorboard Server")
            self.chrome = ChromeProcess()
            print("Started Chrome Browser")
            self.chrome.start()

    def finalize(self):
        if self.server.is_alive():
            print('Killing Tensorboard Server')
            self.server.terminate()
            self.server.join()
        # As a preference, we leave chrome open - but this may be amended similar to the method above


class TensorboardServer(Process):
    def __init__(self, log_dp):
        super().__init__()
        self.os_name = os.name
        self.log_dp = str(log_dp)
        # self.daemon = True

    def run(self):
        if self.os_name == 'nt':  # Windows
            os.system(f'{sys.executable} -m tensorboard.main --logdir "{self.log_dp}" 2> NUL')
        elif self.os_name == 'posix':  # Linux
            os.system(f'{sys.executable} -m tensorboard.main --logdir "{self.log_dp}" '
                      f'--host `hostname -I` >/dev/null 2>&1')
        else:
            raise NotImplementedError(f'No support for OS : {self.os_name}')
    
    
class ChromeProcess(Process):
    def __init__(self):
        super().__init__()
        self.os_name = os.name
        self.daemon = True

    def run(self):
        if self.os_name == 'nt':  # Windows
            os.system(f'start chrome  http://localhost:6006/')
        elif self.os_name == 'posix':  # Linux
            os.system(f'google-chrome http://localhost:6006/')
        else:
            raise NotImplementedError(f'No support for OS : {self.os_name}')

初始化:

tb_sup = TensorboardSupervisor('path/to/logs')

完成培训/测试后:

tb_sup.finalize()

答案 6 :(得分:1)

要在指定的虚拟环境中从python脚本运行tensorboard,您必须将tensorboard更改为/path/to/your/environment/bin/tensorboard。还建议按照@Dmitry的建议在单独的线程中执行命令。

看起来像这样,并且可以在tb和tf 1.14.0版中使用:

def run_tensorboard(logdir_absolute):

   import os, threading
   tb_thread = threading.Thread(
          target=lambda: os.system('/home/username/anaconda3/envs/'
                                   'env_name/bin/tensorboard '
                                   '--logdir=' + logdir_absolute),
          daemon=True)
   tb_thread.start()

答案 7 :(得分:0)

从TensorBoard版本1.9.0开始,以下操作可在同一Python进程中以默认设置启动TensorBoard:

import tensorboard as tb
import tensorboard.program
import tensorboard.default

tb.program.FLAGS.logdir = 'path/to/logdir'
tb.program.main(tb.default.get_plugins(),
                tb.default.get_assets_zip_provider())

答案 8 :(得分:0)

以下内容将打开Chrome标签并启动TensorBoard。只需提供所需的目录和您的系统名称。

import os
os.system(
    "cd <directory> \
    && google-chrome http://<your computer name>:6007 \
    && tensorboard --port=6007 --logdir runs"
) 

答案 9 :(得分:0)

如果您的python解释器路径为:

/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/bin/python3.6

您可以运行此命令代替tensorboard

/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/版本/3.6/lib/python3.6/site-packages/tensorboard/main.py

对我有用。

答案 10 :(得分:0)

有相同的问题: 在Windows上工作时,您可以使用批处理文件来完全自动打开张量板,如下面的示例所示。

您可能想在可见的控制台窗口(cmd.exe)中打开tensorboard。在IDE(pycharm)中调用一个批处理文件将在IDE中运行它,因此在后台运行,这意味着您看不到控制台。因此,您可以使用一种解决方法:调用一个批处理文件,然后调用该批处理文件以启动tensorboard。

注意:在本示例中,我使用Anaconda作为虚拟环境

batch_filename = 'start_tb.bat'  # set filename for batch file
tb_command = 'tensorboard --logdir=' + log_dir  # join strings for tensorflow command

# creates batch file that will call seconds batch file in console window (cmd.exe)
with open(os.path.join('invoke.bat'), "w") as f:
    f.writelines('start ' + batch_filename)

# created batch file that activates Anaconda environment and starts tensorboard
with open(os.path.join(batch_filename), "w") as f:
    f.writelines('\nconda activate YOURCondaEnvNAME  && ' + tb_command)  # change to your conda environment, or other virtualenv

# starts tensorboard using the batch files (will open console window)
# calls the 'invoke.bat' that will call 'start_tb.bat'
os.system('invoke.bat')

# starts tensorboard in default browser >> ATTENTION: must be adapted to local host
os.system('start "" http://YOUR-COMPUTER-NAME:6006/')  # just copy the URL that tensorboard runs at on your computer

有时候,您可能需要刷新浏览器中的张量板,因为张量板在正确设置之前就已经打开。

答案 11 :(得分:-2)

尝试从python

运行
import os
os.system('python -m tensorflow.tensorboard --logdir=' + path)

在PyCharm中为我工作(但在linux上,所以如果shell语法不同,那么你必须调整它)