Python 一种基于NumPy的任意维热编码
给定一个具有任意多个维度的numpy数组,我希望能够对这些维度中的任何一个进行热编码。例如,假设我有一个形状为(10,20,30,40)的数组Python 一种基于NumPy的任意维热编码,python,numpy,one-hot-encoding,Python,Numpy,One Hot Encoding,给定一个具有任意多个维度的numpy数组,我希望能够对这些维度中的任何一个进行热编码。例如,假设我有一个形状为(10,20,30,40)的数组a,我可能想对第二维度进行一次热编码,即变换a,这样结果只包含值0和1,a[I,:,j,k]对于I的每一个选择都只包含一个零条目,j和k(位于沿该尺寸的上一个最大值的位置) 我想先获得a.argmax(axis=1),然后使用np.ogrid将其转化为指向最大值的索引,但我无法理解细节。我还担心这种方法会消耗内存 有没有一种简单的方法可以做到这一点(理想情
a
,我可能想对第二维度进行一次热编码,即变换a
,这样结果只包含值0
和1
,a[I,:,j,k]
对于I
的每一个选择都只包含一个零条目,j
和k
(位于沿该尺寸的上一个最大值的位置)
我想先获得a.argmax(axis=1)
,然后使用np.ogrid
将其转化为指向最大值的索引,但我无法理解细节。我还担心这种方法会消耗内存
有没有一种简单的方法可以做到这一点(理想情况下只需要很少的额外内存)?这里有一种方法可以使用
数组分配
-
def onehotencode_along_axis(a, axis):
# Setup o/p hot encoded bool array
h = np.zeros(a.shape,dtype=bool)
idx = a.argmax(axis=axis)
# Setup same dimensional indexing array as the input
idx = np.expand_dims(idx, axis) # Thanks to @Peter
# Finally assign True values
np.put_along_axis(h,idx,1,axis=axis)
return h
示例在2D
案例中运行-
In [109]: np.random.seed(0)
...: a = np.random.randint(11,99,(4,5))
In [110]: a
Out[110]:
array([[55, 58, 75, 78, 78],
[20, 94, 32, 47, 98],
[81, 23, 69, 76, 50],
[98, 57, 92, 48, 36]])
In [112]: onehotencode_along_axis(a, axis=0)
Out[112]:
array([[False, False, False, True, False],
[False, True, False, False, True],
[False, False, False, False, False],
[ True, False, True, False, False]])
In [113]: onehotencode_along_axis(a, axis=1)
Out[113]:
array([[False, False, False, True, False],
[False, False, False, False, True],
[ True, False, False, False, False],
[ True, False, False, False, False]])
In [114]: np.random.seed(0)
...: a = np.random.randint(11,99,(2,3,4,5,6))
...: for i in range(a.ndim):
...: out = onehotencode_along_axis(a, axis=i)
...: print np.allclose(out.sum(axis=i),1)
True
True
True
True
True
在更高(多维)5D
情况下进行验证的样本运行-
In [109]: np.random.seed(0)
...: a = np.random.randint(11,99,(4,5))
In [110]: a
Out[110]:
array([[55, 58, 75, 78, 78],
[20, 94, 32, 47, 98],
[81, 23, 69, 76, 50],
[98, 57, 92, 48, 36]])
In [112]: onehotencode_along_axis(a, axis=0)
Out[112]:
array([[False, False, False, True, False],
[False, True, False, False, True],
[False, False, False, False, False],
[ True, False, True, False, False]])
In [113]: onehotencode_along_axis(a, axis=1)
Out[113]:
array([[False, False, False, True, False],
[False, False, False, False, True],
[ True, False, False, False, False],
[ True, False, False, False, False]])
In [114]: np.random.seed(0)
...: a = np.random.randint(11,99,(2,3,4,5,6))
...: for i in range(a.ndim):
...: out = onehotencode_along_axis(a, axis=i)
...: print np.allclose(out.sum(axis=i),1)
True
True
True
True
True
如果需要将最终输出作为int
数组和0
s和1
s,请使用布尔输出数组上的视图:
onehotcode\u沿着轴(a,轴=0)。查看('i1')
等等。这就是我要找的。我以前从未见过使用过沿轴放置的,非常整洁。一个建议:你不能用idx=np替换整个idx\u shp
业务。扩展dims(idx,axis)
?@Peter Great建议,谢谢!当然,现在看起来好多了。