【发布时间】: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