将单热编码目标值映射到正确的标签名称

Moo*_*dra 2 mapping numpy machine-learning python-3.x one-hot-encoding

我有一个标签名称列表,我对其进行了枚举并创建了一个字典:

my_list = [b'airplane',
 b'automobile',
 b'bird',
 b'cat',
 b'deer',
 b'dog',
 b'frog',
 b'horse',
 b'ship',
 b'truck']

label_dict =dict(enumerate(my_list))


{0: b'airplane',
 1: b'automobile',
 2: b'bird',
 3: b'cat',
 4: b'deer',
 5: b'dog',
 6: b'frog',
 7: b'horse',
 8: b'ship',
 9: b'truck'}
Run Code Online (Sandbox Code Playgroud)

现在,我试图清理map/apply在字典值我的目标是在独热编码形式。

y_test[0]

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


y_test[0].map(label_dict) should return: 
'cat'
Run Code Online (Sandbox Code Playgroud)

我在玩

(lambda key,value: value for y_test[0] == 1)
Run Code Online (Sandbox Code Playgroud)

但无法想出任何具体的

谢谢你。

Div*_*kar 5

由于我们正在使用one-hot encoded数组,argmax因此可用于获取1每一行的索引。因此,使用列表作为输入 -

[my_list[i] for i in y_test.argmax(1)]
Run Code Online (Sandbox Code Playgroud)

或者np.take有数组输出 -

np.take(my_list,y_test.argmax(1))
Run Code Online (Sandbox Code Playgroud)

要使用dict并假设顺序键为0,1,..,我们可以 -

np.take(label_dict.values(),y_test.argmax(1))
Run Code Online (Sandbox Code Playgroud)

如果键基本上不是按顺序而是排序的 -

np.take(label_dict.values(), np.searchsorted(label_dict.keys(),y_test.argmax(1)))
Run Code Online (Sandbox Code Playgroud)

样品运行 -

In [79]: my_list
Out[79]: 
['airplane',
 'automobile',
 'bird',
 'cat',
 'deer',
 'dog',
 'frog',
 'horse',
 'ship',
 'truck']

In [80]: y_test
Out[80]: 
array([[ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.]])

In [81]: [my_list[i] for i in y_test.argmax(1)]
Out[81]: ['cat', 'automobile', 'ship']

In [82]: np.take(my_list,y_test.argmax(1))
Out[82]: 
array(['cat', 'automobile', 'ship'], 
      dtype='|S10')
Run Code Online (Sandbox Code Playgroud)