一键热编码numpy数组,具有> 2个暗角

问题描述

我有一个形状为(192,224,192,1)的数字数组。最后一个维度是我要热编码的整数类。例如,如果我有12个类,我希望结果数组的of为(192,12),最后一个维全为零,但索引处的1对应于原始值。

我可以天真地使用许多for循环来执行此操作,但想知道是否有更好的方法可以执行此操作。

解决方法

您可以创建一个新的零点数组,并使用高级索引对其进行填充。

# sample array with 12 classes
np.random.seed(123)
a = np.random.randint(0,12,(192,224,192,1))

b = np.zeros((a.size,a.max() + 1))

# use advanced indexing to get one-hot encoding
b[np.arange(a.size),a.ravel()] = 1

# reshape to original form
b = b.reshape(a.shape[:-1] + (a.max() + 1,))

print(b.shape)
print(a[0,0])
print(b[0,0])

输出

(192,12)
[2]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

类似于this answer,但具有数组重塑的功能。

,

如果知道最大值,则可以在单个索引操作中执行此操作。给定数组am = a.max() + 1

out = np.zeros(a.shape[:-1] + (m,),dtype=bool)
out[(*np.indices(a.shape[:-1],sparse=True),a[...,0])] = True

如果删除不必要的尾随尺寸,会更容易:

a = np.squeeze(a)
out = np.zeros(a.shape + (m,bool)
out[(*np.indices(a.shape,a)] = True

索引中的显式元组是进行恒星扩展所必需的。

如果要将其扩展到任意尺寸,也可以这样做。下面将在axis的压缩数组中插入一个新维度。这里的axis是新轴的最终数组中的位置,与np.stack一致,但与list.insert不一致:

def onehot(a,axis=-1,dtype=bool):
    pos = axis if axis >= 0 else a.ndim + axis + 1
    shape = list(a.shape)
    shape.insert(pos,a.max() + 1)
    out = np.zeros(shape,dtype)
    ind = list(np.indices(a.shape,sparse=True))
    ind.insert(pos,a)
    out[tuple(ind)] = True
    return out

如果您要扩展一个单例尺寸,则通用解决方案可以找到第一个可用的单例尺寸:

def onehot2(a,axis=None,dtype=bool):
    shape = np.array(a.shape)
    if axis is None:
        axis = (shape == 1).argmax()
    if shape[axis] != 1:
        raise ValueError(f'Dimension at {axis} is non-singleton')
    shape[axis] = a.max() + 1
    out = np.zeros(shape,sparse=True))
    ind[axis] = a
    out[tuple(ind)] = True
    return out

要使用最后一个可用的单例,请将axis = (shape == 1).argmax()替换为

axis = a.ndim - 1 - (shape[::-1] == 1).argmax()

以下是一些用法示例:

>>> np.random.seed(0x111)
>>> x = np.random.randint(5,size=(3,2))
>>> x
array([[2,3],[3,1],[4,0]])

>>> a = onehot(x,dtype=int)
>>> a.shape
(3,2,5)
>>> a
array([[[0,1,0],# 2
        [0,0]],# 3

       [[0,# 3
        [0,# 1

       [[0,# 4
        [1,0]]]   # 0

>>> b = onehot(x,axis=-2,dtype=int)
>>> b.shape
(3,5,2)
>>> b
array([[[0,[0,[1,[[0,0]]])

onehot2要求您将要添加的尺寸标记为单例:

>>> np.random.seed(0x111)
>>> y = np.random.randint(5,1))
>>> y
array([[[[2],[3]]],[[[3],[1]]],[[[4],[0]]]])

>>> c = onehot2(y,dtype=int)
>>> c.shape
(3,5)
>>> c
array([[[[0,0]]],[[[0,0]]]])

>>> d = onehot2(y,dtype=int)
ValueError: Dimension at -2 is non-singleton

>>> e = onehot2(y,dtype=int)
>>> e.shape
(3,1)
>>> e.squeeze()
array([[[0,0]]])
,

SciKit-learn具有编码器:

from sklearn.preprocessing import OneHotEncoder

# Data
values = np.array([1,3,4,5])
val_reshape = values.reshape(len(values),1)

# One-hot encoding
oh = OneHotEncoder(sparse = False) 
oh_arr = oh.fit_transform(val_reshape)

print(oh_arr)

output: 
[[1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 0. 1. 0.]
 [1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 0. 1.]]