我是TensorFlow的新手,並且想要讀取逗號分隔值(csv)文件,其中包含2列,第1列爲索引,第2列爲標籤字符串。我有下面的代碼,逐行讀取csv文件中的行,並且我能夠使用print語句正確地獲取csv文件中的數據。但是,我想從字符串標籤中進行一次性編碼轉換,而不是在TensorFlow中如何實現。最後的目標是使用tf.train.batch()函數,這樣我就可以獲得批量的單熱標籤矢量來訓練神經網絡。如何將字符串標籤轉換爲TensorFlow中的一個熱點向量?
正如您在下面的代碼中看到的那樣,我可以在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)
你想讓別人修正你的所有代碼,或者告訴你如何在TF中使用單熱編碼器嗎? –
我相信我知道如何使用TF的單熱編碼器,如上面的代碼所示。也許我應該說我應該如何使用TF的計算圖將字符串標籤轉換爲一個熱門的向量。謝謝。 –
基本上我想要的是當col2等於10個標籤字符串中的一個時,獲取標籤索引,然後將col2的值更改爲一個單獨的向量。對所有條目執行此操作,然後返回整批熱敏標籤。 –