# DLS Course2: Week 3 Exercise 6 (compute\_total\_loss method)

**URL:** <https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856>\
**Category:** Improving Deep Neural Networks: Hyperparameter tun\
**Tags:** coursera-platform\
**Created:** [November 25, 2022, 5:53pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856 "2022-11-25T17:53:15Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![venkatesh4](https://avatars.discourse-cdn.com/v4/letter/v/90db22/32.png) [@venkatesh4](https://dlai.staged-by-discourse.com/u/venkatesh4)\
**Post date:** [November 25, 2022, 5:53pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/1 "2022-11-25T17:53:15Z")

</div>

Hello !

I have been having trouble understanding what I need to do for Exercise 6 of Week 3 (Computing the loss function method: compute\_total\_loss) using tensor flow. I thought I would need to simply invoke the cross entropy tf method, compute the reduce\_sum and return the total loss. Below is the code fragment:

_{moderator edit - solution code removed}_

That didn’t seem to help. Reading thru’ the TF docs, it seemed like the crossentropy function expected the logits to be predictions. Upon inspecting the inputs to the compute\_loss\_function which seemed like plain numbers, I thought I could use the sigmoid or the softmax functions in TF and use the output of that as input to the crossentropy function (like below).

_{moderator edit - solution code removed}_

Neither passing in the softmax or the sigmoid\_output in place of logits seemed to work. I also tried setting the property from\_logits for crossentropy to false/true. But they didn’t seem to help either. I seem to be getting a total\_loss of  
tf.Tensor(0.88275003, shape=(), dtype=float32)

while the expected value is  
tf.Tensor(0.810287, shape=(), dtype=float32)

I am kind of stuck and am not sure how to proceed. Any help would be appreciated.

---

<div class="post-metadata">

**Author:** ![paulinpaloalto](https://sea1.discourse-cdn.com/dlaistaging/user_avatar/dlai.staged-by-discourse.com/paulinpaloalto/32/187_2.png) [@paulinpaloalto](https://dlai.staged-by-discourse.com/u/paulinpaloalto)\
**Post date:** [November 25, 2022, 7:43pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/2 "2022-11-25T19:43:55Z")

</div>

The key point is the fact that the output of layer 3 is the “logits” and not the softmax output. So you need to include softmax in the results. There are (as you say) two ways to do that:

1. Manually add `softmax`.
2. Use `from_logits = True` to include the softmax in the loss calculation.

Option 2) is the preferred method because it’s less code for you to write and more numerically stable.

There is one other thing you didn’t mention here: you also need to transpose the labels and logits to get the correct answer. This was discussed in the instructions.

---

<div class="post-metadata">

**Author:** ![venkatesh4](https://avatars.discourse-cdn.com/v4/letter/v/90db22/32.png) [@venkatesh4](https://dlai.staged-by-discourse.com/u/venkatesh4)\
**Post date:** [November 25, 2022, 8:42pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/3 "2022-11-25T20:42:45Z")

</div>

Thank you so much for the response. I had totally missed the part that I needed to transpose both the labels and the logits. I followed the ideas you had provided and that did it ! Thank you so much!

---

<div class="post-metadata">

**Author:** ![Michael\_Markoe](https://avatars.discourse-cdn.com/v4/letter/m/85e7bf/32.png) [@Michael\_Markoe](https://dlai.staged-by-discourse.com/u/Michael_Markoe)\
**Post date:** [January 8, 2023, 5:10am UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/4 "2023-01-08T05:10:05Z")

</div>

Thanks! @paulinpaloalto I was stuck on this one too.

Seems like a candidate for more than “1 line of code.” To be fair, it could be one line of code; it would just be a long line.

Also on my lab the documentation link points to tf.keras. **metrics**.categorical\_crossentropy while the text says tf.keras. **losses**.categorical\_crossentropy … not sure if that makes any difference though. Seems like metrics is actually the right one to use.

---

<div class="post-metadata">

**Author:** ![paulinpaloalto](https://sea1.discourse-cdn.com/dlaistaging/user_avatar/dlai.staged-by-discourse.com/paulinpaloalto/32/187_2.png) [@paulinpaloalto](https://dlai.staged-by-discourse.com/u/paulinpaloalto)\
**Post date:** [January 8, 2023, 5:43pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/5 "2023-01-08T17:43:26Z")

</div>

As to the number of code lines, that is a programming style point and those are always just suggestions. The grader never looks at your actual code: it just calls your functions and checks the output values. I totally agree that clarity and maintainability may well be better served by more rather than fewer lines, provided that they are appropriately “tasteful”. 😆

On the question of which loss function to use, I think they are just two APIs for the same underlying function. The OOP is getting pretty thick here with more subclasses than you can shake a proverbial stick at. [Here’s the docpage](https://www.tensorflow.org/api_docs/python/tf/keras/losses/CategoricalCrossentropy) for the other one. There is one additional argument provided by the “losses” version, but it’s not anything we care about. Either one should work.

---

<div class="post-metadata">

**Author:** ![Dominic\_Culver](https://avatars.discourse-cdn.com/v4/letter/d/3be4f8/32.png) [@Dominic\_Culver](https://dlai.staged-by-discourse.com/u/Dominic_Culver)\
**Post date:** [January 31, 2023, 5:56pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/6 "2023-01-31T17:56:53Z")

</div>

I tried exactly what you suggested here, and I did not get the correct answer.

In particular, I entered the following,

_{moderator edit - solution code removed}_

Am I misunderstanding something???

---

<div class="post-metadata">

**Author:** ![paulinpaloalto](https://sea1.discourse-cdn.com/dlaistaging/user_avatar/dlai.staged-by-discourse.com/paulinpaloalto/32/187_2.png) [@paulinpaloalto](https://dlai.staged-by-discourse.com/u/paulinpaloalto)\
**Post date:** [January 31, 2023, 6:00pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/7 "2023-01-31T18:00:31Z")

</div>

Where does it say to divide the result by 2? 😀

---

<div class="post-metadata">

**Author:** ![Dominic\_Culver](https://avatars.discourse-cdn.com/v4/letter/d/3be4f8/32.png) [@Dominic\_Culver](https://dlai.staged-by-discourse.com/u/Dominic_Culver)\
**Post date:** [January 31, 2023, 6:01pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/8 "2023-01-31T18:01:16Z")

</div>

I already figured it out…

---

<div class="post-metadata">

**Author:** ![suresh\_selvaraj](https://avatars.discourse-cdn.com/v4/letter/s/e79b87/32.png) [@suresh\_selvaraj](https://dlai.staged-by-discourse.com/u/suresh_selvaraj)\
**Post date:** [February 6, 2023, 8:47pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/9 "2023-02-06T20:47:12Z")

</div>

> [@paulinpaloalto](#):
>
> Manually add `softmax`.

Implement the total loss function below. You will use it to compute the total loss of a batch of samples. With this convenient function, you can sum the losses across many batches, and divide the sum by the total number of samples to get the cost value.

Here, divide the sum by the total number of samples is misleading

---

<div class="post-metadata">

**Author:** ![paulinpaloalto](https://sea1.discourse-cdn.com/dlaistaging/user_avatar/dlai.staged-by-discourse.com/paulinpaloalto/32/187_2.png) [@paulinpaloalto](https://dlai.staged-by-discourse.com/u/paulinpaloalto)\
**Post date:** [February 6, 2023, 8:53pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/10 "2023-02-06T20:53:34Z")

</div>

What they say is correct if you think carefully about what is being said. We only divide by the total number of samples at the end of one full pass of training (all the minibatches). But the function we are writing here is computing the cost for one minibatch, so we only take the sum. The higher level logic will compute the running sum across all the minibatches and then compute the average when it is finished with the pass. You can’t compute the average at the minibatch level, because the math doesn’t work if all the minibatches are not the same size. That will happen if the minibatch size does not evenly divide the total batch size. So you can’t get the overall average by taking the average of the averages.

If you were paying close attention, this is exactly how it worked when we first implemented minibatch gradient descent in the previous assignment (C2 W2 A1 Optimization). It’s the same here, but now we’re doing it in TF instead of straight numpy.

---

<div class="post-metadata">

**Author:** ![someone555777](https://avatars.discourse-cdn.com/v4/letter/s/67e7ee/32.png) [@someone555777](https://dlai.staged-by-discourse.com/u/someone555777)\
**Post date:** [May 10, 2023, 7:12pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/11 "2023-05-10T19:12:20Z")

</div>

and why should I know to that place about existing of tf.transpose() method? I didn’t see it in instruction in previous times.

---

<div class="post-metadata">

**Author:** ![paulinpaloalto](https://sea1.discourse-cdn.com/dlaistaging/user_avatar/dlai.staged-by-discourse.com/paulinpaloalto/32/187_2.png) [@paulinpaloalto](https://dlai.staged-by-discourse.com/u/paulinpaloalto)\
**Post date:** [May 10, 2023, 7:21pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/12 "2023-05-10T19:21:48Z")

</div>

Because the dimensions of the output of the forward propagation are `features` x `samples` and the TF loss function requires the orientation with samples as the first dimension. They do mention in the instructions that you need to be aware of that. It’s also never a bad idea to read the documentation for the TF functions they are advising you to use. This is the intro to TF so there is a lot to learn.

[Here’s an earlier thread](http://dlai.staged-by-discourse.com/t/course-2-week-3-compute-total-loss-logits-labels/293215/4) that discusses this same point.

---

<div class="post-metadata">

**Author:** ![someone555777](https://avatars.discourse-cdn.com/v4/letter/s/67e7ee/32.png) [@someone555777](https://dlai.staged-by-discourse.com/u/someone555777)\
**Post date:** [May 10, 2023, 7:27pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/13 "2023-05-10T19:27:10Z")

</div>

it would be nice to see information about tf.transpose() method in instructioin of this exercise

---

<div class="post-metadata">

**Author:** ![paulinpaloalto](https://sea1.discourse-cdn.com/dlaistaging/user_avatar/dlai.staged-by-discourse.com/paulinpaloalto/32/187_2.png) [@paulinpaloalto](https://dlai.staged-by-discourse.com/u/paulinpaloalto)\
**Post date:** [May 10, 2023, 7:46pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/14 "2023-05-10T19:46:19Z")

</div>

Sure, since this is the very first assignment using TF, it would be nice for them to mention it or show an example. But you know that you need a transpose operation and you’re using TF, so try googling “how do I transpose a tensor in TF”. We can thank google for search and for creating TF.

I’ll file an enhancement request asking that they should at least say something like “Hint: you will need the `tf.transpose` function for this purpose” in the section of the instructions where they mention the dimension issue.

---

<div class="post-metadata">

**Author:** ![jbloom](https://avatars.discourse-cdn.com/v4/letter/j/f1d935/32.png) [@jbloom](https://dlai.staged-by-discourse.com/u/jbloom)\
**Post date:** [November 2, 2023, 6:21pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/15 "2023-11-02T18:21:12Z")

</div>

I got stuck here too. Thanks for posting this.

For anyone else stuck: The first bullet in Exercise 6 is key: “[inputs of categorical\_crossentropy] are expected to be of shape (number of examples, num\_classes).”

For feedback: It helps some of the earlier code uses tf.transpose, but I agree that the rest of the assignment and other assignments are usually much more clear about what to do. Perhaps add to this bullet "you can use tf.transpose() if you need it)?

PS: great class, this is just a nit

---

<div class="post-metadata">

**Author:** ![paulinpaloalto](https://sea1.discourse-cdn.com/dlaistaging/user_avatar/dlai.staged-by-discourse.com/paulinpaloalto/32/187_2.png) [@paulinpaloalto](https://dlai.staged-by-discourse.com/u/paulinpaloalto)\
**Post date:** [July 31, 2024, 3:22pm UTC](https://dlai.staged-by-discourse.com/t/dls-course2-week-3-exercise-6-compute-total-loss-method/234856/16 "2024-07-31T15:22:47Z")

</div>

Closed on July 31, 2024, 3:22pm UTC


