给定一个一维下标数组:

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

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

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

当前回答

对于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)

我添加了一个简单的补全函数,只使用numpy操作符:

   def probs_to_onehot(output_probabilities):
        argmax_indices_array = np.argmax(output_probabilities, axis=1)
        onehot_output_array = np.eye(np.unique(argmax_indices_array).shape[0])[argmax_indices_array.reshape(-1)]
        return onehot_output_array

它以一个概率矩阵作为输入:例如:

[[0.03038822 0.65810204 0.16549407 0.3797123] . [0.02771272 0.2760752 0.3280924 0.33458805]

它会返回

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

对于1-hot-encoding

   one_hot_encode=pandas.get_dummies(array)

例如

享受编码

def one_hot(n, class_num, col_wise=True):
  a = np.eye(class_num)[n.reshape(-1)]
  return a.T if col_wise else a

# Column for different hot
print(one_hot(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 8, 7]), 10))
# Row for different hot
print(one_hot(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 8, 7]), 10, col_wise=False))

下面是我根据上面的答案和我自己的用例写的一个示例函数:

def label_vector_to_one_hot_vector(vector, one_hot_size=10):
    """
    Use to convert a column vector to a 'one-hot' matrix

    Example:
        vector: [[2], [0], [1]]
        one_hot_size: 3
        returns:
            [[ 0.,  0.,  1.],
             [ 1.,  0.,  0.],
             [ 0.,  1.,  0.]]

    Parameters:
        vector (np.array): of size (n, 1) to be converted
        one_hot_size (int) optional: size of 'one-hot' row vector

    Returns:
        np.array size (vector.size, one_hot_size): converted to a 'one-hot' matrix
    """
    squeezed_vector = np.squeeze(vector, axis=-1)

    one_hot = np.zeros((squeezed_vector.size, one_hot_size))

    one_hot[np.arange(squeezed_vector.size), squeezed_vector] = 1

    return one_hot

label_vector_to_one_hot_vector(vector=[[2], [0], [1]], one_hot_size=3)