Which of the following best explains why custom training loops offer full control over model training in TensorFlow?
Think about what parts of training you can customize when you write your own loop.
Custom loops let you control every step: how data flows, how loss is computed, and how gradients update the model. This flexibility is why they offer full control.
What will be the printed output after running this TensorFlow custom training loop snippet?
import tensorflow as tf x = tf.constant([[1.0, 2.0]]) y_true = tf.constant([[3.0]]) model = tf.keras.Sequential([tf.keras.layers.Dense(1)]) optimizer = tf.keras.optimizers.SGD(learning_rate=0.1) for epoch in range(1): with tf.GradientTape() as tape: y_pred = model(x) loss = tf.reduce_mean((y_true - y_pred) ** 2) grads = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(grads, model.trainable_variables)) print(f"Loss after epoch {epoch}: {loss.numpy():.4f}")
Calculate the initial prediction and loss before any training updates.
The model starts with random weights, so the initial prediction is near zero. The loss is the squared difference between 3 and ~0, which is about 9, but since the Dense layer has bias and weights initialized randomly, the actual loss is close to 9.
In a TensorFlow custom training loop, which method correctly applies gradients to update model weights?
Focus on how gradients and variables are linked for updates.
In custom loops, gradients are paired with variables and passed to the optimizer's apply_gradients method to update weights.
Which TensorFlow object is best suited to track and update metrics like accuracy during a custom training loop?
Think about which metric measures how often predictions match labels.
tf.keras.metrics.Accuracy() tracks how many predictions equal the true labels, perfect for classification accuracy in custom loops.
What error will this TensorFlow custom training loop code raise?
import tensorflow as tf model = tf.keras.Sequential([tf.keras.layers.Dense(1)]) optimizer = tf.keras.optimizers.Adam() for epoch in range(1): with tf.GradientTape() as tape: y_pred = model(tf.constant([[1.0, 2.0]])) loss = tf.reduce_mean((tf.constant([[3.0]]) - y_pred) ** 2) grads = tape.gradient(loss, model.variables) optimizer.apply_gradients(zip(grads, model.trainable_variables))
Check if the variables passed to gradient calculation match those used in apply_gradients.
Using model.variables instead of model.trainable_variables causes some gradients to be None, leading to a TypeError when applying gradients.
