tensorflow 如何使用R reticulate激活现有Python环境

idfiyjo8  于 2022-11-16  发布在  Python
关注(0)|答案(1)|浏览(218)

我有以下现有的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

正确的做法是什么?

w6mmgewl

w6mmgewl1#

我发现最可靠的方法是在运行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文件中,使它成为永久性的。我通常把它放在项目文件夹中,这样它在打开项目时就被计算了。在代码中,它看起来像这样:

readr::write_lines(paste0("RETICULATE_PYTHON=", py_bin), 
                   ".Rprofile", append = TRUE)

或者更简单,使用usethis::edit_r_profile(scope = "project")(谢谢你@rodrigo-zepeda!)。

相关问题