我是TensorFlow的新手,想读一个逗号分隔值(csv)文件,它包含两列,第1列是索引,第2列是标签字符串。我有以下代码,它逐行读取csv文件中的行,并且我能够使用print语句正确地获取csv文件中的数据。但是,我想从字符串标签进行一次热编码转换,而不是如何在TensorFlow中进行转换。最后一个目标是使用tf.train.batch()函数,这样我就可以得到一批热标签向量来训练神经网络。
正如您在下面的代码中看到的,我可以在TensorFlow会话中为每个标签条目手动创建一个热向量。但是如何使用tf.train.batch()函数呢?如果我移动线路label_batch = tf.train.batch([col2], batch_size=5)
进入TensorFlow会话块(用label_one_hot替换col2),程序块什么也不做。我试图将一个热向量转换移到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)