# Mask for CrossEntropyLoss2d

**URL:** <https://discuss.pytorch.org/t/mask-for-crossentropyloss2d/9559>\
**Category:** Uncategorized\
**Created:** [November 6, 2017, 1:17am UTC](https://discuss.pytorch.org/t/mask-for-crossentropyloss2d/9559 "2017-11-06T01:17:01Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![foxet](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/f/d9b06d/32.png) [@foxet](https://discuss.pytorch.org/u/foxet)\
**Post date:** [November 6, 2017, 1:17am UTC](https://discuss.pytorch.org/t/mask-for-crossentropyloss2d/9559/1 "2017-11-06T01:17:01Z")

</div>

is it possible to only calculate the loss within mask area?

---

<div class="post-metadata">

**Author:** ![SimonW](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/simonw/32/1702_2.png) [@SimonW](https://discuss.pytorch.org/u/SimonW)\
**Post date:** [November 6, 2017, 1:29am UTC](https://discuss.pytorch.org/t/mask-for-crossentropyloss2d/9559/2 "2017-11-06T01:29:02Z")

</div>

You can process the output a bit or write your own loss function to do that.

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [November 7, 2017, 10:02am UTC](https://discuss.pytorch.org/t/mask-for-crossentropyloss2d/9559/3 "2017-11-07T10:02:58Z")

</div>

I implemented a weighted NLLLoss2d in [this thread](https://discuss.pytorch.org/t/weighted-pixelwise-nllloss2d/7766?u=ptrblck). Maybe you could use it by setting your weights accordingly to 0 and 1. 🙂

---

<div class="post-metadata">

**Author:** ![alexis-jacq](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/alexis-jacq/32/180_2.png) [@alexis-jacq](https://discuss.pytorch.org/u/alexis-jacq)\
**Post date:** [November 7, 2017, 10:38am UTC](https://discuss.pytorch.org/t/mask-for-crossentropyloss2d/9559/4 "2017-11-07T10:38:07Z")

</div>

Why don’t you:

```python
loss = nn.CrossEntropyLoss2d(output[mask>0], target[mask>0])

```

?
