Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trouble with compiling my keras_model_sequential() #1421

Closed
josephkletzer opened this issue Apr 1, 2024 · 7 comments
Closed

Trouble with compiling my keras_model_sequential() #1421

josephkletzer opened this issue Apr 1, 2024 · 7 comments
Labels
awaiting response Waiting for issue author to respond

Comments

@josephkletzer
Copy link

josephkletzer commented Apr 1, 2024

Hey, i am fairly new to keras on R. I am now working through the Deep Learning with R book and in the first couple of chapters there is already a load of Errors for me.
So ive figured out how to install keras and tensorflow, like this:

install.packages("remotes")
remotes::install_github("rstudio/reticulate", force = TRUE)
remotes::install_github(sprintf("rstudio/%s", c("tensorflow", "keras")))
reticulate::miniconda_uninstall() # start with a blank slate
reticulate::install_miniconda()
#keras::install_keras()
#keras::install_keras(method = "conda", conda = "auto")
library(keras)
tensorflow::install_tensorflow(conda = "auto", envname = "r-reticulate", version = "release")
reticulate::use_condaenv(condaenv = "r-reticulate", conda = "auto", required = TRUE)`

Then i can import the mnist dataset normally.
After this i use the keras_model_sequential() function like this:

model1 <- keras_model_sequential(list(
  layer_dense(units = 512, input_shape = c(28, 28), activation = "relu", name = "layer1"),
  layer_dense(units = 10, activation = "softmax", name = "output")
))

When i then try to compile() it the following error code appears:

model1 %>% keras::compile(optimizer = "rmsprop",
        loss = "sparse_categorical_crossentropy",
        metrics = "accuracy")


Error: Fehler in UseMethod("compile") : 
  nicht anwendbare Methode für 'compile' auf Objekt der Klasse "c('keras.models.sequential.Sequential', 'keras.models.model.Model', 'keras.backend.tensorflow.trainer.TensorFlowTrainer', 'keras.trainers.trainer.Trainer', 'keras.layers.layer.Layer', 'keras.backend.tensorflow.layer.TFLayer', 'keras.backend.tensorflow.trackable.KerasAutoTrackable', 'tensorflow.python.trackable.autotrackable.AutoTrackable', 'tensorflow.python.trackable.base.Trackable', 'keras.ops.operation.Operation', 'python.builtin.object')" angewendet

So i figured that the class which is produced by my keras_model_sequential() must be different from keras.engine.training.Model, which would be expected as per documentation.

When i call summary(model1) the following appears:

<Sequential name=sequential, built=True>

When i call class(model1) there are multiple results:

[1] "keras.models.sequential.Sequential"                     
 [2] "keras.models.model.Model"                               
 [3] "keras.backend.tensorflow.trainer.TensorFlowTrainer"     
 [4] "keras.trainers.trainer.Trainer"                         
 [5] "keras.layers.layer.Layer"                               
 [6] "keras.backend.tensorflow.layer.TFLayer"                 
 [7] "keras.backend.tensorflow.trackable.KerasAutoTrackable"  
 [8] "tensorflow.python.trackable.autotrackable.AutoTrackable"
 [9] "tensorflow.python.trackable.base.Trackable"             
[10] "keras.ops.operation.Operation"                          
[11] "python.builtin.object"   

How do i get keras_model_sequential() to produce the correct class? I figure thats my problem.. Or what else could be my problem?

@t-kalinowski
Copy link
Member

t-kalinowski commented Apr 1, 2024

We no longer recommend installing keras with conda - please run the following commands to install keras (please note the '3' in 'keras3'):

install.packages("keras3")
## or, to install the development version
# remotes::install_github("rstudio/keras")
reticulate::install_python()
keras3::install_keras()

There is no need to call use_condaenv() or use_python() these days. A call like library(keras3) will be sufficient to cause reticulate to select the correct r-keras environment that was created by install_keras(). After keras has initialized, please confirm it is using the correct Python virtualenv "r-keras" by calling reticulate::py_config().

The S3 classes of the keras objects can change between releases, and the most likely cause of the issue is that there is a mismatch between the version of the R package installed, and the version of the underlying keras package.

@josephkletzer
Copy link
Author

When i try this method it stops at reticulate::install_python() with the following error:

Fehler in pyenv_bootstrap_windows() : 
  Please install git and ensure it is on your PATH

The Way i am installing it right now is the only thing that has worked so far...

@t-kalinowski
Copy link
Member

Can you install git as the error message suggests?

https://git-scm.com/download/win

Alternatively, you can install python manually from www.python.org/downloads. Note that the latest release is still too new for the backends, python 3.11 is the latest that is supported.

@josephkletzer
Copy link
Author

So i tried everything, and your way of installing works as well. But now i see that more often than not i get this error when i try to create a model:

Fehler in py_call_impl(callable, call_args$unnamed, call_args$named) : ValueError: Only input tensors may be passed as positional arguments. The following argument value should be passed as a keyword argument: <Sequential name=sequential, built=False> (of type <class 'keras.src.models.sequential.Sequential'>)

This is very frustrating, because its difficult to recreate this error, as sometimes when i install everything the first, or first couple of models work, but when i recreate the same models without changing the code, they suddenly turn up this error.... Have you ever seen this before? Do you have any ideas what could be the cause of this?

@josephkletzer
Copy link
Author

This is my Traceback:

`── Python Exception Message ────────────────────────────────
Traceback (most recent call last):
File "C:\Users\josep\OneDrive\DOKUME1\VIRTUA1\r-keras\lib\site-packages\keras\src\utils\traceback_utils.py", line 122, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\josep\OneDrive\DOKUME1\VIRTUA1\r-keras\lib\site-packages\keras\src\layers\layer.py", line 753, in call
raise ValueError(
ValueError: Only input tensors may be passed as positional arguments. The following argument value should be passed as a keyword argument: (of type <class 'keras.src.models.sequential.Sequential'>)

── R Traceback ─────────────────────────────────────────────

  1. ├─... %>% layer_dense(units = 10, activation = "softmax")
  2. ├─keras::layer_dense(., units = 10, activation = "softmax")
  3. │ └─keras::create_layer(...)
  4. ├─keras::layer_dense(., units = 30, activation = "relu")
  5. │ └─keras::create_layer(...)
  6. └─keras::layer_dense(., units = 512, activation = "relu")
  7. └─keras::create_layer(...)
  8. ├─keras:::compose_layer(object, layer)
    
  9. └─keras:::compose_layer.default(object, layer)
    
  10.   └─reticulate (local) layer(object, ...)
    
  11.     └─reticulate:::py_call_impl(callable, call_args$unnamed, call_args$named)
    

See reticulate::py_last_error()$r_trace$full_call for more details.

reticulate::py_last_error()$r_trace$full_call
[[1]]
keras_model_sequential() %>% layer_dense(units = 512, activation = "relu") %>%
layer_dense(units = 30, activation = "relu") %>% layer_dense(units = 10,
activation = "softmax")

[[2]]
layer_dense(., units = 10, activation = "softmax")

[[3]]
create_layer(keras$layers$Dense, object, list(units = as.integer(units),
activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer,
bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer,
bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer,
kernel_constraint = kernel_constraint, bias_constraint = bias_constraint,
input_shape = normalize_shape(input_shape), batch_input_shape = normalize_shape(batch_input_shape),
batch_size = as_nullable_integer(batch_size), dtype = dtype,
name = name, trainable = trainable, weights = weights))

[[4]]
layer_dense(., units = 30, activation = "relu")

[[5]]
create_layer(keras$layers$Dense, object, list(units = as.integer(units),
activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer,
bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer,
bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer,
kernel_constraint = kernel_constraint, bias_constraint = bias_constraint,
input_shape = normalize_shape(input_shape), batch_input_shape = normalize_shape(batch_input_shape),
batch_size = as_nullable_integer(batch_size), dtype = dtype,
name = name, trainable = trainable, weights = weights))

[[6]]
layer_dense(., units = 512, activation = "relu")

[[7]]
create_layer(keras$layers$Dense, object, list(units = as.integer(units),
activation = activation, use_bias = use_bias, kernel_initializer = kernel_initializer,
bias_initializer = bias_initializer, kernel_regularizer = kernel_regularizer,
bias_regularizer = bias_regularizer, activity_regularizer = activity_regularizer,
kernel_constraint = kernel_constraint, bias_constraint = bias_constraint,
input_shape = normalize_shape(input_shape), batch_input_shape = normalize_shape(batch_input_shape),
batch_size = as_nullable_integer(batch_size), dtype = dtype,
name = name, trainable = trainable, weights = weights))

[[8]]
compose_layer(object, layer)

[[9]]
compose_layer.default(object, layer)

[[10]]
layer(object, ...)

[[11]]
py_call_impl(callable, call_args$unnamed, call_args$named)`

@t-kalinowski
Copy link
Member

This error was fixed with a recent release of {keras}. Can you please make sure you're updated?

Also, for new code today, I'd recommend using library(keras3) instead of keras.

@t-kalinowski t-kalinowski added the awaiting response Waiting for issue author to respond label May 7, 2024
Copy link

github-actions bot commented Jun 7, 2024

Automatically closed because there has not been a response for 30 days. When you're ready to work on this further, please comment here and the issue will automatically reopen.

@github-actions github-actions bot closed this as completed Jun 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
awaiting response Waiting for issue author to respond
Projects
None yet
Development

No branches or pull requests

2 participants