给定一个一维下标数组:

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

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

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

当前回答

使用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

其他回答

如果你正在使用keras,有一个内置的实用程序:

from keras.utils.np_utils import to_categorical   

categorical_labels = to_categorical(int_labels, num_classes=3)

它与@YXD的答案几乎相同(请参阅源代码)。

如果使用tensorflow,则存在one_hot():

import tensorflow as tf
import numpy as np

a = np.array([1, 0, 3])
depth = 4
b = tf.one_hot(a, depth)
# <tf.Tensor: shape=(3, 3), dtype=float32, numpy=
# array([[0., 1., 0.],
#        [1., 0., 0.],
#        [0., 0., 0.]], dtype=float32)>

对于1-hot-encoding

   one_hot_encode=pandas.get_dummies(array)

例如

享受编码

P是一个2d ndarray。 我们想知道哪一个值在一行中是最大的,在这里是1,其他地方是0。

干净简单的解决方案:

max_elements_i = np.expand_dims(np.argmax(p, axis=1), axis=1)
one_hot = np.zeros(p.shape)
np.put_along_axis(one_hot, max_elements_i, 1, axis=1)

我发现最简单的解决方案结合np。拿着和眼睛

def one_hot(x, depth: int):
  return np.take(np.eye(depth), x, axis=0)

对任何形状的x都成立。