user2840286
user2840286

Reputation: 601

R Keras flatten layer - got an array of shape 1

I am trying to build a model in R Keras with TensorFlow that just has a flatten layer. Here is a snippet of the code:

model <- keras_model_sequential() %>%
  layer_flatten(input_shape = c(lookback, dim(train.data)[-1]))

model %>% compile(
  optimizer = optimizer_rmsprop(),
  loss = "mae"
)

history <- model %>% fit_generator(
  train_gen,
  steps_per_epoch = 500,
  epochs = 20
)

lookback is 1200 and dim(train.data) is (13155, 3). The input to the flatten layer is (1200, 3) and I expect it should output a 1D vector of 3600.

train_gen returns a list of 2. The first is a 3D matrix with dimensions (129, 1200, 3) and the second one is a 1D vector with dimension (129,).

However, I get the error:

Error in py_call_impl(callable, dots$args, dots$keywords) : 
  ValueError: Error when checking target: expected dense_15 to have shape (3600,) but got array with shape (1,)

I don't know why this is happening. If I add a layer_dense(units = 1) it works but I don't understand why.

Upvotes: 1

Views: 340

Answers (1)

today
today

Reputation: 33410

The target shapes are incompatible: you provide as target a vector of size of 1 (i.e. (129,) means 129 sample labels with size one), however the model's output shape is (None, 3600) so it expects vectors of size 3600. And that's why when you add a Dense layer with one unit the problem is resolved: the Dense layer's output shape is (None, 1) and you provide (129,) and they match with each other, hence no issue to complain about.

Upvotes: 1

Related Questions