keras中

时间:2018-05-17 22:42:59

标签: python keras

我正在尝试关注在线教程,并在Keras中为广泛而深入的模型编写代码。但是,我遇到了将两个模型合并在一起的问题

wide = Sequential()
wide.add(Dense(1, input_dim=X_train.shape[1], kernel_initializer ='uniform', activation='relu'))

deep = Sequential()
deep.add(Dense(1, input_dim=X_train.shape[1], kernel_initializer ='uniform', activation='relu'))
deep.add(Dense(100, activation='relu'))
deep.add(Dense(50, activation='relu'))
deep.add(Dense(1, activation='linear'))

model = Sequential()
model.add(Merge([wide, deep], mode='concat', concat_axis=1))
model.add(Dense(1, activation='linear'))

发生以下警告:

model = Sequential()
model.add(Merge([wide, deep], mode='concat', concat_axis=1))
__main__:2: UserWarning: The `Merge` layer is deprecated and will be removed after 08/2017. Use instead layers from `keras.layers.merge`, e.g. `add`, `concatenate`, etc

警告信息告诉我该怎么做,但我还没弄清楚如何将两种模型结合起来。

我尝试过以下不同的事情,但不断出错。

from keras.layers import add
model = Sequential()

model.add([wide, deep])
Traceback (most recent call last):

  File "<ipython-input-428-3e81d6d35c6f>", line 1, in <module>
    model.add([wide, deep])

  File "/Users/abrahammathew/anaconda3/lib/python3.6/site-packages/keras/models.py", line 430, in add
    'Found: ' + str(layer))

TypeError: The added layer must be an instance of class Layer. Found: [<keras.models.Sequential object at 0x1a32876cc0>, <keras.models.Sequential object at 0x1a328761d0>]

任何人都可以告诉我如何使用keras连接广泛和深入的模型。

1 个答案:

答案 0 :(得分:1)

这是因为您正在尝试合并Sequential模型中的模型。在这种情况下,您需要扩展到functional API,因为您需要先计算两个模型的输出,然后才能合并它们。有点像:

in = Input(shape=(X_train.shape[1],)
wide_out = wide(in)
deep_out = deep(in)
wide_deep = concatenate([wide_out, deep_out]) # or any merge layer
out = Dense(1, activation='linear')(wide_deep)
model = Model(in, out) # Your final model

简而言之,在功能API层中,类似于将设置操作应用于给定层的函数,从而创建相应的计算图。