将2d矩阵转换为3d一个热矩阵numpy

时间:2016-04-30 21:15:16

标签: python numpy vectorization one-hot-encoding

我有np矩阵,我想将其转换为3d数组,其中元素的热编码为第三维。有没有办法处理没有循环每一行 例如

a=[[1,3],
   [2,4]]

应该变成

b=[[1,0,0,0], [0,0,1,0],
   [0,1,0,0], [0,0,0,1]]

4 个答案:

答案 0 :(得分:29)

方法#1

这是一个厚颜无耻的单行,滥用broadcasted比较 -

(np.arange(a.max()) == a[...,None]-1).astype(int)

示例运行 -

In [120]: a
Out[120]: 
array([[1, 7, 5, 3],
       [2, 4, 1, 4]])

In [121]: (np.arange(a.max()) == a[...,None]-1).astype(int)
Out[121]: 
array([[[1, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 1],
        [0, 0, 0, 0, 1, 0, 0],
        [0, 0, 1, 0, 0, 0, 0]],

       [[0, 1, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0],
        [1, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0]]])

对于0-based索引,它将是 -

In [122]: (np.arange(a.max()+1) == a[...,None]).astype(int)
Out[122]: 
array([[[0, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 1],
        [0, 0, 0, 0, 0, 1, 0, 0],
        [0, 0, 0, 1, 0, 0, 0, 0]],

       [[0, 0, 1, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 0, 0, 0],
        [0, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 0, 0, 0]]])

如果one-hot enconding将覆盖范围从最小值到最大值的值范围,则偏移最小值,然后将其提供给建议的0-based索引方法。这也适用于本文后面讨论的其他方法。

这是一个同样的例子 -

In [223]: a
Out[223]: 
array([[ 6, 12, 10,  8],
       [ 7,  9,  6,  9]])

In [224]: a_off = a - a.min() # feed a_off to proposed approaches

In [225]: (np.arange(a_off.max()+1) == a_off[...,None]).astype(int)
Out[225]: 
array([[[1, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 1],
        [0, 0, 0, 0, 1, 0, 0],
        [0, 0, 1, 0, 0, 0, 0]],

       [[0, 1, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0],
        [1, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0]]])

如果您对True的{​​{1}}和1's的{​​0}}的布尔数组没问题,可以跳过0's转换。

方法#2

我们还可以使用advanced-indexing初始化零数组并将索引编入输出。因此,对于.astype(int)索引,我们会有 -

0-based

助手功能 -

def onehot_initialization(a):
    ncols = a.max()+1
    out = np.zeros(a.shape + (ncols,), dtype=int)
    out[all_idx(a, axis=2)] = 1
    return out

在处理更大范围的值时,这应该更加高效。

对于# https://stackoverflow.com/a/46103129/ @Divakar def all_idx(idx, axis): grid = np.ogrid[tuple(map(slice, idx.shape))] grid.insert(axis, idx) return tuple(grid) 索引,只需输入1-based作为输入。

方法#3:稀疏矩阵解决方案

现在,如果您正在寻找稀疏数组作为输出和AFAIK,因为scipy的内置稀疏矩阵仅支持a-1格式,您可以获得稀疏输出,这是前面显示的输出的重新整形版本前两个轴合并,第三个轴保持不变。 2D索引的实现看起来像这样 -

0-based

同样,对于from scipy.sparse import coo_matrix def onehot_sparse(a): N = a.size L = a.max()+1 data = np.ones(N,dtype=int) return coo_matrix((data,(np.arange(N),a.ravel())), shape=(N,L)) 索引,只需输入1-based作为输入。

示例运行 -

a-1

如果您可以使用稀疏输出,那么这比前两种方法要好得多。

基于0的索引的运行时比较

案例#1:

In [157]: a
Out[157]: 
array([[1, 7, 5, 3],
       [2, 4, 1, 4]])

In [158]: onehot_sparse(a).toarray()
Out[158]: 
array([[0, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0]])

In [159]: onehot_sparse(a-1).toarray()
Out[159]: 
array([[1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0]])

案例#2:

In [160]: a = np.random.randint(0,100,(100,100))

In [161]: %timeit (np.arange(a.max()+1) == a[...,None]).astype(int)
1000 loops, best of 3: 1.51 ms per loop

In [162]: %timeit onehot_initialization(a)
1000 loops, best of 3: 478 µs per loop

In [163]: %timeit onehot_sparse(a)
10000 loops, best of 3: 87.5 µs per loop

In [164]: %timeit onehot_sparse(a).toarray()
1000 loops, best of 3: 530 µs per loop

挤出最佳表现

为了挤出最佳性能,我们可以修改方法#2以在In [166]: a = np.random.randint(0,500,(100,100)) In [167]: %timeit (np.arange(a.max()+1) == a[...,None]).astype(int) 100 loops, best of 3: 8.51 ms per loop In [168]: %timeit onehot_initialization(a) 100 loops, best of 3: 2.52 ms per loop In [169]: %timeit onehot_sparse(a) 10000 loops, best of 3: 87.1 µs per loop In [170]: %timeit onehot_sparse(a).toarray() 100 loops, best of 3: 2.67 ms per loop 形状的输出数组上使用索引,并使用2D dtype来提高内存效率,从而实现更快的分配,例如所以 -

uint8

计时 -

def onehot_initialization_v2(a):
    ncols = a.max()+1
    out = np.zeros( (a.size,ncols), dtype=np.uint8)
    out[np.arange(a.size),a.ravel()] = 1
    out.shape = a.shape + (ncols,)
    return out

答案 1 :(得分:0)

编辑:我刚刚意识到我的答案已经包含在接受的答案中。不幸的是,作为一个未注册用户,我无法再将其删除。

作为已接受答案的补充:如果您要编码的类非常少,并且可以接受np.bool数组作为输出,我发现以下内容会更快:

def onehot_initialization_v3(a):
    ncols = a.max() + 1
    labels_one_hot = (a.ravel()[np.newaxis] == np.arange(ncols)[:, np.newaxis]).T
    labels_one_hot.shape = a.shape + (ncols,)
    return labels_one_hot

时间(十节课):

a = np.random.randint(0,10,(100,100))
assert np.all(onehot_initialization_v2(a) == onehot_initialization_v3(a))
%timeit onehot_initialization_v2(a)
%timeit onehot_initialization_v3(a)

# 102 µs ± 1.66 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
# 79.3 µs ± 815 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

但是,如果班级数量增加(现在为100个班级),则情况会发生变化:

a = np.random.randint(0,100,(100,100))
assert np.all(onehot_initialization_v2(a) == one_hot_initialization_v3(a))
%timeit onehot_initialization_v2(a)
%timeit onehot_initialization_v3(a)

# 132 µs ± 1.4 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
# 639 µs ± 3.12 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

因此,根据您的问题,可能是更快的版本。

答案 2 :(得分:0)

如果您尝试为机器学习模型(安装了tensorflowkeras)创建单张量张量,则可以使用https://www.tensorflow.org/api_docs/python/tf/keras/backend/one_hot中的one_hot函数或https://www.tensorflow.org/api_docs/python/tf/one_hot

这就是我正在使用的并且对于高维数据很好地工作。

这里是示例用法:

>>> import tensorflow as tf

>>> tf.one_hot([[0,2],[1,3]], 4).numpy()
array([[[1., 0., 0., 0.],
        [0., 0., 1., 0.]],

       [[0., 1., 0., 0.],
        [0., 0., 0., 1.]]], dtype=float32)

答案 3 :(得分:0)

这是使用 np.eye(身份矩阵)和 numpy 强大索引的最简单和最优雅的解决方案:

labels_3d = np.eye(N_CLASSES)[labels_2d]

enter image description here

相关问题