Taran
Taran

Reputation: 365

Correct input_shape for an LSTM in kerasR

I see a lot of help for similar topics in python but I was using the R implementation and can't seem to replicate any of the suggested solutions.

I am attempting to setup an LSTM like so,

mod <- Sequential()

mod$add(LSTM(50, activation = 'relu', dropout = 0.25, input_shape = c(dim(X_train_scaled)[1], dim(X_train_scaled)[2]), return_sequences = TRUE))

mod$add(Dense(1))

keras_compile(mod,  loss = 'mean_squared_error', optimizer = 'adam')

keras_fit(mod, X_train_scaled, Y_train, batch_size = 72, epochs = 10, verbose = 1, validation_split = 0.1)

However, when I run the keras_fit I get the following error,

Error in py_call_impl(callable, dots$args, dots$keywords) : ValueError: Error when checking input: expected lstm_36_input to have 3 dimensions, but got array with shape (2000, 44)

The X_train is a numeric matrix with 2000 rows and 44 columns that represent 2000 timesteps and the values of 44 features at each timestep

The Y_train is a numeric vector of length 2000

I should add that when I attempt to use a 3 dimensional value for the input_shape so as to specify an input shape that follows the (samples, timesteps, features) structure, I get an error like this when I add the LSTM layer to the model,

Error in py_call_impl(callable, dots$args, dots$keywords) : ValueError: Input 0 is incompatible with layer lstm_37: expected ndim=3, found ndim=4

Upvotes: 2

Views: 968

Answers (1)

Andres D.
Andres D.

Reputation: 11

Your train matrix should be 3-dimensional (samples, timesteps, features). Then you have to use 2nd and 3rd dimensions for input_shape:

input_shape = c(dim(X_train_scaled)[2], dim(X_train_scaled)[3])

Also, number of rows in your dataset is samples, not timesteps. You can read more about samples, timesteps and features here.

Upvotes: 1

Related Questions