Complete the code to define a custom training step function that calculates the loss.
def train_step(model, inputs, targets, loss_fn): with tf.GradientTape() as tape: predictions = model(inputs, training=True) loss = [1](targets, predictions) return loss
Complete the code to compute gradients of the loss with respect to the model's trainable variables.
def train_step(model, inputs, targets, loss_fn, optimizer): with tf.GradientTape() as tape: predictions = model(inputs, training=True) loss = loss_fn(targets, predictions) gradients = tape.[1](loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) return loss
Fix the error in the custom training step by completing the code to update the model weights.
def train_step(model, inputs, targets, loss_fn, optimizer): with tf.GradientTape() as tape: predictions = model(inputs, training=True) loss = loss_fn(targets, predictions) gradients = tape.gradient(loss, model.trainable_variables) [1].apply_gradients(zip(gradients, model.trainable_variables)) return loss
Fill both blanks to complete the custom training step that returns loss and accuracy.
def train_step(model, inputs, targets, loss_fn, optimizer, metric): with tf.GradientTape() as tape: predictions = model(inputs, training=True) loss = loss_fn(targets, predictions) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) metric.[1](targets, predictions) return loss, metric.[2]()
Fill all three blanks to complete a custom training loop that iterates over batches and updates metrics.
for batch, (inputs, targets) in enumerate(dataset): loss = train_step(model, inputs, targets, loss_fn, optimizer) train_loss.[1](loss) train_accuracy.[2](targets, model(inputs, training=True)) if batch % 10 == 0: print(f"Batch {batch}: Loss = {train_loss.[3]():.4f}, Accuracy = {train_accuracy.result():.4f}")
