简体   繁体   English

在Keras合并2个连续模型

[英]Merge 2 sequential models in Keras

I a trying to merge 2 sequential models in keras. 我试图在keras中合并2个连续模型。 Here is the code: 这是代码:

model1 = Sequential(layers=[
    # input layers and convolutional layers
    Conv1D(128, kernel_size=12, strides=4, padding='valid', activation='relu', input_shape=input_shape),
    MaxPooling1D(pool_size=6),
    Conv1D(256, kernel_size=12, strides=4, padding='valid', activation='relu'),
    MaxPooling1D(pool_size=6),
    Dropout(.5),

])

model2 = Sequential(layers=[
    # input layers and convolutional layers
    Conv1D(128, kernel_size=20, strides=5, padding='valid', activation='relu', input_shape=input_shape),
    MaxPooling1D(pool_size=5),
    Conv1D(256, kernel_size=20, strides=5, padding='valid', activation='relu'),
    MaxPooling1D(pool_size=5),
    Dropout(.5),

])

model = merge([model1, model2], mode = 'sum')
Flatten(),
Dense(256, activation='relu'),
Dropout(.5),
Dense(128, activation='relu'),
Dropout(.35),
# output layer
Dense(5, activation='softmax')
return model

Here is the error log: 这是错误日志:

File "/nics/d/home/dsawant/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 392, 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. 文件“/nics/d/home/dsawant/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py”,第392行,在is_keras_tensor中引发ValueError('意外地找到了类型' + str(type(x)) + '的实例' + str(type(x)) + ' 。'ValueError:意外地发现了一个类型为<class 'keras.models.Sequential'>实例。期望一个符号张量实例。

Some more log: 更多日志:

ValueError: Layer merge_1 was called with an input that isn't a symbolic tensor. ValueError:使用不是符号张量的输入调用图层merge_1。 Received type: class 'keras.models.Sequential'. 收到类型:class'keras.models.Sequential'。 Full input: [keras.models.Sequential object at 0x2b32d518a780, keras.models.Sequential object at 0x2b32d521ee80]. 完整输入:[keras.models.Sequential object at 0x2b32d518a780,keras.models.Sequential object at 0x2b32d521ee80]。 All inputs to the layer should be tensors. 该层的所有输入都应该是张量。

How can I merge these 2 Sequential models that use different window sizes and apply functions like 'max', 'sum' etc to them? 如何合并使用不同窗口大小的这两个Sequential模型并将“max”,“sum”等函数应用于它们?

Using the functional API brings you all possibilities. 使用功能API为您带来所有可能性。

When using the functional API, you need to keep track of inputs and outputs, instead of just defining layers. 使用功能API时,您需要跟踪输入和输出,而不仅仅是定义图层。

You define a layer, then you call the layer with an input tensor to get the output tensor. 您定义一个图层,然后使用输入张量调用图层以获得输出张量。 Models and layers can be called exactly the same way. 模型和图层可以完全相同的方式调用。

For the merge layer, I prefer using other merge layers that are more intuitive, such as Add() , Multiply() and Concatenate() for instance. 对于合并层,我更喜欢使用更直观的其他合并层,例如Add()Multiply()Concatenate()

from keras.layers import *

mergedOut = Add()([model1.output,model2.output])
    #Add() -> creates a merge layer that sums the inputs
    #The second parentheses "calls" the layer with the output tensors of the two models
    #it will demand that both model1 and model2 have the same output shape

This same idea apply to all the following layers. 同样的想法适用于以下所有层。 We keep updating the output tensor giving it to each layer and getting a new output (if we were interested in creating branches, we would use a different var for each output of interest to keep track of them): 我们不断更新输出张量,将它提供给每一层并获得一个新输出(如果我们对创建分支感兴趣,我们将为每个感兴趣的输出使用不同的var来跟踪它们):

mergedOut = Flatten()(mergedOut)    
mergedOut = Dense(256, activation='relu')(mergedOut)
mergedOut = Dropout(.5)(mergedOut)
mergedOut = Dense(128, activation='relu')(mergedOut)
mergedOut = Dropout(.35)(mergedOut)

# output layer
mergedOut = Dense(5, activation='softmax')(mergedOut)

Now that we created the "path", it's time to create the Model . 现在我们创建了“路径”,是时候创建Model Creating the model is just like telling at which input tensors it starts and where it ends: 创建模型就像告诉它开始的输入张量以及结束的位置:

from keras.models import Model

newModel = Model([model1.input,model2.input], mergedOut)
    #use lists if you want more than one input or output    

Notice that since this model has two inputs, you have to train it with two different X_training vars in a list: 请注意,由于此模型有两个输入,因此您必须在列表中使用两个不同的X_training变量进行训练:

newModel.fit([X_train_1, X_train_2], Y_train, ....)    

Now, suppose you wanted only one input, and both model1 and model2 would take the same input. 现在,假设您只需要一个输入,并且model1和model2将采用相同的输入。

The functional API allows that quite easily by creating an input tensor and feeding it to the models (we call the models as if they were layers): 功能API通过创建输入张量并将其提供给模型(我们称模型就像它们是图层一样)非常容易:

commonInput = Input(input_shape)

out1 = model1(commonInput)    
out2 = model2(commonInput)    

mergedOut = Add()([out1,out2])

In this case, the Model would consider this input: 在这种情况下,模型会考虑这个输入:

oneInputModel = Model(commonInput,mergedOut)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM