Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

np_utils.to_categorical Reverse

import numpy as np
from keras.utils import np_utils
nsample = 100
sample_space = ["HOME","DRAW","AWAY"]
array = np.random.choice(sample_space, nsample, )
uniques, coded_id = np.unique(array, return_inverse=True)
coded_array = np_utils.to_categorical(coded_id)

Example

Input

 ['AWAY', 'HOME', 'DRAW', 'AWAY', ...]

Output coded_array

[[ 0.  1.  0.]
 [ 0.  0.  1.]
 [ 0.  0.  1.]
 ..., 
 [ 0.  0.  1.]
 [ 0.  0.  1.]
 [ 1.  0.  0.]]

How to reverse process and get the original data from coded_array?

like image 834
Ken Ho Avatar asked Aug 09 '16 07:08

Ken Ho


1 Answers

You can use np.argmax to retrieve back those ids and then simply indexing into uniques should give you the original array. Thus, we would have an implementation, like so -

uniques[y_code.argmax(1)]

Sample run -

In [44]: arr
Out[44]: array([5, 7, 3, 2, 4, 3, 7])

In [45]: uniques, ids = np.unique(arr, return_inverse=True)

In [46]: y_code = np_utils.to_categorical(ids, len(uniques))

In [47]: uniques[y_code.argmax(1)]
Out[47]: array([5, 7, 3, 2, 4, 3, 7])
like image 90
Divakar Avatar answered Oct 15 '22 00:10

Divakar