简体   繁体   中英

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

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.

You should use model.trainable_variables .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM