I'm trying to calculate the gradient within tensorflow, however returning None. I have already adjusted the type to be tensorflow.python.framework.ops.EagerTensor, however htis did not solve the problem.
This is the code so far:
accuracy = tf.keras.metrics.CategoricalAccuracy('accuracy')
loss = tf.keras.metrics.CategoricalCrossentropy('loss')
for epoch in range(epochs):
accuracy.reset_states()
loss.reset_states()
for batch in iterate_minibatches(X_train, y_train, batch_size):
imgs = batch[0]
labels = batch[1]
with tf.GradientTape() as tape:
preds = model(imgs)
labels = tf.convert_to_tensor(labels, dtype=tf.float32)
#print(loss(labels,preds))
# Loss is crossentropy loss with regularization term for each parameter
total_loss = loss(labels, preds) #+l2_penalty(model, theta_A)
grads = tape.gradient(total_loss, model.trainable_variables)
model.optimizer.apply_gradients(zip(grads, model.trainable_variables))
accuracy.update_state(labels, preds)
loss.update_state(labels, preds)
print("\rEpoch: {}, Batch: {}, Loss: {:.3f}, Accuracy: {:.3f}".format(
epoch+1, batch+1, loss.result().numpy(), accuracy.result().numpy()), flush=True, end='')
print("")
print("Task B accuracy after training trained model on Task B: {}".format(model.evaluate(task_B_test)))
print("Task A accuracy after training trained model on Task B: {}".format(model.evaluate(task_A_test)))
does anybody know why it's turning none or how i can fix this?
Edit: My error message looks the following:
AttributeError Traceback (most recent call last) C:\Users\DC5DE~1.ALB\AppData\Local\Temp/ipykernel_13300/818221091.py in 34 grads = tape.gradient(total_loss, model.trainable_variables) 35 ---> 36 model.optimizer.apply_gradients(zip(grads, model.trainable_variables)) 37 38 accuracy.update_state(labels, preds)
AttributeError: 'NoneType' object has no attribute 'apply_gradients'
Since I am not sure if it has to do with how I pass my image data to GradientTape here is my function for the minibatch:
def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
assert inputs.shape[0] == targets.shape[0]
if shuffle:
indices = np.arange(inputs.shape[0])
np.random.shuffle(indices)
for start_idx in range(0, inputs.shape[0] - batchsize + 1, batchsize):
if shuffle:
excerpt = indices[start_idx:start_idx + batchsize]
else:
excerpt = slice(start_idx, start_idx + batchsize)
yield inputs[excerpt], targets[excerpt]
Also: a similar problem was mentioned here, however without any solution that works.