Search code examples
tensorflowkerastensorflow2.0

How to use Keras preprocessing layers with functional APIs


Following sequential model is equal to the model created using functional API in the second code snippet.

model = Sequential([
    Dense(...),
    Dense(...),
    Dense(...),
])
input = Input(...)
x = Dense(...)(x)
x = Dense(...)(x)
output = Dense(...)(x)
model = Model(inputs=input, outputs=output)

But, how can I include preprocessing layers into the model using functional APIs? What would be the functional approach of following sequential model?

model = Sequential([
    Resizing(224, 224),
    Dense(...),
    Dense(...),
    Dense(...),
])

Solution

  • You can define the input layer as the first step, apply the preprocessing layers to the input, and then continue building the rest of the model as usual.

    from tensorflow.keras.layers import Input, Dense, Resizing
    from tensorflow.keras.models import Model
    
    # Define the input layer
    input = Input(shape=(...))  # Specify the input shape
    
    # Preprocessing layers
    x = Resizing(224, 224)(input)
    
    # Rest of the model
    x = Dense(...)(x)
    x = Dense(...)(x)
    output = Dense(...)(x)
    
    # Create the model
    model = Model(inputs=input, outputs=output)