我对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)
总而言之,以下是我的问题:
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)
答案 0 :(得分:23)
我认为你在这里混合了命令式和图形构造部分。操作tf.train.shuffle_batch
创建一个新的队列节点,单个节点可用于处理整个数据集。所以我认为你是挂起的,因为你在for循环中创建了一堆shuffle_batch
队列并且没有为它们启动队列运行器。
正常输入管道使用情况如下所示:
shuffle_batch
等节点添加到输入管道---图形结构的结束,命令式编程的开始 -
tf.start_queue_runners
while(True): session.run()
为了更具可扩展性(避免使用Python GIL),您可以使用TensorFlow管道生成所有数据。但是,如果性能不重要,可以使用slice_input_producer.
将numpy数组连接到输入管道。这是一个带有Print
个节点的示例,以查看正在发生的事情(Print
中的消息运行节点时转到stdout)
tf.reset_default_graph()
num_examples = 5
num_features = 2
data = np.reshape(np.arange(num_examples*num_features), (num_examples, num_features))
print data
(data_node,) = tf.slice_input_producer([tf.constant(data)], num_epochs=1, shuffle=False)
data_node_debug = tf.Print(data_node, [data_node], "Dequeueing from data_node ")
data_batch = tf.batch([data_node_debug], batch_size=2)
data_batch_debug = tf.Print(data_batch, [data_batch], "Dequeueing from data_batch ")
sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())
tf.get_default_graph().finalize()
tf.start_queue_runners()
try:
while True:
print sess.run(data_batch_debug)
except tf.errors.OutOfRangeError as e:
print "No more inputs."
你应该看到类似的东西
[[0 1]
[2 3]
[4 5]
[6 7]
[8 9]]
[[0 1]
[2 3]]
[[4 5]
[6 7]]
No more inputs.
“8,9”数字没有填满整批,因此它们没有生成。此外,tf.Print
也会打印到sys.stdout,因此它们会在终端中单独显示给我。
PS:将batch
连接到手动初始化队列的最小值位于github issue 2193
此外,出于调试目的,您可能希望在会话中设置timeout
,以便您的IPython笔记本不会挂起空队列出列。我将这个帮助函数用于我的会话
def create_session():
config = tf.ConfigProto(log_device_placement=True)
config.gpu_options.per_process_gpu_memory_fraction=0.3 # don't hog all vRAM
config.operation_timeout_in_ms=60000 # terminate on long hangs
# create interactive session to register a default session
sess = tf.InteractiveSession("", config=config)
return sess
可伸缩性注意:
tf.constant
将您的数据副本内联到图表中。 Graph定义的大小基本上限为2GB,因此这是数据大小的上限v=tf.Variable
并通过在右侧运行带有v.assign_op
的{{1}}并将numpy数组提供给占位符(tf.placeholder
来将数据保存到该限制中。 {1}})feed_dict
版本,该版本在numpy数组上运行,并使用slice_input_producer
答案 1 :(得分:13)
或者你可以尝试这个,代码使用pandas和numpy将Iris数据集加载到tensorflow中,并在会话中打印一个简单的神经元输出。希望它有助于基本理解.... [我没有添加一个热解码标签的方式]。
import tensorflow as tf
import numpy
import pandas as pd
df=pd.read_csv('/home/nagarjun/Desktop/Iris.csv',usecols = [0,1,2,3,4],skiprows = [0],header=None)
d = df.values
l = pd.read_csv('/home/nagarjun/Desktop/Iris.csv',usecols = [5] ,header=None)
labels = l.values
data = numpy.float32(d)
labels = numpy.array(l,'str')
#print data, labels
#tensorflow
x = tf.placeholder(tf.float32,shape=(150,5))
x = data
w = tf.random_normal([100,150],mean=0.0, stddev=1.0, dtype=tf.float32)
y = tf.nn.softmax(tf.matmul(w,x))
with tf.Session() as sess:
print sess.run(y)
答案 2 :(得分:2)
您可以使用最新的tf.data API:
dataset = tf.contrib.data.make_csv_dataset(filepath)
iterator = dataset.make_initializable_iterator()
columns = iterator.get_next()
with tf.Session() as sess:
sess.run([iteator.initializer])
答案 3 :(得分:2)
如果有人来这里寻找一种简单的方法来读取tf.estimator API中的绝对大小和分片的CSV文件,请参见下面的代码
CSV_COLUMNS = ['ID','text','class']
LABEL_COLUMN = 'class'
DEFAULTS = [['x'],['no'],[0]] #Default values
def read_dataset(filename, mode, batch_size = 512):
def _input_fn(v_test=False):
# def decode_csv(value_column):
# columns = tf.decode_csv(value_column, record_defaults = DEFAULTS)
# features = dict(zip(CSV_COLUMNS, columns))
# label = features.pop(LABEL_COLUMN)
# return add_engineered(features), label
# Create list of files that match pattern
file_list = tf.gfile.Glob(filename)
# Create dataset from file list
#dataset = tf.data.TextLineDataset(file_list).map(decode_csv)
dataset = tf.contrib.data.make_csv_dataset(file_list,
batch_size=batch_size,
column_names=CSV_COLUMNS,
column_defaults=DEFAULTS,
label_name=LABEL_COLUMN)
if mode == tf.estimator.ModeKeys.TRAIN:
num_epochs = None # indefinitely
dataset = dataset.shuffle(buffer_size = 10 * batch_size)
else:
num_epochs = 1 # end-of-input after this
batch_features, batch_labels = dataset.make_one_shot_iterator().get_next()
#Begins - Uncomment for testing only -----------------------------------------------------<
if v_test == True:
with tf.Session() as sess:
print(sess.run(batch_features))
#End - Uncomment for testing only -----------------------------------------------------<
return add_engineered(batch_features), batch_labels
return _input_fn
TF.estimator中的示例用法:
train_spec = tf.estimator.TrainSpec(input_fn = read_dataset(
filename = train_file,
mode = tf.estimator.ModeKeys.TRAIN,
batch_size = 128),
max_steps = num_train_steps)
答案 4 :(得分:0)
2.0兼容解决方案:此答案可能是由上述线程中的其他人提供的,但我将提供其他链接,以帮助社区。 p>
dataset = tf.data.experimental.make_csv_dataset(
file_path,
batch_size=5, # Artificially small to make examples easier to show.
label_name=LABEL_COLUMN,
na_value="?",
num_epochs=1,
ignore_errors=True,
**kwargs)
有关更多信息,请参阅此Tensorflow Tutorial。