TypeError returned while training

Hello, in the week 3’s graded assignment, a typeError is returned while the training as follows.




I removed the @tf.function decorator for the def train() function in cell 20, and the training goes well as expected. I can not figure out why restoring the decorator will casue error. Would you give me some hints ? Thanks.

@dsfasfuqwjoasjsad As error suggest that it failed to convert the object of type class. So check that the @tf.function is getting the correct arguments.

Hello mentor, I have found where the cause. I am also a bit confused the following code provided in the function def train(). The code is to run the model on the validation set and calculate validation loss.

with tf.device(device_name=device):
       for x, y in valid_ds:
            # Call the model on the batches of inputs x and get the predictions
            y_pred = model(x)
            loss = val_loss(y, y_pred)
            val_accuracy(y, y_pred)

My question is, since x in the loop stands for one batch of inputs from validation set, the loss and val_accuracy calculated in one loop only represent the loss and accuracy for one batch. To get the loss and accuracy for the whole validation set, we should accumulate those values. Would you make any clarification ?

what is the loss you are using?

yes correct you need to accumulate the values of val_loss, val_accuracy and val_accuracy.result()

@dsfasfuqwjoasjsad
but your error is more pointing towards your loss function is not having the class type tf.keras.losses

check in your define loss function code how have you created train_loss and val_loss which you would have to use in def.train

1 Like

Hello mentor, thanks for your reply and clarification. I have found my error is caused by a typo.

2 Likes

it was the tf.keras.losses.SparseCrossentropt() right?

let the learner know what typo error you did and how you corrected. So future learners when get similar error, can get help from your topic.

1 Like