How to get trainable variables of keras model in eager execution mode?

Viewed 655

I'm using tensorflow 1.15.0.

I build my own model with tf.keras. But when I trying to save my model with Saver:

saver = tf.compat.v1.train.Saver(var_list=tf.trainable_variables())

I find that tf.trainable_variables() will always return empty list in eager execution mode.

Here is a simple code sample:

import numpy as np
import tensorflow as tf
from tensorflow import keras

tf.enable_eager_execution()

def create_model():
    inlayer = keras.Input(shape=(10), name="input")
    outlayer = keras.layers.Dense(1, activation='relu')(inlayer)
    
    model = keras.Model(
        inputs=inlayer,
        outputs=outlayer,
    )
    
    optimizer = tf.keras.optimizers.Adam(0.0001)
           
    model.compile(optimizer=optimizer,
                  loss='mae') 
    return model

model = create_model()

history = model.fit(np.zeros((1, 10)), np.zeros((1, 10)), epochs=1)

tf.trainable_variables()

Output is [].

Could someone please tell me why this happens and how could I get trainable_variables for a keras model?

Thanks.

1 Answers

You should use model.trainable_variables.

Related