volperossa
volperossa

Reputation: 1431

KERAS error when using VGG preprocess_input in Lambda layers together with Dense and keras.backend.clear_session()

I need to create several models in a loop (so I need to clean the environment with keras.backend.clear_session() for each iteration) but, if the model contains a Lambda with vgg16.preprocess_input and a dense layer, after the second time I create the model i get ValueError: Tensor("PREPROCESS/Const:0", shape=(3,), dtype=float32) must be from the same graph as Tensor("PREPROCESS_1/strided_slice:0", shape=(?, 3), dtype=float32).

Code to reproduce the error:

# making the model
from keras.layers import Dense, Reshape, Lambda
from keras import Sequential
f = keras.applications.vgg16.preprocess_input
d_l = Dense(3, activation='linear', input_shape=(3,), name='MYDENSE')

p_l = Lambda(f,name='PREPROCESS')

model_mod = Sequential()
model_mod.add(d_l)
model_mod.add(p_l)
model_mod.summary()
model_mod.build()
# clean the environment
keras.backend.clear_session()
# making again the same model
f = keras.applications.vgg16.preprocess_input
d_l = Dense(3, activation='linear', input_shape=(3,), name='MYDENSE')
p_l = Lambda(f,name='PREPROCESS')
model_mod = Sequential()
model_mod.add(d_l)
model_mod.add(p_l)

keras version: '2.2.4'

Upvotes: 0

Views: 283

Answers (1)

user11530462
user11530462

Reputation:

The below code works with Tensorflow

# making the model
import tensorflow as tf
from keras.layers import Dense, Reshape, Lambda
from keras import Sequential
f = tf.keras.applications.vgg16.preprocess_input
d_l = Dense(3, activation='linear', input_shape=(3,), name='MYDENSE')

p_l = Lambda(f,name='PREPROCESS')

model_mod = Sequential()
model_mod.add(d_l)
model_mod.add(p_l)
model_mod.summary()
model_mod.build()
# clean the environment
tf.keras.backend.clear_session()
# making again the same model
f = tf.keras.applications.vgg16.preprocess_input
d_l = Dense(3, activation='linear', input_shape=(3,), name='MYDENSE')
p_l = Lambda(f,name='PREPROCESS')
model_mod = Sequential()
model_mod.add(d_l)
model_mod.add(p_l)

Output

Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
MYDENSE (Dense)              (None, 3)                 12        
_________________________________________________________________
PREPROCESS (Lambda)          (None, 3)                 0         
=================================================================
Total params: 12
Trainable params: 12
Non-trainable params: 0

Upvotes: 1

Related Questions