RuntimeError: Attempting to capture an EagerTensor

2020-08-21 06:07发布

问题:

I use tf.data.datset API and use residual network. When I run code for TensorBoard for visualizing my embeddings I have this error, but when I use a two layers network I don't have this problem.

def load_and_preprocess_from_path_label(path, label):
    return load_and_preprocess_image(path), label

ds = tf.data.Dataset.from_tensor_slices((all_image_paths, all_image_labels))
with tf.Session() as sess:
    # TODO (@omoindrot): remove the hard-coded 10000
    # Obtain the test labels
    image_label_ds = ds.map(load_and_preprocess_from_path_label)
    ds = image_label_ds.shuffle(image_count)

RuntimeError                              Traceback (most recent call last)
<ipython-input-41-ead5d6a54baa> in <module>()
     92         # TODO (@omoindrot): remove the hard-coded 10000
     93         # Obtain the test labels
---> 94         image_label_ds = ds.map(load_and_preprocess_from_path_label)
     95         ds = image_label_ds.shuffle(image_count)
     96 
RuntimeError: Attempting to capture an EagerTensor without building a function.

回答1:

Running the following code worked for me:

from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
from keras.callbacks import EarlyStopping
from keras import backend as K
import tensorflow as tf


tf.compat.v1.enable_eager_execution()

It would be great if you use the following code as well to force LSTM clear the model parameters and Graph after creating the models.

K.clear_session()
tf.compat.v1.reset_default_graph()
#tf.compat.v1.disable_eager_execution()


回答2:

The error is possibly due to Tensorflow version

Running the following code worked for me:

import tensorflow.compat.v1 as tf

Correct function:

tf.disable_v2_behavior()