为了训练 Tensorflow 模型,从多个 TFRecord 文件提供数据的最有效方法是什么?在我当前的流程中,我迭代 TFRecord 中的示例,分别将示例提取到 Python 变量中,但我认为这不是执行此操作的正确方法。
我正在从 Keras 迁移到 Tensorflow,希望能在我的工作流程中看到一些速度改进。为此,我已将数据移至 TFRecord,现在我正试图了解如何使用 TFRecord 文件目录运行基本线性回归模型。我已经到了可以将 TFRecord 读入 Tensor 并像这样分批训练的地步(代码取自 Tensorflow 入门示例,然后进行了修改):
# Model parameters
W = tf.Variable([.1], dtype=tf.float32)
b = tf.Variable([.1], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W*x + b
y = tf.placeholder(tf.float32)
# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(loss)
# Transforms a scalar string `example_proto` into a pair of a scalar string and
# a scalar integer, representing an image and its label, respectively.
def _parse_function(example_proto):
keys_to_features = {
"X": tf.FixedLenFeature([40], tf.float32),
"Y": tf.FixedLenFeature([10], tf.float32)
}
example = tf.parse_single_example(example_proto, keys_to_features)
return example["X"][0], example["Y"][0]
filenames = tf.placeholder(tf.string, shape=[None])
dataset = tf.data.TFRecordDataset(filenames, "ZLIB")
dataset = dataset.map(_parse_function)
dataset = dataset.repeat()
dataset = dataset.batch(1024)
iterator = dataset.make_initializable_iterator()
next_element = iterator.get_next()
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
sess.run(iterator.initializer, feed_dict = { filenames: training_filenames })
for i in range(10):
**x_train, y_train = sess.run(iterator.get_next())**
sess.run(train, {x: x_train, y: y_train})
我的问题是,我不相信这会遵循 Tensorflow 可能实现的预期的、最高效的数据集工作流程。特别是,将数据从二进制提取到 python 变量中,然后将其输入训练过程有什么意义? (下面一行)
**x_train, y_train = sess.run(iterator.get_next())**
我的印象是应该有一种方法可以将二进制数据更直接地馈送到 session 中进行训练,但是在阅读了 TF 教程、示例和其他堆栈溢出帖子之后,我没有找到任何东西。
请您参考如下方法:
数据集 API 非常通用且灵活。它可以像您一样用作字典输入。然而,更好的方法是将数据集合并到图中并使其同时处理所有内容。
def model_function(input, label)
# Model parameters
W = tf.Variable([None, input.shape[1]], dtype=tf.float32)
b = tf.Variable([input.shape[1]], dtype=tf.float32)
# Model input and output
x = input
linear_model = W*x + b
y = label
# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(loss)
return train
---<Previous dataset related code>---
iterator.make_initializable_iterator()
next_example, next_label = iterator.get_next()
train_op = model_function(next_example, next label)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for steps in range(1000):
_ = sess.run([train_op], feeddict={filenames: training_filenames})
通过这种方式,数据集操作是主图的一部分。这也将更好地使用数据集的排队结构。由于只使用了一个 sess.run,run 函数的开销被最小化了。
有关更多信息,请查看文档的这一部分:Importing data | Tensorflow 1.4
如果您需要在图形运行时指定的训练文件名,您只能在 feeddict 中指定该占位符。但是,我建议不要这样做。文件名是相当静态的。我会使用诸如 config.py 之类的资源文件,并将所有配置属性放在该文件中。然后在图形构建中加载文件名。
要指定文件名,有两种方法。 第一个:
...
filenames = tf.constant([filename1.tfrecords, filename2.tfrecords], dtype=tf.String)
dataset = tf.data.Dataset(filenames, "ZLIB")
...
否则,更合适的方法是在名为 resources 的主文件夹中创建一个新目录,在其中放置空的 __init__.py 文件和另一个名为 config.py 的文件。 在 config.py 中:
--- inside config.py ---
FILENAMES = ["filename1.tfrecord", "filename2.tfrecord"]
在创建数据集的主要 tensorflow 函数中:
--- inside tensorflow file ---
from resources import config
...
filenames = tf.constant(config.FILENAMES, dtype=tf.String)
dataset = tf.data.Dataset(filenames, "ZLIB")
...
