本博英文版参见:
[English Version]

1 项目场景

利用TensorFlow的LSTM模型进行预测


2 问题描述

在使用TensorFlow进行数据预测的时候,在
model.fit的时候可能会报形如
Input 0 of layer "lstm_37" is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (16, 7)
的错误

Model.fit(X_train, Y_train, batch_size = BATCH_SIZE, epochs = EPOCHS, shuffle = True, verbose = 1, validation_split = VALIDATION_SPLIT)

3 原因分析

这是由于输入数组的维度不匹配导致的,缺失了一维数据,我们可以通过增维的方法改进这一错误


4 解决方案:

这是原本的输入

X_train = df_1.values

4.1 方法1

通过.reshape()方法改进数组

X_train = X_train.reshape(dimi_x,dim_y,dim_z)

.reshape方法可以直接对数组的维度进行设置来符合模型需要

4.2 方法2

通过np.expand_dims()方法
numpy是一款Python常用的基础数学计算工具

import numpy as np   # 导入numpy基础计算模块(import numpy module)

X_train = np.expand_dims(X_train, axis=0)

通过此方法可以较简便地实现扩维

4.3 方法3

通过Lambda(lambda _:K.expand_dims(_,axis=-1))()实现

import keras.backend as K
from keras.layers import Lambda

X_train = Lambda(lambda d_1:K.expand_dims(X_train,axis=-1))(X_train)

注意:以上三种方法扩维可能会出现新的报错:
ValueError: Input 0 of layer "lstm_43" is incompatible with the layer: expected ndim=3, found ndim=4. Full shape received: (None, 63360, 7, 1)
这是因为输入数组因为扩维造成了新的问题,即当前输入维度超过了预期维度3,此时可以尝试删去建模过程中的
input_shape = X_train.shape

4.4 方法4

X_train = X_train[:, None]
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐