简体   繁体   English

通过 vscode 的 SSH 隧道打开一个 Matplotlib 图

[英]Open a Matplotlib figure through SSH tunnel of vscode

I am setting up a remote workstation to run machine learning related python code from my laptop on another computer that includes a GPU.我正在设置一个远程工作站,以在另一台包含 GPU 的计算机上从我的笔记本电脑运行机器学习相关的 python 代码。

I use the SSH remote feature of vscode to remotely run and debug my code and I am very happy with the interface.我使用 vscode 的 SSH 远程功能来远程运行和调试我的代码,我对界面非常满意。 However, I am not able to generate figures coming from the "matplotlib" library.但是,我无法生成来自“matplotlib”库的图形。

I tried to modify some matlplotlib options, but it was unsucessful:我试图修改一些matlplotlib选项,但没有成功:

import matplotlib
matplotlib.use('Agg')

As instructed in: _tkinter.TclError: no display name and no $DISPLAY environment variable按照指示: _tkinter.TclError: no display name and no $DISPLAY environment variable

In short my problem emerges with the following example code:简而言之,我的问题出现在以下示例代码中:

import numpy as np
from matplotlib import pyplot as plt 

x = np.linspace(0,1,101)
y = x ** 2

plt.close()
plt.figure()
plt.plot(x,y)
plt.show()
~/vscode$ cd /home/*/vscode ; env PYTHONIOENCODING=UTF-8 PYTHONUNBUFFERED=1 /usr/bin/python3 /home/*/.vscode-server/extensions/ms-python.python-2019.6.24221/pythonFiles/ptvsd_launcher.py --default --client --host localhost --port 39903 /home/*/vscode/test_plot.py 
Traceback (most recent call last):
  File "/home/*/.vscode-server/extensions/ms-python.python-2019.6.24221/pythonFiles/ptvsd_launcher.py", line 43, in <module>
    main(ptvsdArgs)
  File "/home/*/.vscode-server/extensions/ms-python.python-2019.6.24221/pythonFiles/lib/python/ptvsd/__main__.py", line 434, in main
    run()
  File "/home/*/.vscode-server/extensions/ms-python.python-2019.6.24221/pythonFiles/lib/python/ptvsd/__main__.py", line 312, in run_file
    runpy.run_path(target, run_name='__main__')
  File "/usr/lib/python3.6/runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "/usr/lib/python3.6/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/*/vscode/test_plot.py", line 8, in <module>
    plt.figure()
  File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 539, in figure
    **kwargs)
  File "/usr/lib/python3/dist-packages/matplotlib/backend_bases.py", line 171, in new_figure_manager
    return cls.new_figure_manager_given_figure(num, fig)
  File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 1049, in new_figure_manager_given_figure
    window = Tk.Tk(className="matplotlib")
  File "/usr/lib/python3.6/tkinter/__init__.py", line 2023, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

Thanks a lot for helping me !非常感谢你帮助我!

I managed to solve the problem by running a parallel Putty ssh connection with X11 forwarding enabled and by writing export DISPLAY=localhost:10.0 in the terminal of vscode before launching a python script.我设法通过在启用 X11 转发的情况下运行并行 Putty ssh 连接并在启动 python 脚本之前在 vscode 的终端中写入export DISPLAY=localhost:10.0来解决这个问题。

However, I have safety concerns and I wonder why I have to manually do these commands in order for it to work... Any insight would be much appreciated !但是,我有安全问题,我想知道为什么我必须手动执行这些命令才能使其工作......任何见解将不胜感激!

I found a slight variation of a previous answer to work very well.我发现以前的答案略有变化,效果很好。

Save the plot as .png instead of plotting it.将绘图另存为.png而不是绘制它。

plt.savefig("dummy_name.png")

The previous answer then suggests moving the file through scp .然后,上一个答案建议通过scp移动文件。 I instead suggest to open dummy_name.png with Visual Code, no need to write commands and it automatically refreshes the image whenever you plot something else.我建议使用 Visual Code 打开dummy_name.png ,无需编写命令,只要您绘制其他内容,它就会自动刷新图像。 I tested this from USA with SSH into a server in Europe, the images refreshed in less than half a second.我在美国用 SSH 测试到欧洲的服务器,图像在不到半秒内刷新。

For an easy configuration, you have 2 options :为了轻松配置,您有 2 个选项:

  1. Plot without showing and transfer picture file through SSH不显示并通过SSH传输图片文件的绘图

This option consists in replacing plt.show() with此选项包括将plt.show()替换为

plt.savefig('foo.png')
plt.savefig('foo.pdf')

More information on saving matplotlib plots有关保存matplotlib图的更多信息

After that, you can transfer this figure with scp之后,你可以用scp传输这个数字

scp remote_username@10.10.0.2:/path/to/foo.png /local/directory
  1. Use Jupyter Notebook使用 Jupyter 笔记本

You can easily plot into a Jupyter Notebook.您可以轻松地绘制到 Jupyter Notebook 中。 Here is a tutorial on how to setup a Raspberry Pi through ssh to create a remote server for Jupyter Notebook.这里是一个教程如何设置一个树莓派通过ssh创建Jupyter笔记本电脑的远程服务器。

On Jupyter Notebook, you need to add on the first line of your notebook, before importing matplotlib , to plot your image after cell.在 Jupyter Notebook 上,您需要在 Notebook 的第一行添加,在导入matplotlib之前,在单元格之后绘制图像。

%matplotlib inline

Another approach is to use Tensorboard, which is now available via an extension in VS code.另一种方法是使用 Tensorboard,它现在可通过 VS 代码中的扩展获得。 You can save your image or plot (as well as other types of data) and immediately view it through the Tensorboard interface in a VS code tab.您可以保存图像或绘图(以及其他类型的数据),并通过 VS 代码选项卡中的 Tensorboard 界面立即查看。 I use this all the time via ssh.我一直通过 ssh 使用它。 However, you do need Tensorflow or Pytorch to do this.但是,您确实需要 Tensorflow 或 Pytorch 来执行此操作。

Here's an example in Pytorch for an image in numpy.array or torch.Tensor format.这是 Pytorch 中 numpy.array 或 torch.Tensor 格式图像的示例。 Make sure to launch your Tensorboard session first.确保首先启动您的 Tensorboard 会话。

from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter('log_dir')    

# for some image "im"
writer.add_image('My image', im, 0)
write.close()

Here's an example for matplotlib figures:这是 matplotlib 图形的示例:

def examplePlot(data):
    fig = plt.figure()
    # do some plotting
    return fig

writer.add_figure('My plot', examplePlot(data), 0)
writer.close()

Refresh your Tensorboard and you should see it right away.刷新您的 Tensorboard,您应该立即看到它。

you can also use pickle to dumb the files on the server machine and then replot them on the local one.您还可以使用 pickle 将服务器计算机上的文件变哑,然后在本地计算机上重新绘制它们。 You can use "SCP" to copy the raw data to your local machine.您可以使用“SCP”将原始数据复制到本地计算机。 Sometimes it helps since you can have real-time interaction with the plot.有时它会有所帮助,因为您可以与情节进行实时交互。 I follow these 2 links:我按照这两个链接:

  1. save draw data python matplotlib save graph as data file保存绘制数据python matplotlib 将图形保存为数据文件
  2. copy using SCP Copying files from server to local computer using SSH使用 SCP 复制 使用 SSH 将文件从服务器复制到本地计算机

I suggest simply creating a new notebook and running the python file in this notebook.我建议简单地创建一个新笔记本并在此笔记本中运行 python 文件。 That works best for me.这最适合我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM