H.Bukhari
H.Bukhari

Reputation: 2291

Combine Layers with Input

Is it possible in keras add external input to Merge layer? I have simple embedding which I would like to combine with external values, but every time I try to do I always get error. Is there way to add external input to Keras layers?

models = []
inputs =Input(shape=(10,))
models.append(inputs)
for i in range(2):
    model_s = Sequential()
    model_s.add(Embedding(1115, 10, input_length=1, name='Hb_{}'.format(i)))
    model_s.add(Reshape(target_shape=(10,)))
    models.append(model_s)

    

model = Sequential()
model.add(Merge(models, mode='concat'))
model.add(Dense(1000, kernel_initializer='uniform'))
model.add(Activation('relu'))
model.add(Dense(500, kernel_initializer='uniform'))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.summary()   

Error

Tensor' object has no attribute 'get_output_shape_at'

This is the small code for testing.

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])


m={'Hb_0_input': np.array([0,1, 2, 3, 4, 5, 6, 7, 8, 9]),'Hb_1_input': np.array([0,1, 2, 3, 4, 5, 6, 7, 8, 9]), 'x': np.array([0,1, 2, 3, 4, 5, 6, 7, 8, 9])}
y=np.array([0, 1, 0, 1, 0, 1, 0, 0, 0, 0])
model.fit(m, y)

Upvotes: 0

Views: 118

Answers (1)

Daniel Möller
Daniel Möller

Reputation: 86650

Not sure what is your intention, but you're mixing models and tensors in the same list models = [inputs, model1, model2]. This is the cause of the error.

Now, we have no idea about what kinds of input you have, so we cannot help further, but assuming a few things (that may be wrong) this code can help you:

inputForEmbedding = Input((length,)) #where length seems to be 1
extraInput = Input(shapeOfTheExtraInput) #I don't know this shape

model1Out = Embedding(1115, 10, input_length=1 name='Hb_{}'.format(i))(inputForEmbedding)
model1Out = Reshape((10,))(model1Out)

....you must make the shapes compatible for `model1Out` and `extraInput`...

outputs = Concatenate(axis=...)([model1Out,extraInput])
outputs = Dense(1000, kernel_initializer='uniform')(outputs)
outputs = Activation('relu')(outputs)
outputs = Dense(500, kernel_initializer='uniform')(outputs)
outputs = Activation('relu')(outputs)
outputs = Dense(1)(outputs)
outputs = Activation('sigmoid')(outputs)

model = Model([inputForEmbedding, extraInput])
model.summary()   

Upvotes: 2

Related Questions