2

What is the easiest/smartest way of going from a matrix of values to one hot representation of the same thing in 3d tensor? For example if the matrix is the index after argmax in a tensor like:

indices=numpy.argmax(mytensor,axis=2)

Where tensor is 3D [x,y,z] and indices will naturally be [x,y]. Now you want to go to a 3D [x,y,z] tensor that has 1s in the place of maxes in axis=2 and 0 in any other place.

P.S. I know the answer for vector to 1-hot matrix, but this is matrix to 1-hot tensor.

Amir Zadeh
  • 3,481
  • 2
  • 26
  • 47

1 Answers1

3

One of the perfect setups to use broadcasting -

indices[...,None] == np.arange(mytensor.shape[-1])

If you need in ints of 0s and 1s, append with .astype(int)

Divakar
  • 218,885
  • 19
  • 262
  • 358
  • Cool answer! Out of curiosity anything that doesn't use arange? – Amir Zadeh Jan 06 '17 at 19:54
  • @A2B Use `range` instead of `np.arange`? :) What's wrong with using `arange`? Are you looking for a built-in to create such a one-hot array? If so, there's isn't any. – Divakar Jan 06 '17 at 19:55
  • @A2B We can intialize the 3D output array of zeros and then assign values of 1s into it based on `indices`. Would that be *elegant* enough for you? Oh wait, we would still need `np.arange` for that indexing part. – Divakar Jan 06 '17 at 20:01
  • You can't just say same_shape_zero_tensor[matrix]=1. So there has to be another function to turn [i,j]->m into [i,j,m], which is resolving where in the matrix value m resides. – Amir Zadeh Jan 06 '17 at 20:06
  • @A2B Well `indices` are the last axis indices. We just need to generate the indices corresponding to first two axes. For the same, it has to involve range creation explicitly or implicitly. – Divakar Jan 06 '17 at 20:25