Keras Lambda层给出ValueError:输入0与层xxx不兼容:预期的min_ndim = 3,找到的ndim = 2

时间:2019-03-07 14:54:41

标签: python keras deep-learning

当我在顺序模型中添加lambda层时,它会出现ValueError:输入0与...不兼容。

对于此模型,我得到ValueError: Input 0 is incompatible with layer flatten_1: expected min_ndim=3, found ndim=2

model1 = Sequential()
model1.add(Embedding(max_words, embedding_dim, input_length=maxlen))
model1.add(Lambda(lambda x: mean(x, axis=1)))
model1.add(Flatten())
model1.add(Bidirectional(LSTM(32)))
model1.add(Dropout(0.6))
model1.add(Dense(2))

如果我删除Flatten(),则会得到:ValueError: Input 0 is incompatible with layer bidirectional_1: expected ndim=3, found ndim=2。但是,没有lambda层,模型可以正常工作。

任何引起此问题以及如何解决此问题的想法将不胜感激。谢谢

1 个答案:

答案 0 :(得分:1)

下面的代码生成了一个看起来正确的图形:

from tensorflow.python import keras
from keras.models import Sequential
from keras.layers import *
import numpy as np

max_words = 1000
embedding_dim = 300
maxlen = 10

def mean(x, axis):
  """mean
     input_shape=(batch_size, time_slots, ndims)
     depending on the axis mean will:
       0: compute mean value for a batch and reduce batch size to 1
       1: compute mean value across time slots and reduce time_slots to 1
       2: compute mean value across ndims an reduce dims to 1.
  """
  return K.mean(x, axis=axis, keepdims=True)

model1 = Sequential()
model1.add(Embedding(max_words, embedding_dim, input_length=maxlen))
model1.add(Lambda(lambda x: mean(x, axis=1)))
model1.add(Bidirectional(LSTM(32)))
model1.add(Dropout(0.6))
model1.add(Dense(2))
model1.compile('sgd', 'mse')
model1.summary()

嵌入层使用3个维度(batch_size,maxlen,embedding_dim)。 LSTM层也期望3维。因此,lambda应该返回兼容的形状,或者您需要重塑形状。在这里,K.mean提供了一个方便的参数(keepdims),可以帮助我们做到这一点。