【问题标题】:How to convert string labels to one-hot vectors in TensorFlow?如何在 TensorFlow 中将字符串标签转换为 one-hot 向量?
【发布时间】:2017-09-22 00:03:21
【问题描述】:

我是 TensorFlow 新手,想读取一个逗号分隔值 (csv) 文件,其中包含 2 列,第 1 列是索引,第 2 列是标签字符串。我有以下代码逐行读取 csv 文件中的行,并且我能够使用打印语句正确获取 csv 文件中的数据。但是,我想从字符串标签进行一次热编码转换,而不是如何在 TensorFlow 中进行。最终目标是使用 tf.train.batch() 函数,这样我就可以获得一批单热标签向量来训练神经网络。

正如您在下面的代码中所见,我可以在 TensorFlow 会话中手动为每个标签条目创建一个单热向量。但是如何使用 tf.train.batch() 函数?如果我移动这条线

label_batch = tf.train.batch([col2], batch_size=5)

进入 TensorFlow 会话块(将 col2 替换为 label_one_hot),程序块什么都不做。我试图将单热向量转换移到 TensorFlow 会话之外,但未能使其正常工作。正确的方法是什么?请帮忙。

label_files = []
label_files.append(LABEL_FILE)
print "label_files: ", label_files

filename_queue = tf.train.string_input_producer(label_files)

reader = tf.TextLineReader()
key, value = reader.read(filename_queue)
print "key:", key, ", value:", value

record_defaults = [['default_id'], ['default_label']]
col1, col2 = tf.decode_csv(value, record_defaults=record_defaults)

num_lines = sum(1 for line in open(LABEL_FILE))

label_batch = tf.train.batch([col2], batch_size=5)

with tf.Session() as sess:
    coordinator = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coordinator)

    for i in range(100):
        column1, column2 = sess.run([col1, col2])

        index = 0
        if column2 == 'airplane':
            index = 0
        elif column2 == 'automobile':
            index = 1
        elif column2 == 'bird':
            index = 2
        elif column2 == 'cat':
            index = 3
        elif column2 == 'deer':
            index = 4
        elif column2 == 'dog':
            index = 5
        elif column2 == 'frog':
            index = 6
        elif column2 == 'horse':
            index = 7
        elif column2 == 'ship':
            index = 8
        elif column2 == 'truck':
            index = 9

        label_one_hot = tf.one_hot([index], 10)  # depth=10 for 10 categories
        print "column1:", column1, ", column2:", column2
        # print "onehot label:", sess.run([label_one_hot])

    print sess.run(label_batch)

    coordinator.request_stop()
    coordinator.join(threads)

【问题讨论】:

  • 您希望有人修复您的所有代码,还是向您展示如何在 TF 中使用 one-hot 编码器?
  • 相信我知道如何使用TF的one-hot编码器,如上代码所示。也许我应该说如何使用 TF 的计算图将字符串标签转换为 one-hot 向量。谢谢。
  • 基本上我想要的是当 col2 等于 10 个标签字符串之一时,获取标签索引,然后将 col2 的值更改为 one-hot 向量。对所有条目执行此操作,然后返回整批 one-hot 标签。

标签: python machine-learning tensorflow


【解决方案1】:

问这个问题已经 2 年多了,但这个答案可能对某些人来说仍然相关。这是在 TF 中将字符串标签转换为 one-hot 向量的一种简单方法:

import tensorflow as tf

vocab = ['a', 'b', 'c']

input = tf.placeholder(dtype=tf.string, shape=(None,))
matches = tf.stack([tf.equal(input, s) for s in vocab], axis=-1)
onehot = tf.cast(matches, tf.float32)

with tf.Session() as sess:
    out = sess.run(onehot, feed_dict={input: ['c', 'a']})
    print(out) # prints [[0. 0. 1.]
               #         [1. 0. 0.]]

【讨论】:

    【解决方案2】:

    您可能想尝试将您的index 变量输入到占位符中,然后通过tf.one_hot 将其转换为单热向量?大致如下:

    lbl = tf.placeholder(tf.uint8, [YOUR_BATCH_SIZE])
    lbl_one_hot = tf.one_hot(lbl, YOUR_VOCAB_SIZE, 1.0, 0.0)
    lb_h = sess.run([lbl_one_hot], feed_dict={lbl: index})
    

    不确定您是否分批做事,所以如果不是,您的情况可能与 YOUR_BATCH_SIZE 无关。你也可以使用 numpy.zeros 来完成,但我发现上面的方法更简洁、更容易,尤其是批处理。

    【讨论】:

    • 用这个方法,我们在TF外准备标签索引列表?我如何在 TF 中进行所有操作?
    • 你的意思是如何将字符串标签映射到 TF 中的整数?如果是这样,恐怕我还没有遇到过那个。希望其他人会回答。我想在外面做会容易得多,比如使用 PD DataFrame
    • 是的,我就是这个意思。也许我也应该在外面做。谢谢@VS_FF!
    • @so_user 你可以使用tf.contrib.lookup.index_table_from_tensor。详情请见this question
    • @so_user 在我的回答中,一切都发生在计算图中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 2020-10-10
    • 2017-07-27
    相关资源
    最近更新 更多