ValueError: 输入0与层lstm_1不兼容:期望维度为3,但发现维度为2 [keras]

我遇到了以下错误: ValueError: Input 0 is incompatible with layer lstm_1: expected ndim=3, found ndim=2,这是我使用的代码:

def make_model():  model = Sequential()        model.add(Conv2D(20,(5,5), input_shape = (24,48,30), activation = "relu", strides = 1, padding = "valid"))  model.add(MaxPooling2D(pool_size=(2,2)))          model.add(Conv2D(50, (5,5), use_bias = 50))      model.add(MaxPooling2D(pool_size=(2,2)))      model.add(Flatten())  model.add(Dense(20, activation = "relu"))  model.add(LSTM(50, activation="relu", return_sequences=True))  return model

我的输入是30个大小为24*48的矩阵。


回答:

问题在于最后一个Dense层(LSTM层之前)的输出形状为(?, 20),而LSTM层期望的是一个3D张量,而不是2D张量。因此,您可以在输入到LSTM层之前扩展维度。

您可以使用tf.expand_dims来扩展维度(假设您使用TensorFlow作为后端) tf expand

input_layer = Input((30,24,48))model = Conv2D(20,(5,5), input_shape = (30,24,48), activation = "relu", strides = 1, padding = "valid")(input_layer)model = MaxPooling2D(pool_size=(2,2))(model)        model = Conv2D(50, (5,5), use_bias = 50)(model)    model = MaxPooling2D(pool_size=(2,2))(model)  model = Flatten()(model)model = Dense(20, activation = "relu")(model)model = tf.expand_dims(model, axis=-1)model = LSTM(50, activation="relu", return_sequences=True)(model)

(我没有使用Sequential模式,我使用的是函数式API,因为它更灵活)

如果您想使用Sequential模型:

    model = Sequential()          model.add(Conv2D(20,(5,5), input_shape = (30, 24, 48), activation = "relu", strides = 1, padding = "valid"))    model.add(MaxPooling2D(pool_size=(2,2)))            model.add(Conv2D(50, (5,5), use_bias = 50))        model.add(MaxPooling2D(pool_size=(2,2)))        model.add(Flatten())    model.add(Dense(20, activation = "relu"))    model.add(Lambda(lambda x: tf.expand_dims(model.output, axis=-1)))    model.add(LSTM(50, activation="relu", return_sequences=True))

您必须在Lambda中使用expand dims

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注