Compiles a function into a callable TensorFlow graph.

Used in the notebooks

Used in the guide Used in the tutorials

tf.function constructs a callable that executes a TensorFlow graph (tf.Graph) created by trace-compiling the TensorFlow operations in func, effectively executing func as a TensorFlow graph.

Example usage:

def f(x, y):
  return x ** 2 + y
x = tf.constant([2, 3])
y = tf.constant([3, -2])
f(x, y)
<tf.Tensor: ... numpy=array([7, 7], ...)>


func may use data-dependent control flow, including if, for, while break, continue and return statements:

def f(x):
  if tf.reduce_sum(x) > 0:
    return x * x
    return -x // 2
<tf.Tensor: ... numpy=1>

func's closure may include tf.Tensor and tf.Variable objects:

def f():
  return x ** 2 + y
x = tf.constant([-2, -3])
y = tf.Variable([3, -2])