Force execution of Python function inside Tensorflow graph

Viewed 21

I created a custom layer in Keras, it takes an input, randomly extracts a list of (indexes, values) and substitutes for each index the extracted value. The problem is that if I run the predict function multiple times the list of indexes and values is not generated each time. If I understood correctly it is due to the fact that Tensorflow tracing runs Python code only the first time that a function is invoked. How can I force Tensorflow to generate a new list each time?

The code looks like this, I have to create an object of class CustomClass and then pass it as an argument to an object of AnotherCustomClass in order to generate the list of indexes and values. Unfortunately the code to extract this list was not written by me and I would like to modify it as little as possible

class CustomLayer(tf.keras.layers.Layer):
        def __init__(self):
           super(CustomLayer, self).__init__()
           self.__indexes_values = []
   
        def random_extracts(self):
           custom_class_object = CustomClass(some_params)
           self.__indexes_values = AnotherCustomClass(custom_class_object, other_params)

        def call(self, inputs):
           self.random_extracts()
           output = inputs.copy()
           for index, value in self__indexes_values():
              output[index] = value
           return output

0 Answers
Related