2017-04-05 71 views
1

下面是我遇到的问题的简化版本。Keras中的掩蔽零嵌入层

的样本数据:

X = np.round(np.random.rand(10, 10) * 10).astype(np.int32) 
y = np.round(np.random.rand(10)).astype(np.int32) 

型号:

i = Input(shape=(10,), name='sentence_input', dtype='int32') 
x = Embedding(1000, 10, mask_zero=True)(i) 
o = LSTM(10)(x) 
enc_model = Model(i, o) 

i2 = Input(shape=(10,), dtype='int32') 
x2 = enc_model(i2) 
o2 = Dense(1, activation='sigmoid')(x2) 

model = Model(i2, o2) 
model.compile(optimizer='rmsprop', loss='binary_crossentropy') 
model.fit(X, y, epochs=1) 

我使用Tensorflow 1.0.1作为Keras后端。 Keras版本2.0。

我要添加掩蔽,但此刻mask_zero=True加时,出现错误:

InvalidArgumentError: You must feed a value for placeholder tensor 'sentence_input_10' with dtype int32 
[[Node: sentence_input_10 = Placeholder[dtype=DT_INT32, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 

我虽然两个Input层添加dtype='int32'将解决这个问题。

我需要有enc_model作为一个单独的Model

回答

0

我觉得你的1000 input_dim太大了,你不只是有10个值作为输入?
所以它应该是12(因为你使用mask_zero = True)。

mask_zero: Whether or not the input value 0 is a special "padding" value that should be masked out. This is useful when using recurrent layers which may take variable length input. If this is True then all subsequent layers in the model need to support masking or an exception will be raised. If mask_zero is set to True, as a consequence, index 0 cannot be used in the vocabulary (input_dim should equal |vocabulary| + 2).

+0

我意识到|词汇| +2规则,但这里并没有改变任何东西。我做了一个足够简单的例子,让任何人在他们的计算机上执行/实验(假设您使用Keras 2和TF 1.0。*)。如果您将1000更改为12,则错误仍然存​​在。顺便说一句。我怀疑是一个凯拉斯错误,但只是想确保我没有做错什么。 – bartgras

+0

我尝试了一下,看起来问题在于,您希望将模型用作图层,但这不起作用。如果您将第一个模型的图层集成到第二个模型的图层中,那么图层看起来不是问题。我可以问为什么你需要分离模型? 解决办法可能是编写自己的keras图层,并在第二个模型中使用它。 – Paul

+0

我需要它分开,因为我的enc_model被重复使用在2个独立的输入必须共享相同的权重。在我尝试使用Sequential重写它之前,它仍然会给出相同的错误。该代码基于https://keras.io/getting-started/functional-api-guide/,称为“共享视觉模型”的示例代码片段。我做的完全一样,直到屏蔽被添加为止。 – bartgras