【问题标题】:Mapping one-hot encoded target values to proper label names将 one-hot 编码的目标值映射到正确的标签名称
【发布时间】:2017-11-11 20:30:36
【问题描述】:

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

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'}

现在我正在尝试将 map/apply 的 dict 值清理到我的目标中,该目标采用单热编码形式。

y_test[0]

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


y_test[0].map(label_dict) should return: 
'cat'

我在玩

(lambda key,value: value for y_test[0] == 1)

但无法提出任何具体的建议

谢谢。

【问题讨论】:

    标签: python-3.x numpy machine-learning mapping one-hot-encoding


    【解决方案1】:

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

    [my_list[i] for i in y_test.argmax(1)]
    

    或使用np.take 来获得数组输出 -

    np.take(my_list,y_test.argmax(1))
    

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

    np.take(label_dict.values(),y_test.argmax(1))
    

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

    np.take(label_dict.values(), np.searchsorted(label_dict.keys(),y_test.argmax(1)))
    

    示例运行 -

    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')
    

    【讨论】:

      【解决方案2】:

      如果真的是ONE-hot,我们可以使用点积来反转one-hot编码。

      让我们从分解列表开始

      f, u = pd.factorize(my_list)
      

      现在,如果你有一个数组,你想用它来取回你的字符串

      a = np.array([0, 0, 0, 1, 0, 0, 0, 0, 0, 0])
      

      然后使用dot

      a.dot(u)
      
      'cat'
      

      现在假设

      y_test = np.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]
          ])
      

      然后

      y_test.dot(u)
      
      array(['cat', 'automobile', 'ship'], dtype=object)
      

      如果不是 one-hot 而是 multi-hot,你可以用逗号加入

      y_test = np.array([
              [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
              [0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
              [0, 0, 1, 0, 0, 0, 0, 0, 1, 0]
          ])
      
      [', '.join(u[y.astype(bool)]) for y in y_test]
      
      
      ['cat', 'automobile, truck', 'bird, ship']
      

      【讨论】:

        猜你喜欢
        • 2018-05-09
        • 2021-08-05
        • 1970-01-01
        • 2020-11-04
        • 2020-07-18
        • 2021-12-13
        • 2020-10-08
        • 2017-07-27
        相关资源
        最近更新 更多