TensorFlow tensors and GradientTape
Quick answer
TensorFlow represents numerical arrays as tensors; mutable trainable state normally lives in tf.Variable. GradientTape records operations to compute derivatives. Keras is a higher-level API and can use TensorFlow, Torch or other supported backends; selecting Torch does not provide TensorFlow APIs. Native TensorFlow examples are unexecuted; local Keras uses Torch. ByteMind execution is unverified.
TensorFlow tape with a watched variable
import tensorflow as tfw=tf.Variable(3.,dtype=tf.float64)with tf.GradientTape() as tape: loss=(2*w-4)**2print(float(tape.gradient(loss,w).numpy()))Expected output (NOT RUN): 8.0. The derivative is 4*(2*w-4). This snippet requires TensorFlow and is not locally executed.
How it works
For batch X of shape (N,D), a dense affine operation X @ W + b uses W of shape (D,H). TensorFlow tensors are immutable; assign to a Variable to update state. A tape automatically watches accessed trainable variables; explicitly watch a plain floating tensor. Compute the loss inside the tape; gradient(loss, variable) gives the derivative or None for a disconnected path. A nonpersistent tape is consumed after one gradient call. Reduce losses explicitly to a scalar, and avoid NumPy conversions inside differentiable TensorFlow calculations. tf.function traces TensorFlow operations; Python side effects may occur during tracing rather than on each execution. Keras ops provide backend-portable arithmetic but not a universal GradientTape. Set KERAS_BACKEND before importing Keras in a fresh process. Here TensorFlow snippets are documentation-grounded, not executed; Keras 3.13.2 uses Torch 2.10.0 CPU for local checks.
Portable tensor arithmetic
import osos.environ["KERAS_BACKEND"]="torch"import kerasfrom keras import opsx=ops.convert_to_tensor([[1.,2.],[3.,4.]])b=ops.convert_to_tensor([10.,20.])print(ops.convert_to_numpy(ops.sum(x+b,axis=0)).tolist())Expected output (locally tested): [24.0, 46.0]. The bias broadcasts across rows before the reduction.
Common mistakes
An integer tensor is not a differentiable real parameter. A None gradient is not the same as a zero derivative. Do not label a Torch-backed Keras result as TensorFlow execution.
Practice and next steps
Compute the gradient of a weighted squared residual by hand, then compare the expected TensorFlow result in a compatible environment. Next, keep aligned features and labels in batches.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TensorFlow tensors and GradientTape — knowledge check
Apply tensorflow tensors and gradienttape to small examples and debugging scenarios.
Which type normally stores mutable trainable state in TensorFlow?
How does a tape watch an ordinary floating tensor?
What is the derivative of (2w-4)^2 at w=3?
What can a disconnected gradient return?
Does Torch-backed Keras execute tf.GradientTape?