Home > Back-end >  how to solve input tensor error in adopting pre-trained keras models
how to solve input tensor error in adopting pre-trained keras models

Time:11-02

I am trying to adopt a pre-trained keras model as follow, but it requires an input to be a tensor. can anyone help to solve it?

from keras.applications.vgg19 import VGG19
inputs = layers.Input(shape = (32,32,4))

vgg_model = VGG19(weights='imagenet', include_top=False)
vgg_model.trainable = False

x = tensorflow.keras.layers.Flatten(name='flatten')(vgg_model)
x = tensorflow.keras.layers.Dense(512, activation='relu', name='fc1')(x)
x = tensorflow.keras.layers.Dense(512, activation='relu', name='fc2')(x)
x = tensorflow.keras.layers.Dense(1,name='predictions')(x)
new_model = tensorflow.keras.models.Model(inputs=inputs, outputs=x)
new_model.compile(optimizer='adam', loss='mean_squared_error', 
                   metrics=['mae'])

error:

TypeError: Inputs to a layer should be tensors. Got: <keras.engine.functional.Functional object at 0x000001F48267B588>

CodePudding user response:

If you want to use the VGG19 as your base model, you will have to use its output as the input to your custom model:

import tensorflow as tf
from keras.applications.vgg19 import VGG19


vgg_model = VGG19(weights='imagenet', include_top=False, input_shape=(32, 32, 3))
vgg_model.trainable = False

x = vgg_model.output
x = tf.keras.layers.Dense(512, activation='relu', name='fc1')(x)
x = tf.keras.layers.Dense(512, activation='relu', name='fc2')(x)
x = tf.keras.layers.Dense(1, name='predictions')(x)
new_model = tf.keras.Model(inputs=vgg_model.input, outputs=x)
new_model.compile(optimizer='adam', loss='mean_squared_error', 
                   metrics=['mae'])

new_model(tf.random.normal((1, 32, 32, 3)))

Note that I removed your Flatten layer, since the output from the vgg_model already has the shape (batch_size, features).

  • Related