代码之家  ›  专栏  ›  技术社区  ›  Taimur Islam

python tensorflow中的分类级到一个热编码

  •  0
  • Taimur Islam  · 技术社区  · 7 年前

    如果我有这样的分类标签

    labels = [cat,dog, bird, cow]
    

    现在我想把它转换成一个热编码。是否可以使用tensorflow。 这样地

    output_label = [[1 0 0 0]
                   [0 1 0 0]
                   [0 0 1 0]
                   [0 0 0 1]]
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Tim    7 年前

    首先,您需要将分类数据转换为数字格式。例如,您可以这样做:

    def categorical_to_numerical(labels):
        num_labels=[]
        for k in labels:
            if k == 'cat':
                num_labels.append(0)
            if k == 'dog':
                num_labels.append(1)
            if k == 'bird':
                num_labels.append(2)
            if k == 'cow':
                num_labels.append(3)
        return num_labels
    
    print labels
    // prints ['cat','dog', 'bird', 'cow', 'dog', 'bird'] 
    print categorical_to_numerical(labels)
    // prints [0, 1, 2, 3, 1, 2]
    

    现在可以很容易地使用tensorflow内置函数 tf.one_hot 以下内容:

    indices = categorical_to_numerical(labels)
    detph = 4 // because you have four categories 
    one_hot_labels = tf.one_hot(indices, depth) 
    

    阅读更多关于 特遣部队 here 是的。

    推荐文章