Np_utils.to_categorical Reverse

from keras.utils import np_utils uniques, ids = np.unique(arr, return_inverse=True) coded_array = np_utils.to_categorical(ids, len(uniques)) encode_dict ={} for i,j in zip(arr,coded_array): encode_dict[i] = j if len(encode_dict)==len(np.unique(arr)): break return coded_array,encode_dict 

Example

Matching dictionary

 {{'HOME': array([ 0., 0., 1.]), 'DRAW': array([ 0., 1., 0.]), 'AWAY': array([ 1., 0., 0.])} 

Enter

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

Coded output

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

How to cancel this function and get the decoding function?

+6
source share
1 answer

You can use np.argmax to return their ids , and then just indexing in uniques should give you the original array. Thus, we would have an implementation, for example:

 uniques[y_code.argmax(1)] 

Run Example -

 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]) 
+6
source

All Articles