如何校正Keras输入3D阵列的形状

时间:2018-10-14 15:02:57

标签: pandas numpy dataframe keras

我有一个Keras模型,当我适合时会因该错误而失败

> 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)

查看我的输入时,我发现它的形状为(10842, 1),但实际上每一行都是一个列表列表。我可以用

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

如何校正输入形状?

尝试使用keras Reshape层时,模型创建失败,并显示以下信息:

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

2 个答案:

答案 0 :(得分:1)

  1. 您可以使用numpy.expand_dims方法将形状转换为3D。

    import numpy as np
    
    np.expand_dims(realInput,axis=0)
    
  2. 重塑层keras

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

  3. 将第三个参数用作1

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

编辑:添加了np.reshape方法

请参考此存储库:https://github.com/NilanshBansal/Stock_Price_Prediction/blob/master/Stock_Price_Prediction_20_days_later_4_LSTM.ipynb

答案 1 :(得分:1)

正如我之前在评论中所说。您需要确保调整数据的形状以符合LSTM期望接收的数据,并确保正确设置了input_shape。

当我努力输入LSTM层时,我发现这篇文章很有帮助。我希望它也对您有帮助:Reshape input for LSTM