Issue
I've been following a couple of tensorflow tutorials that don't work.
https://www.amestosolutions.no/blogg/using-keras-in-r--simpler-than-ever/ https://www.datacamp.com/community/tutorials/keras-r-deep-learning
Here is some sample code that is very similar to what's in the tutorials.
x <-rnorm(1000) #input variables
y <- rnorm(1000) #input variables
z <-x+y+rnorm(1000) #output variable
df <-data.frame(x=x,y=y,z=z)
model <- keras_model_sequential() %>%
layer_dense(units = 8,activation = "relu",input_shape = 2) %>%
layer_dense(units = 8,activation = "relu") %>%
layer_dense(units = 1,activation = "relu")
model %>% compile(
loss = "mse",
optimizer = optimizer_adam(),
metrics = list("mean_absolute_error"))
model %>% fit(df[,1:2],df[,3], epochs = 20)
When I run it, I get this error:
Error in py_call_impl(callable, dots$args, dots$keywords) :
ValueError: in user code:
C:\Users\User\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\engine\training.py:853 train_function *
return step_function(self, iterator)
C:\Users\User\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\engine\training.py:842 step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
C:\Users\User\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1286 run
return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
C:\Users\User\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2849 call_for_each_replica
return self._call_for_each_replica(fn, args, kwargs)
C:\Users\User\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:3632 _call_for_each_replica
return fn(*args, **kwargs)
I am using tensorflow 2.6
What in this code could be causing me this error, and how would I fix it?
Solution
You probably want to pass an array to the fit()
method for the input training data, right now you are passing in a data.frame. Converting df
to a matrix/R array in your example makes everything work:
library(keras)
x <- rnorm(1000) #input variables
y <- rnorm(1000) #input variables
z <- x + y + rnorm(1000) #output variable
mat <- cbind(x, y, z)
model <- keras_model_sequential(input_shape = 2) %>%
layer_dense(8, activation = "relu") %>%
layer_dense(8, activation = "relu") %>%
layer_dense(1, activation = "relu")
#> Loaded Tensorflow version 2.6.0
model %>% compile(
loss = "mse",
optimizer = optimizer_adam(),
metrics = list("mean_absolute_error")
)
model %>% fit(mat[, 1:2], mat[, 3])
Created on 2021-10-05 by the reprex package (v2.0.1)
Answered By - t-kalinowski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.