one-hot 的 python 实现

keras中的 utils 包中的 to_categorical 用于实现 one-hot

def to_categorical(y, num_classes=None):
    y = np.array(y, dtype='int')
    print('y = ',y)  # [0 1 1 3 2]
    input_shape = y.shape
    print('input_shape = ', input_shape)  #(5,)
    print('input_shape[-1] = ',input_shape[-1]) # 5
    print('len(input_shape) = ', len(input_shape)) # 1
    if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
        input_shape = tuple(input_shape[:-1])
    y = y.ravel()
    print('y = ', y) # [0 1 1 3 2]
    if not num_classes:
        num_classes = np.max(y) + 1
    n = y.shape[0]
    categorical = np.zeros((n, num_classes))
    print('categorical = \n', categorical)
    categorical[np.arange(n), y] = 1
    print('categorical = \n', categorical)
    output_shape = input_shape + (num_classes,)
    print('input_shape = ', input_shape)
    print('(num_classes,) = ', (num_classes,))
    print('output_shape = ', output_shape)
    categorical = np.reshape(categorical, output_shape)
    print('categorical = \n', categorical)
    return categorical
y = np.array((0, 1, 1, 3, 2))
b = to_categorical(y)
print('b = \n', b)
one-hot 的 python 实现_第1张图片

源代码

def to_categorical(y, num_classes=None):
    """Converts a class vector (integers) to binary class matrix.

    E.g. for use with categorical_crossentropy.

    # Arguments
        y: class vector to be converted into a matrix
            (integers from 0 to num_classes).
        num_classes: total number of classes.

    # Returns
        A binary matrix representation of the input.
    """
    y = np.array(y, dtype='int')
    input_shape = y.shape
    if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
        input_shape = tuple(input_shape[:-1])
    y = y.ravel()
    if not num_classes:
        num_classes = np.max(y) + 1
    n = y.shape[0]
    categorical = np.zeros((n, num_classes))
    categorical[np.arange(n), y] = 1
    output_shape = input_shape + (num_classes,)
    categorical = np.reshape(categorical, output_shape)
    return categorical

你可能感兴趣的:(one-hot 的 python 实现)