Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Best practices to write functions for both execution modes in Tensorflow, eager and graph mode
I regularly run into the problem that I have a Python function that I want to use in both, eager and graph execution mode. I therefore have to adjust the code so that it can handle both situations. Here are two examples:
import tensorflow as tf
def lin_to_db(x: float | tf.Tensor) -> float | tf.Tensor: # convert signal to noise ratio (SNR) from linear to dB if tf.is_tensor(x): return tf.math.log(x) * (10. / tf.math.log(10.)) else: return math.log10(x) * 10.
def cast_to_int_if_eager(x: tf.Variable) -> int | tf.Variable: return int(x) if tf.executing_eagerly() else x
Are there best practices for such functions? Or maybe helpful predefined functions from Tensorflow?