【问题标题】:How to "Merge" Sequential models in Keras 2.0?如何在 Keras 2.0 中“合并”顺序模型?
【发布时间】:2018-03-05 22:53:44
【问题描述】:

我正在尝试在 Keras 2.0 中合并两个序列模型,使用以下行:

merged_model.add(Merge([model1, model2], mode='concat'))

这仍然可以正常工作,但会发出警告:

"The `Merge` layer is deprecated and will be removed after 08/2017. Use
instead layers from `keras.layers.merge`, e.g. `add`, `concatenate`, etc." 

但是,研究 Keras 文档并尝试添加 Add() 并没有产生有效的结果。我已经阅读了有同样问题的人的几篇帖子,但在下面的案例中没有找到适合我的解决方案。有什么建议吗?

model = Sequential()
model1 = Sequential()
model1.add(Dense(300, input_dim=40, activation='relu', name='layer_1'))
model2 = Sequential()
model2.add(Dense(300, input_dim=40, activation='relu', name='layer_2'))
merged_model = Sequential()

merged_model.add(Merge([model1, model2], mode='concat'))

merged_model.add(Dense(1, activation='softmax', name='output_layer'))
merged_model.compile(loss='binary_crossentropy', optimizer='adam', 
metrics=['accuracy'])

checkpoint = ModelCheckpoint('weights.h5', monitor='val_acc',
save_best_only=True, verbose=2)
early_stopping = EarlyStopping(monitor="val_loss", patience=5)

merged_model.fit([x1, x2], y=y, batch_size=384, epochs=200,
             verbose=1, validation_split=0.1, shuffle=True, 
callbacks=[early_stopping, checkpoint])

编辑:当我尝试时(如下 Kent Sommer 所建议):

from keras.layers.merge import concatenate
merged_model.add(concatenate([model1, model2]))

这是错误信息:

Traceback (most recent call last):
  File "/anaconda/lib/python3.6/site- packages/keras/engine/topology.py", line 425, 
in assert_input_compatibility
    K.is_keras_tensor(x)
  File "/anaconda/lib/python3.6/site-
packages/keras/backend/tensorflow_backend.py", line 403, in     is_keras_tensor
    raise ValueError('Unexpectedly found an instance of type `' +
 str(type(x)) + '`. '
ValueError: Unexpectedly found an instance of type 
`<class'keras.models.Sequential'>`. Expected a symbolic tensor instance.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "quoradeeptest_simple1.py", line 78, in <module>
    merged_model.add(concatenate([model1, model2]))
  File "/anaconda/lib/python3.6/site-packages/keras/layers/merge.py",
 line 600, in concatenate return Concatenate(axis=axis, **kwargs)(inputs)
  File "/anaconda/lib/python3.6/site-   packages/keras/engine/topology.py", 
line 558, in __call__self.assert_input_compatibility(inputs)
  File "/anaconda/lib/python3.6/site-packages/keras/engine/topology.py", line 431, 
 in assert_input_compatibility str(inputs) + '.All inputs to the layer '
ValueError: Layer concatenate_1 was called with an input that isn't a
symbolic tensor. Received type: <class 'keras.models.Sequential'>. 
Full input: [<keras.models.Sequential object at 0x140fa7ba8>,
<keras.models.Sequential object at 0x140fabdd8>]. All inputs to the
layer should be tensors.

【问题讨论】:

标签: python keras


【解决方案1】:

该警告的意思是,不再使用具有特定模式的合并层,而是将不同的模式拆分为各自的层。

所以Merge(mode='concat') 现在是concatenate(axis=-1)。

但是,由于您想合并模型而不是图层,因此这不适用于您的情况。您需要做的是使用功能模型,因为基本 Sequential 模型类型不再支持此行为。

在您的情况下,这意味着代码应更改为以下内容:

from keras.layers.merge import concatenate
from keras.models import Model, Sequential
from keras.layers import Dense, Input

model1_in = Input(shape=(27, 27, 1))
model1_out = Dense(300, input_dim=40, activation='relu', name='layer_1')(model1_in)
model1 = Model(model1_in, model1_out)

model2_in = Input(shape=(27, 27, 1))
model2_out = Dense(300, input_dim=40, activation='relu', name='layer_2')(model2_in)
model2 = Model(model2_in, model2_out)


concatenated = concatenate([model1_out, model2_out])
out = Dense(1, activation='softmax', name='output_layer')(concatenated)

merged_model = Model([model1_in, model2_in], out)
merged_model.compile(loss='binary_crossentropy', optimizer='adam', 
metrics=['accuracy'])

checkpoint = ModelCheckpoint('weights.h5', monitor='val_acc',
save_best_only=True, verbose=2)
early_stopping = EarlyStopping(monitor="val_loss", patience=5)

merged_model.fit([x1, x2], y=y, batch_size=384, epochs=200,
             verbose=1, validation_split=0.1, shuffle=True, 
callbacks=[early_stopping, checkpoint])

【讨论】:

  • 谢谢!我试过了,但这又产生了另一个错误——我在上面的“编辑”之后添加了这个错误。显然,两者并不完全等价。
  • 我已更新我的答案以修复您的新错误。对于一开始没有正确阅读您的问题,我深表歉意!
  • 没问题。非常感谢。将处理此问题并通知您。
  • 这导致:ValueError:检查输入时出错:预期 input_1 有 4 个维度,但得到的数组形状为 (100, 40)
  • 我将输入形状更改为 model1_in = Input(shape=(40,)) 现在它可以工作了,谢谢!
【解决方案2】:

用 keras==2.2.4 和 tensorflow==1.13.1 试试这个演示:

from keras import Sequential, Model
from keras.layers import Embedding, GlobalAveragePooling1D, Dense, concatenate
import numpy as np

model1 = Sequential()
model1.add(Embedding(20, 10, trainable=True))
model1.add(GlobalAveragePooling1D())
model1.add(Dense(1, activation='sigmoid'))
model2 = Sequential()
model2.add(Embedding(20, 10, trainable=True))
model2.add(GlobalAveragePooling1D())
model2.add(Dense(1, activation='sigmoid'))

model_concat = concatenate([model1.output, model2.output], axis=-1)
model_concat = Dense(1, activation='softmax')(model_concat)
model = Model(inputs=[model1.input, model2.input], outputs=model_concat)

model.compile(loss='binary_crossentropy', optimizer='adam')

X_train_1 = np.random.randint(0, 20, (10000, 256))
X_train_2 = np.random.randint(0, 20, (10000, 256))
Y_train = np.random.randint(0, 2, 10000)

model.fit([X_train_1, X_train_2], Y_train, batch_size=1000, epochs=200,
              verbose=True)

【讨论】:

  • 谢谢!我在stackoverflow上经历了许多解决方案,但这一个对我有用。从已经工作的脚本开始可以更容易地根据我的情况对其进行修改。这个演示最好的部分是它不需要我安装或下载另一个数据集。
  • 向 model.fit 提供多个输入时,我面临以下错误。我想知道你是否也遇到过这个错误。 ValueError: 未能找到可以处理输入的数据适配器:( 包含类型 {""}),
  • stackoverflow.com/questions/68330534/…你能帮我解决这个问题吗?
【解决方案3】:

除非您有充分的理由将模型分开,否则您可以(并且应该)在单个模型中拥有相同的拓扑。比如:

input1 = Input(shape=(27, 27, 1))
dense1 = Dense(300, activation='relu', name='layer_1')(input1)
input2 = Input(shape=(27, 27, 1))
dense2 = Dense(300, activation='relu', name='layer_2')(input2)
merged = concatenate([dense1, dense2])
out = Dense(1, activation='softmax', name='output_layer')(merged)
model = Model(inputs = [input1, input2], outputs = [out])

【讨论】:

  • 谢谢。我试了一下,得到:ValueError:检查输入时出错:预期 input_1 有 4 个维度,但得到了形状为 (100, 40) 的数组。与肯特的建议相同。还没弄清楚我做错了什么。
  • 我将输入形状更改为 model1_in = Input(shape=(40,)),现在可以使用了,谢谢!
猜你喜欢
  • 2019-02-13
  • 2018-02-09
  • 2018-02-06
  • 2019-12-16
  • 2019-02-24
  • 2021-07-31
  • 2017-11-26
  • 2021-08-20
  • 1970-01-01
相关资源
最近更新 更多