bachr
bachr

Reputation: 6006

How to correct shape of Keras input into a 3D array

I've a Keras model that when I fit fails with this error

> kerasInput = Input(shape=(None, 47))
> LSTM(..)(kerasInput)
...
> model.fit(realInput, ...)
ValueError: Error when checking input: expected input_1 to have 3 dimensions, but got array with shape (10842, 1)

When looking at my input I found it has a shape of (10842, 1) but for each row it's actually a list of list. I can verify with

> pd.DataFrame(realInput[0]).shape
(260, 47)

How I could correct my input shape?

When trying with keras Reshape layer, the creation of the model fails with:

Model inputs must come from `keras.layers.Input` (thus holding past layer metadata), they cannot be the output of a previous non-Input layer. Here, a tensor specified as input to your model was not an Input tensor, it was generated by layer reshape_8.
Note that input tensors are instantiated via `tensor = keras.layers.Input(shape)`.
The tensor that caused the issue was: reshape_8/Reshape:0

Upvotes: 1

Views: 6100

Answers (2)

Wazaki
Wazaki

Reputation: 899

As I said before in the comments. You will need to make sure to reshape your data to match what LSTM expects to receive and also make sure the input_shape is correctly set.

I found this post quite helpful when I struggled with inputting to an LSTM layer. I hope it helps you too : Reshape input for LSTM

Upvotes: 1

nilansh bansal
nilansh bansal

Reputation: 1494

  1. You can use numpy.expand_dims method to convert the shape to 3D.

    import numpy as np
    
    np.expand_dims(realInput,axis=0)
    
  2. Reshape layer keras

    https://keras.io/layers/core/#reshape

  3. Use the third parameter as 1

    # Something Similar to this
    X_train = np.reshape(X_train,(X_train.shape[0],X_train.shape[1],1))
    

Edit: Added np.reshape method

Refer this repository: https://github.com/NilanshBansal/Stock_Price_Prediction/blob/master/Stock_Price_Prediction_20_days_later_4_LSTM.ipynb

Upvotes: 4

Related Questions