【发布时间】:2016-09-02 16:18:13
【问题描述】:
我对 TensorFlow 的世界还比较陌生,并且对您如何实际上将 CSV 数据读入 TensorFlow 中的可用示例/标签张量感到非常困惑。 TensorFlow tutorial on reading CSV data 中的示例非常分散,只能让您在 CSV 数据上进行训练。
这是我根据 CSV 教程拼凑的代码:
from __future__ import print_function
import tensorflow as tf
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
filename = "csv_test_data.csv"
# setup text reader
file_length = file_len(filename)
filename_queue = tf.train.string_input_producer([filename])
reader = tf.TextLineReader(skip_header_lines=1)
_, csv_row = reader.read(filename_queue)
# setup CSV decoding
record_defaults = [[0],[0],[0],[0],[0]]
col1,col2,col3,col4,col5 = tf.decode_csv(csv_row, record_defaults=record_defaults)
# turn features back into a tensor
features = tf.stack([col1,col2,col3,col4])
print("loading, " + str(file_length) + " line(s)\n")
with tf.Session() as sess:
tf.initialize_all_variables().run()
# start populating filename queue
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(file_length):
# retrieve a single instance
example, label = sess.run([features, col5])
print(example, label)
coord.request_stop()
coord.join(threads)
print("\ndone loading")
这是我正在加载的 CSV 文件中的一个简短示例 - 非常基本的数据 - 4 个特征列和 1 个标签列:
0,0,0,0,0
0,15,0,0,0
0,30,0,0,0
0,45,0,0,0
上面的所有代码都是从 CSV 文件中逐个打印每个示例,虽然不错,但对训练毫无用处。
我在这里苦苦挣扎的是,您实际上如何将这些单独的示例,一个一个地加载,转化为训练数据集。例如,here's a notebook 我正在学习 Udacity 深度学习课程。我基本上想获取我正在加载的 CSV 数据,并将其放入 train_dataset 和 train_labels 之类的东西中:
def reformat(dataset, labels):
dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
# Map 2 to [0.0, 1.0, 0.0 ...], 3 to [0.0, 0.0, 1.0 ...]
labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
return dataset, labels
train_dataset, train_labels = reformat(train_dataset, train_labels)
valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
test_dataset, test_labels = reformat(test_dataset, test_labels)
print('Training set', train_dataset.shape, train_labels.shape)
print('Validation set', valid_dataset.shape, valid_labels.shape)
print('Test set', test_dataset.shape, test_labels.shape)
我试过像这样使用tf.train.shuffle_batch,但它只是莫名其妙地挂起:
for i in range(file_length):
# retrieve a single instance
example, label = sess.run([features, colRelevant])
example_batch, label_batch = tf.train.shuffle_batch([example, label], batch_size=file_length, capacity=file_length, min_after_dequeue=10000)
print(example, label)
所以总结一下,这是我的问题:
-
我在这个过程中遗漏了什么?
- 感觉我缺少一些关于如何正确构建输入管道的关键直觉。
-
有没有办法避免知道 CSV 文件的长度?
- 必须知道要处理的行数感觉很不雅(上面的
for i in range(file_length)代码行)
- 必须知道要处理的行数感觉很不雅(上面的
编辑: 一旦雅罗斯拉夫指出我可能在这里混淆了命令式和图形构造部分,它就开始变得更加清晰。我能够汇总以下代码,我认为这更接近从 CSV 训练模型时通常会执行的操作(不包括任何模型训练代码):
from __future__ import print_function
import numpy as np
import tensorflow as tf
import math as math
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('dataset')
args = parser.parse_args()
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
def read_from_csv(filename_queue):
reader = tf.TextLineReader(skip_header_lines=1)
_, csv_row = reader.read(filename_queue)
record_defaults = [[0],[0],[0],[0],[0]]
colHour,colQuarter,colAction,colUser,colLabel = tf.decode_csv(csv_row, record_defaults=record_defaults)
features = tf.stack([colHour,colQuarter,colAction,colUser])
label = tf.stack([colLabel])
return features, label
def input_pipeline(batch_size, num_epochs=None):
filename_queue = tf.train.string_input_producer([args.dataset], num_epochs=num_epochs, shuffle=True)
example, label = read_from_csv(filename_queue)
min_after_dequeue = 10000
capacity = min_after_dequeue + 3 * batch_size
example_batch, label_batch = tf.train.shuffle_batch(
[example, label], batch_size=batch_size, capacity=capacity,
min_after_dequeue=min_after_dequeue)
return example_batch, label_batch
file_length = file_len(args.dataset) - 1
examples, labels = input_pipeline(file_length, 1)
with tf.Session() as sess:
tf.initialize_all_variables().run()
# start populating filename queue
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
try:
while not coord.should_stop():
example_batch, label_batch = sess.run([examples, labels])
print(example_batch)
except tf.errors.OutOfRangeError:
print('Done training, epoch reached')
finally:
coord.request_stop()
coord.join(threads)
【问题讨论】:
-
我一直在尝试您的代码,但无法使其正常工作。你确定有什么我想念的吗?谢谢。我在这里发布了一个帖子,以便您了解更多详细信息:stackoverflow.com/questions/40143019/…
标签: python csv tensorflow