Search code examples
pythonlistdeep-learningpytorchone-hot-encoding

Mapping a list of label with one hot encoding


How can I do the same thing when 'label' is a list? For example: label = [2,4,6,1,7...,9]

label = 3
NumClass = 10
NumRows  = 100

mask    =  torch.zeros(100, 64)
ones     =  torch.ones(1, 64)
ElementsPerClass = NumRows//NumClass
mask [ ElementsPerClass*label : ElementsPerClass*(label+1) ] = ones

Solution

  • You are looking for scatter:

    NumRows = len(label)
    mask = torch.zeros((NumRoes, NumClass)).scatter_(dim=1, index=torch.tensor(label, dtype=torch.long)[:, None], src=torch.ones(NumRows, 1))