Combine 2 consecutive models in Keras

I am trying to combine 2 consecutive models in keras. 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 instance enter <class 'keras.models.Sequential'>. The expected symbolic tensor instance.

A few more magazines:

ValueError: Layer merge_1 is called with an input that is not a symbolic tensor. The resulting type: class 'keras.models.Sequential'. Full input: [keras.models.Sequential object at 0x2b32d518a780, keras.models.Sequential at 0x2b32d521ee80]. All input data for the layer must be a tensor.

2 , , "max", "sum" ..

+14
1

API .

API , .

, , . .

, , 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

. , ( , 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)

, "", Model. - , :

from keras.models import Model

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

, , , X_training vars :

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

, , model1, model2 .

API , ( , ):

commonInput = Input(input_shape)

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

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

:

oneInputModel = Model(commonInput,mergedOut)
+18

Source: https://habr.com/ru/post/1684810/


All Articles