Numpy thermometer encoding

后端 未结 4 1613
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 00:28

I am trying to use numpy optimized in-built functions to generate thermometer encoding. Thermometer encoding is basically generating n amount if 1\'s in a given len

4条回答
  •  一整个雨季
    2021-01-06 00:43

    Wim's answer is incredible. I also never heard of thermometer encoding, but if I were to do I would go with map. It's simply shorter without for loop solution. The performance is quite similar.

    >>> def setValue(val):
          return np.append(np.ones(val), np.zeros(8-val))
    >>> np.array(list(map(setValue, [2,3,4,5])))
    
    array([[ 1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  0.,  0.,  0.]])
    

    or one-liner with lambda function

    >>> np.array(list(map(lambda v: np.append(np.ones(v), np.zeros(8-v)), [1,6,3,8])))
    
    array([[ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]])
    

提交回复
热议问题