Project 29: Discount Layer Gradient Demo
ML Engineer
Current Task
Objective
Review day: combine a custom layer and GradientTape — days 10 and 6 — to compute a gradient through custom computation.
Task: write a DiscountLayer, apply it inside a GradientTape, and print the gradient of the total with respect to the input.
index.py
import tensorflow as tf
from tensorflow.keras import layers
class DiscountLayer(layers.Layer):
def call(self, inputs):
return inputs * 0.9
x = tf.Variable([100.0, 200.0])
layer = DiscountLayer()
with tf.GradientTape() as tape:
discounted = layer(x)
total = tf.reduce_sum(discounted)
grad = tape.gradient(total, x)
print(grad.numpy())
* Hint: Correct characters turn green, incorrect ones turn red.
Live Preview
🖼️
Verify your code to see the preview