tensorflowkerasduplicatesmultiple-input

How can I have multiple duplicate input layers from the first input layer in tensorflow library?


I want multiple duplicate input layers from the first input layer. So that I don't have to send the input to the fit function twice.

Image


Solution

  • You can reuse the instance of the input layer when creating your two models. I can see in the image that you want to concatenate the output of the two separate layers, so I also included that in my code snippet.

    Firstly, I create the input layer. Then I create two sub-models that use the same instance of the input. I stack the output of both sub-models. You can also use tf.concat instead of tf.stack.

    import tensorflow as tf
    from tensorflow.python.keras import layers
    from tensorflow.python.keras import Model
    
    
    def get_model(input_layer):
        model = tf.keras.Sequential(
            [
                input_layer,
                layers.Dense(32, activation="relu"),
                layers.Dense(32, activation="relu"),
                layers.Dense(1),
            ]
        )
        return model
    
    
    num_features = 3
    input = tf.keras.Input(shape=(num_features,))
    
    model1 = get_model(input)
    model2 = get_model(input)
    
    combined_output = tf.stack([model1.output, model2.output], axis=0)
    
    model = Model(inputs=input, outputs=combined_output)
    
    print(tf.shape(model(tf.ones([32, 3]))))
    

    The batch size is 32, and the number of features is 3. The code snippet prints

    tf.Tensor([ 2 32  1], shape=(3,), dtype=int32)