-2

Is there a pain free to convert a tensor of integers to a binary tensor with 1 only at that integers index in pytorch?

e.g.

tensor([[1,3,2,6]])

would become

tensor([[0,1,0,0,0,0,0],
        [0,0,0,1,0,0,0],
        [0,0,1,0,0,0,0],
        [0,0,0,0,0,0,1]])

Seraf Fej
  • 209
  • 1
  • 9
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Show me how to solve this coding problem” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. – Prune Jul 08 '21 at 20:32
  • See [How much research?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). Try the phrase "one-hot encoding". – Prune Jul 08 '21 at 20:33

1 Answers1

1
t = tensor([[1,3,2,6]])

rows = t.shape[1]
cols = t.max() + 1

output = torch.zeros(rows, cols) # initializes zeros array of desired dimensions
output[list(range(rows)), t.tolist()] = 1 # sets cells to 1

To clarify the last operation, you can pass in a list of the row numbers and column numbers, and it will set all those elements to the value after the equal. So in our case we want to set the following locations to 1:

(0,1), (1,3), (2,2), (3,6)

Which we'd represent as:

output[[0,1,2,3], [1,3,2,6]] = 1

And you'll see that those lists line up with a) an increasing list up to the total row count, and b) our original tensor

sampocs
  • 11
  • 1