# Convert int into one-hot format

**URL:** <https://discuss.pytorch.org/t/convert-int-into-one-hot-format/507>\
**Category:** Uncategorized\
**Created:** [February 15, 2017, 7:52am UTC](https://discuss.pytorch.org/t/convert-int-into-one-hot-format/507 "2017-02-15T07:52:08Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![albanD](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/alband/32/215_2.png) [@albanD](https://discuss.pytorch.org/u/albanD)\
**Post date:** [February 15, 2017, 10:58am UTC](https://discuss.pytorch.org/t/convert-int-into-one-hot-format/507/4 "2017-02-15T10:58:55Z")

</div>

Hi,

You can use the `scatter_` method to achieve this.  
I would also advise to create the `y_onehot` tensor once and then just fill it:

```auto
import torch

batch_size = 5
nb_digits = 10
# Dummy input that HAS to be 2D for the scatter (you can use view(-1,1) if needed)
y = torch.LongTensor(batch_size,1).random_() % nb_digits
# One hot encoding buffer that you create out of the loop and just keep reusing
y_onehot = torch.FloatTensor(batch_size, nb_digits)

# In your for loop
y_onehot.zero_()
y_onehot.scatter_(1, y, 1)

print(y)
print(y_onehot)

```

---

_[View the full topic](https://discuss.pytorch.org/t/convert-int-into-one-hot-format/507)._
