美文网首页
用Numpy快速实现one_hot编码标签

用Numpy快速实现one_hot编码标签

作者: LabVIEW_Python | 来源:发表于2021-02-13 11:41 被阅读0次

    机器学习的分类问题,常用one_hot编码方式做为标签;经常会需要将连续的整型标签值转化为one_hot编码标签,用Numpy实现转换(映射map)的一个思路:用连续的整型标签值索引np.eye数组。范例代码如下:

    import numpy as np
    #连续的整型标签值
    labels = np.array([0, 1, 2, 1, 2, 0, 2, 1, 0])
    #类别
    num_classes = 3
    #one_hot编码
    one_hot_codes = np.eye(num_classes)
    
    one_hot_labels = []
    for label in labels:
        #将连续的整型值映射为one_hot编码
        one_hot_label = one_hot_codes[label]
        one_hot_labels.append(one_hot_label)
    
    one_hot_labels = np.array(one_hot_labels)
    print(one_hot_labels)
    

    运行结果:

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

    相关文章

      网友评论

          本文标题:用Numpy快速实现one_hot编码标签

          本文链接:https://www.haomeiwen.com/subject/ffysxltx.html