I'd like to calculate the error gradient: dJ/dredictionp
(if J
is the cost function). In the function train_step()
you can see that the gradients are calculated wrt the model weights.
When I tried to calculate the gradients like: gradients = tape.gradient(loss, predictions)
, it returned None
which would mean that my loss function is not dependent on the predictions.
How can that be?
class SimpleModel(models.Model):
def __init__(self, nb_classes, X_dim: int, batch_size: int):
super().__init__()
self.model_input_layer = layers.InputLayer(input_shape=(X_dim,), batch_size=batch_size)
self.d1 = layers.Dense(64, name="d1")
self.a1 = layers.Activation("relu", name="a1")
self.d2 = layers.Dense(32, name="d2")
self.a2 = layers.Activation("relu", name="a2")
self.d3 = layers.Dense(nb_classes, name="d3")
self.a3 = layers.Activation("softmax", name="a3")
self.model_input = None
self.d1_output = None
self.a1_output = None
self.d2_output = None
self.a2_output = None
self.d3_output = None
self.a3_output = None
def call(self, inputs, training=None, mask=None):
self.model_input = self.model_input_layer(inputs)
self.d1_output = self.d1(self.model_input)
self.a1_output = self.a1(self.d1_output)
self.d2_output = self.d2(self.a1_output)
self.a2_output = self.a2(self.d2_output)
self.d3_output = self.d3(self.a2_output)
self.a3_output = self.a3(self.d3_output)
return self.a3_output
model = SimpleModel(NB_CLASSES, X_DIM, BATCH_SIZE)
model.build((BATCH_SIZE, X_DIM))
optimizer = Adam()
loss_object = losses.CategoricalCrossentropy()
train_loss = metrics.Mean(name='train_loss')
test_loss = metrics.Mean(name='test_loss')
@tf.function
def train_step(X, y):
with tf.GradientTape() as tape:
predictions = model(X)
loss = loss_object(y, predictions)
gradients = tape.gradient(loss, model.trainable_weights)
optimizer.apply_gradients(zip(gradients, model.trainable_weights))
train_loss(loss)
The issue is that GradientTape
by default only tracks trainable variables, and no other tensors. Thus you need to explicitly tell it to track the tensor of interest. Try this:
predictions = model(X) # if you also need gradients for model variables, move this back into the tape context
with tf.GradientTape() as tape:
tape.watch(predictions)
loss = loss_object(y, predictions)
gradients = tape.gradient(loss, [predictions])
Note the use of the watch
method to track arbitrary tensors. This should not return None
anymore.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.