Overcoming incompatibilities between tensorflow 1.x and 2.x when trying to view layer activity with backend

Viewed 67

I would like to run newer tensorflow routines like:

    from tensorflow.keras.preprocessing import image_dataset_from_directory

for which I get error in 1.x:

ImportError: cannot import name image_dataset_from_directory

while preserving older functionality of 1.x like running the routine to see activations in various layers like:

    K=tf.keras.backend
    func = K.function([base_model.input, K.learning_phase()],[layer.output for layer in base_model.layers if layer.output is not base_model.input]) 

for which I get the following error in tf 2.x:

ValueError: Input tensors to a Functional must come from tf.keras.Input. Received: 0 (missing previous layer metadata).

The code:

    import tensorflow as tf
    from tensorflow.keras.preprocessing import image_dataset_from_directory

    IMG_SHAPE = (160, 160) + (3,)
    base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,
                                                   include_top=False,
                                                   weights='imagenet')

    K=tf.keras.backend
    func = K.function([base_model.input, K.learning_phase()],[layer.output for layer in base_model.layers if layer.output is not base_model.input])

The documentation I looked at suggests the problem may have something to do with eager computation mode eg https://github.com/tensorflow/tensorflow/issues/34201

But I cannot figure out how to resolve this. Thank you for suggestions!

1 Answers

As suggested #34201, Just disable the eager execution and run the rest of your code

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
from tensorflow.keras.preprocessing import image_dataset_from_directory

IMG_SHAPE = (160, 160) + (3,)
base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,
                                                   include_top=False,
                                                   weights='imagenet')

K=tf.keras.backend
func = K.function([base_model.input, K.learning_phase()],[layer.output for layer in base_model.layers if layer.output is not base_model.input])
Related