Search code examples
pythonpython-2.7python-3.xnumpyone-hot-encoding

Python Numpy One Hot to Regions


What is the best way to make this One Hot encoded matrix

array([[[1, 0, 0],
        [1, 0, 0],
        [0, 1, 0]],

       [[0, 0, 1],
        [0, 1, 0],
        [1, 0, 0]]])

as

array([[0, 0, 1],
       [2, 1, 0]])

In other words, how to decode One Hot array?


Solution

  • Use np.argmax along axis=2 -

    a.argmax(2)
    

    Sample run -

    In [186]: a
    Out[186]: 
    array([[[1, 0, 0],
            [1, 0, 0],
            [0, 1, 0]],
    
           [[0, 0, 1],
            [0, 1, 0],
            [1, 0, 0]]])
    
    In [187]: a.argmax(2)
    Out[187]: 
    array([[0, 0, 1],
           [2, 1, 0]])