【问题标题】:How to activate existing Python environment with R reticulate如何使用 R reticulate 激活现有 Python 环境
【发布时间】:2022-10-17 21:39:30
【问题描述】:

我有以下现有的 Python 环境:

$   conda info --envs

base                  *  /home/ubuntu/anaconda3
tensorflow2_latest_p37     /home/ubuntu/anaconda3/envs/tensorflow2_latest_p37

我要做的是激活tensorflow2_latest_p37环境 并在 R 代码中使用它。我尝试了以下代码:

library(reticulate)
use_condaenv( "tensorflow2_latest_p37")

library(tensorflow)
tf$constant("Hello Tensorflow!")

但它未能识别环境:

> library(reticulate)
> use_condaenv( "tensorflow2_latest_p37")
/tmp/RtmpAs9fYG/file41912f80e49f.sh: 3: /home/ubuntu/anaconda3/envs/tensorflow2_latest_p37/etc/conda/activate.d/00_activate.sh: Bad substitution
Error in Sys.setenv(PATH = new_path) : wrong length for argument
In addition: Warning message:
In system2(Sys.which("sh"), fi, stdout = if (identical(intern, FALSE)) "" else intern) :
  running command ''/bin/sh' /tmp/RtmpAs9fYG/file41912f80e49f.sh' had status 2

正确的方法是什么?

【问题讨论】:

  • 是网状虫。见this
  • 你在哪里定义tf?你想念tf = import("tensorflow") 吗?

标签: python r tensorflow rstudio reticulate


【解决方案1】:

我发现最可靠的方法是在运行library(reticulate) 之前设置RETICULATE_PYTHON 系统变量,因为这将加载默认环境并且更改环境似乎有点问题。所以你应该尝试这样的事情:

library(tidyverse)
py_bin <- reticulate::conda_list() %>% 
  filter(name == "tensorflow2_latest_p37") %>% 
  pull(python)

Sys.setenv(RETICULATE_PYTHON = py_bin)
library(reticulate)

您可以通过将其放置在 .Rprofile 文件中来使其永久化。我通常在项目文件夹中放置一个,因此在打开项目时对其进行评估。在代码中,这看起来像这样(警告,这会覆盖现有的.Rprofile 文件):

writeLines(paste0("RETICULATE_PYTHON=", py_bin), ".Rprofile")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2014-03-06
    • 2016-06-08
    • 2013-12-03
    相关资源
    最近更新 更多