运行 Visual Studio 代码上的 Anaconda tensorflow-gpu

Running Anaconda tesorflow-gpu on Visual Studio Code

我有一个安装了 TensorFlow GPU 的 conda 环境 (tf-2-gpu)。如果我使用 Anaconda 提示符或 CMD,它就像魅力一样。

但是,在 Visual Studio 代码中我有以下消息:

> conda activate tf-2-gpu
> & C:/Users/<my_user>/.conda/envs/tf-2-gpu/python.exe my_python_script.py
2020-11-16 15:01:07.297343: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found

Anaconda 似乎可以正常工作,因为它可以正确激活它,而且起初我遇到了一些导入错误,然后我在 conda env 上安装了这些库并开始工作。

显然,我有 GPU,正如我之前所说,如果我 运行 在 cmd 上运行它,它就可以工作。

这似乎是 PowerShell 的问题,有什么想法吗?


我发现dll文件在里面.conda/env/tf-2-gpu/Library/bin我把它加到环境路径里了,还是不行

到目前为止我找到了 2 个解决方案。但是他们两个都还不够完美,都有问题。

选项 1: 此选项是找到的解决方案 。 运行 PowerShell 作为管理员,然后:

conda init powershell
set-executionpolicy remotesigned

这很糟糕,因为您必须更改可能存在安全风险的执行策略。

如果您只 运行 第一个命令,您将收到此消息并且代码仍然无法正常工作。

. : File C:\Users\<my_user>\Documents\WindowsPowerShell\profile.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at 
https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:3
+ . 'C:\Users\<my_user>\Documents\WindowsPowerShell\profile.ps1'
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess
Loading personal and system profiles took 4461ms.

使用 powershell -ExecutionPolicy Bypass -File C:\Users\<my_user>\Documents\WindowsPowerShell\profile.ps1 对我不起作用我不知道为什么。

选项 2: 将 CMD 设置为默认 shell.

这意味着它仍然无法在 PowerShell 中运行。

以下步骤对我有用:

按照视频中的操作进行。 https://www.youtube.com/watch?v=r31jnE7pR-g

同时安装视频中缺少的 tensorflow estimator。在图片中,您可以看到适合我的环境。

my environment

也许您必须将版本更改为相同的版本。 现在进入 Visual Code 和 运行 您的代码以及您之前创建的 anaconda 环境。见下图。

select your environment

在我的例子中是 tf_env,我创建并命名的。

尝试 运行 您的代码。如果 Visual Code 提示缺少某些内容,请尝试使用 anaconda 终端安装它。单击“播放”按钮启动终端。

play Button terminal

进行更改时也关闭并打开 Visual Code,有时也关闭 anaconda。现在试试下面的代码。

print("Num GPU: ", len(tf.config.list_physical_devices("GPU")))

print(tf.test.is_gpu_available()) 
print(tf.test.is_built_with_cuda())



> OUTPUT 
> Num GPU:  1 
> WARNING:tensorflow:From <ipython-input-2-8748de971110>:3:
> is_gpu_available (from tensorflow.python.framework.test_util) is
> deprecated and will be removed in a future version. Instructions for
> updating: Use `tf.config.list_physical_devices('GPU')` instead. 
> True
> True

如果您的输出相同,则一切正常。现在,当您训练模型时,您应该会在任务管理器中看到您的 gpu 运行ning。

希望对大家有所帮助:)