首页 > 解决方案 > Keras R Value Error: No data provided for "dense_59"

问题描述

I am working with the KERAS package in R for the first time. Using this tutorial as help to guide my first model (https://keras.rstudio.com/articles/tutorial_basic_regression.html). Everything was going smoothly until I got to the actual "building of the model" I was able to replicate the example in the link perfectly, but once I substituted my own data, I could not get this error message to go away "Error in py_call_impl(callable, dots$args, dots$keywords) : ValueError: No data provided for "dense_59". Need data for each key in: ['dense_59'] "

I tried adjusting the units and all it did was change the number after "dense_." For what its worth, my training data is 6 columns 964 rows.

build_model <- function() {

  model <- keras_model_sequential() %>%
    layer_dense(units = 5, activation = "relu",
                input_shape = dim(train)[2]) %>%
    layer_dense(units = 5, activation = "relu") %>%
    layer_dense(units = 1)

  model %>% compile(
    loss = "mse",
    optimizer = optimizer_rmsprop(),
    metrics = list("mean_absolute_error")
  )

  model
}

model <- build_model()
model %>% summary()

print_dot_callback <- callback_lambda(
  on_epoch_end = function(epoch, logs) {
    if (epoch %% 80 == 0) cat("\n")
    cat(".")
  }
)    

epochs <- 200

history <- model %>% fit(
  train,
  train_labels,
  epochs = epochs,
  validation_split = 0.2,
  verbose = 0,
  callbacks = list(print_dot_callback)
)

Since this is my first time working with Keras, I really have no idea where to even start when it comes to solving this problem. Any help is much appreciated. Thank you!

标签: rtensorflowkerasneural-network

解决方案


Your data is not a minimal working example. your train refers to sth not given. Nobody can try your code. Thus nobody helped.

Always post a minimal working example - although you don't see it often. This is the fastest way to get quickly answers!

However, I took some time to answer this. And created what I needed to have.

Install keras and R in a virtual environment

I use conda, creating virtual environments - because it saves tons of work when you have to install complicated packages like keras.

# create new environment in conda
conda create --name newR
# enter new environment
conda activate newR
# install 'keras' package - and at the same time R and 
# everything you need to run keras properly.
conda install -c r r-keras

# enter R
R

# to fully intall 'keras' with 'tensorflow', do
require(keras)
install_keras()

# so easy the installation is with conda ... 5 min maybe.

Generate data

Since you gave no example data, I took iris data.

data(iris)
X <- iris[, 1:4]
y <- as.numeric(iris[, 5])

The data you gave wants to do regression, but iris' labels y are categorical data. I applied as.numeric() on the categorical data to make them numeric.

Try your given code

Then, I took your code, changed train to X and train_labels as y.

build_model <- function() {

  model <- keras_model_sequential() %>%
    layer_dense(units = 5, activation = "relu",
                input_shape = dim(X)[2]) %>%
    layer_dense(units = 5, activation = "relu") %>%
    layer_dense(units = 1)

  model %>% compile(
    loss = "mse",
    optimizer = optimizer_rmsprop(),
    metrics = list("mean_absolute_error")
  )

  model
}

print_dot_callback <- callback_lambda(
  on_epoch_end = function(epoch, logs) {
    if (epoch %% 80 == 0) cat("\n")
    cat(".")
  }
)    

epochs <- 200

history <- model %>% fit(
  as.matrix(X),
  y,
  epochs = epochs,
  validation_split = 0.2,
  verbose = 0,
  callbacks = list(print_dot_callback)
)

It runs smoothly without any error! (Dots).

>history
Trained on 120 samples (batch_size=32, epochs=200)
Final epoch (plot to see history):
                   loss: 0.04127
    mean_absolute_error: 0.1497
               val_loss: 0.1147
val_mean_absolute_error: 0.2761 

# save model
keras::save_model_hdf5(model, filepath = "test_rkeras.h5")

# load model
keras::load_model_hdf5("test_rkeras.h5")

which results in:

Model
________________________________________________________________________________
Layer (type)                        Output Shape                    Param #     
================================================================================
dense (Dense)                       (None, 5)                       25          
________________________________________________________________________________
dense_1 (Dense)                     (None, 5)                       30          
________________________________________________________________________________
dense_2 (Dense)                     (None, 1)                       6           
================================================================================
Total params: 61
Trainable params: 61
Non-trainable params: 0
________________________________________________________________________________

So it works well!

Conclusion

This proves that your model and the code is valid.

Simply your input data must be the problem! check its structure by using str(train). It should be a simple numeric matrix of 2 dimensions! Is your labels/targets vector a simple numeric vector?

Mostly errors occur when reading-in data. Always check after reading-in some data that the data looks like you expect it to be!


推荐阅读