简体   繁体   中英

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

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!

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])

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