# Unclear about Weighted BCE Loss

**URL:** <https://discuss.pytorch.org/t/unclear-about-weighted-bce-loss/21486>\
**Category:** Uncategorized\
**Created:** [July 21, 2018, 4:30pm UTC](https://discuss.pytorch.org/t/unclear-about-weighted-bce-loss/21486 "2018-07-21T16:30:20Z")\
**Posts on this page:** 1\
**Showing post:** 2

<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:** [July 21, 2018, 8:00pm UTC](https://discuss.pytorch.org/t/unclear-about-weighted-bce-loss/21486/2 "2018-07-21T20:00:46Z")

</div>

If you would like to use the weight as a class weight, I assume you have a binary target, i.e. it contains only zeros and ones.  
In that case I would create a weight tensor and just multiply it with your unreduces loss. Here is a small example:

```python
weight = torch.tensor([0.1, 0.9])
weight_ = weight[y.data.view(-1).long()].view_as(y)
criterion = nn.BCELoss(reduce=False)
loss = criterion(output, y)
loss_class_weighted = loss * weight_
loss_class_weighted = loss_class_weighted.mean()

```

Let me know, if that works for you.

---

_[View the full topic](https://discuss.pytorch.org/t/unclear-about-weighted-bce-loss/21486)._
