给定一个一维下标数组:
a = array([1, 0, 3])
我想把它编码成一个2D数组:
b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
给定一个一维下标数组:
a = array([1, 0, 3])
我想把它编码成一个2D数组:
b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
当前回答
如果你正在使用keras,有一个内置的实用程序:
from keras.utils.np_utils import to_categorical
categorical_labels = to_categorical(int_labels, num_classes=3)
它与@YXD的答案几乎相同(请参阅源代码)。
其他回答
我发现最简单的解决方案结合np。拿着和眼睛
def one_hot(x, depth: int):
return np.take(np.eye(depth), x, axis=0)
对任何形状的x都成立。
创建一个有足够列的零数组b,即a.max() + 1。 然后,对于每一行i,设置第a[i]列为1。
>>> a = np.array([1, 0, 3])
>>> b = np.zeros((a.size, a.max() + 1))
>>> b[np.arange(a.size), a] = 1
>>> b
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])
我认为简短的答案是否定的。对于n维的更一般的情况,我想到了这个:
# For 2-dimensional data, 4 values
a = np.array([[0, 1, 2], [3, 2, 1]])
z = np.zeros(list(a.shape) + [4])
z[list(np.indices(z.shape[:-1])) + [a]] = 1
我想知道是否有更好的解决方案——我不喜欢我必须在最后两行创建这些列表。不管怎样,我用timeit做了一些测量,似乎基于numpy的(索引/范围)和迭代版本的表现是一样的。
为了详细说明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)
对于1-hot-encoding
one_hot_encode=pandas.get_dummies(array)
例如
享受编码