给定一个一维下标数组:

a = array([1, 0, 3])

我想把它编码成一个2D数组:

b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])

当前回答

这种类型的编码通常是numpy数组的一部分。如果你使用numpy数组,像这样:

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

然后有一个非常简单的方法将其转换为1-hot编码

out = (np.arange(4) == a[:,None]).astype(np.float32)

就是这样。

其他回答

为了详细说明K3—rnc的优秀答案,这里有一个更通用的版本:

def onehottify(x, n=None, dtype=float):
    """1-hot encode x with the max value n (computed from data if n is None)."""
    x = np.asarray(x)
    n = np.max(x) + 1 if n is None else n
    return np.eye(n, dtype=dtype)[x]

此外,这里是这个方法的快速和粗略的基准测试,以及YXD目前接受的答案(略有更改,以便他们提供相同的API,除了后者只适用于1D ndarray):

def onehottify_only_1d(x, n=None, dtype=float):
    x = np.asarray(x)
    n = np.max(x) + 1 if n is None else n
    b = np.zeros((len(x), n), dtype=dtype)
    b[np.arange(len(x)), x] = 1
    return b

后一种方法快35% (MacBook Pro 13 2015),但前一种更通用:

>>> import numpy as np
>>> np.random.seed(42)
>>> a = np.random.randint(0, 9, size=(10_000,))
>>> a
array([6, 3, 7, ..., 5, 8, 6])
>>> %timeit onehottify(a, 10)
188 µs ± 5.03 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit onehottify_only_1d(a, 10)
139 µs ± 2.78 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

使用Neuraxle管道步骤:

树立榜样

import numpy as np
a = np.array([1,0,3])
b = np.array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])

进行实际的转换

from neuraxle.steps.numpy import OneHotEncoder
encoder = OneHotEncoder(nb_columns=4)
b_pred = encoder.transform(a)

断言它有效

assert b_pred == b

文档链接:neuraxle.steps.numpy.OneHotEncoder

你也可以使用numpy的eye函数:

numpy。眼(类数)[包含标签的向量]

这是一个与维度无关的独立解决方案。

这将把任何非负整数的N维数组arr转换为一个N+1维数组one_hot,其中one_hot[i_1,…,i_N,c] = 1表示arr[i_1,…,i_N] = c.可以通过np恢复输入。argmax (one_hot, 1)

def expand_integer_grid(arr, n_classes):
    """

    :param arr: N dim array of size i_1, ..., i_N
    :param n_classes: C
    :returns: one-hot N+1 dim array of size i_1, ..., i_N, C
    :rtype: ndarray

    """
    one_hot = np.zeros(arr.shape + (n_classes,))
    axes_ranges = [range(arr.shape[i]) for i in range(arr.ndim)]
    flat_grids = [_.ravel() for _ in np.meshgrid(*axes_ranges, indexing='ij')]
    one_hot[flat_grids + [arr.ravel()]] = 1
    assert((one_hot.sum(-1) == 1).all())
    assert(np.allclose(np.argmax(one_hot, -1), arr))
    return one_hot

你可以使用sklearn.预处理。labelbinarizer:

例子:

import sklearn.preprocessing
a = [1,0,3]
label_binarizer = sklearn.preprocessing.LabelBinarizer()
label_binarizer.fit(range(max(a)+1))
b = label_binarizer.transform(a)
print('{0}'.format(b))

输出:

[[0 1 0 0]
 [1 0 0 0]
 [0 0 0 1]]

除此之外,你可以初始化sklearn.pre - processing. labelbinarizer(),这样transform的输出是稀疏的。