# How to convert labels into one-hot encoded tensors

**URL:** <https://discuss.pytorch.org/t/how-to-convert-labels-into-one-hot-encoded-tensors/49192>\
**Category:** Uncategorized\
**Created:** [June 28, 2019, 5:58am UTC](https://discuss.pytorch.org/t/how-to-convert-labels-into-one-hot-encoded-tensors/49192 "2019-06-28T05:58:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![AmardeepGanguly](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/a/48db29/32.png) [@AmardeepGanguly](https://discuss.pytorch.org/u/AmardeepGanguly)\
**Post date:** [June 28, 2019, 5:58am UTC](https://discuss.pytorch.org/t/how-to-convert-labels-into-one-hot-encoded-tensors/49192/1 "2019-06-28T05:58:44Z")

</div>

I wrote the following code to get the name of the label of every image from a csv file which has the corresponding label for every image In this case the number of labels are three how can i modify my CustomDataset to return one-hot-encoded tensors instead of text labels  
This my code ,i have three labels namely “YOUNG”,“MIDDLE”,“OLD”.

```auto
class CustomDataset(Dataset):
  def __init__ (self, labels_df, img_path, transform=None):
    self.labels_df=labels_df
    self.img_path=img_path
    self.transform=transform
    
  def __len__ (self):
    return len(self.labels_df)
  
  def __getitem__ (self,idx):
    image_name=os.path.join(self.img_path, self.labels_df.ID[idx])
    #img=io.imread(image_name)
    img=Image.open(image_name).convert('RGB')
    label=self.labels_df.Class[idx]
    
    
    
    if self.transform:
      img=self.transform(img)
    return [img, label]  

```

This is how my csv file looks like

 ![csv](https://discuss.pytorch.org/uploads/default/original/2X/3/3a4b923db6bbae5c3cb8cdde0c09a08b52382de2.png)

---

<div class="post-metadata">

**Author:** ![Pranavan\_Theivendira](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/pranavan_theivendira/32/12366_2.png) [@Pranavan\_Theivendira](https://discuss.pytorch.org/u/Pranavan_Theivendira)\
**Post date:** [June 28, 2019, 10:04am UTC](https://discuss.pytorch.org/t/how-to-convert-labels-into-one-hot-encoded-tensors/49192/2 "2019-06-28T10:04:07Z")

</div>

Hi,

This topic has been discussed previously. Have a look at this [thread](https://discuss.pytorch.org/t/convert-int-into-one-hot-format/507/3).
