'Error in virtualenv_install for tensorflow in R

I am trying to train a model using keras library in RStudio.

library(keras)
N <- 100
x <- runif(N, -2, 3)
# Build a Gompertz function with some noise
a <- 10 # ceiling parameter
b <- 0 # horizontal shift parameter
c <- 2 # growth rate parameter
y <- a*exp(-exp(b - c*x)) + rnorm(N, mean=0, sd= a/10)
plot(x,y)
# format data in a way model.fit() would like it
x <- as.matrix(x)
y <- as.matrix(y)
# sequence along x for later prediction
xnew <- as.matrix(seq(from=min(x), to=max(x), length.out=1000))
# Build and compile simple model
model <- keras_model_sequential() |>
layer_dense(units=32, activation="relu", input_shape=1) |>
layer_dense(units=16, activation = "relu") |>
layer_dense(units=1, activation="linear")

at this point I got an error

Error: Python module tensorflow.keras was not found.

Detected Python configuration:

I found a similar issue here and tried to

library(keras)
library(tensorflow)
install_tensorflow()
install_keras()

But I got this error:

Error in virtualenv_install(envname = envname, packages = packages, ignore_installed = pip_ignore_installed, : '/usr/local/bin' exists but is not a virtual environment

I have tensorflow and keras installed in my python 3.9. Here is my pip3 freeze output:

enter image description here



Solution 1:[1]

Many installation issues are resolved by running the following in a fresh R session (you can restart R in Rstudio with Ctrl+Shift+F10) :

# install the development version of packages, in case the
# issue is already fixed but not on CRAN yet.
install.packages("remotes")
remotes::install_github(sprintf("rstudio/%s", c("reticulate", "tensorflow", "keras")))
reticulate::miniconda_uninstall() # start with a blank slate
reticulate::install_miniconda()
keras::install_keras()

Test to see if installation was successful.

tensorflow::as_tensor("Hello World")

If the above snippet succeeded and you saw something like tf.Tensor(b'Hello World', shape=(), dtype=string), then you've successfully installed Tensorflow! If not, please file an issue at https://github.com/rstudio/tensorflow/issues

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 t-kalinowski