如何将已弃用的 tf.train.QueueRunners tensorflow 导入数据的方法转换为新的 tf.data.Dataset 方法
How to translate deprecated tf.train.QueueRunners tensorflow approach to importing data to new tf.data.Dataset approach
尽管 tensorflow 强烈建议不要使用将被 tf.data 对象替换的已弃用函数,但似乎没有好的文档可以干净地替换现代方法中已弃用的函数。此外,Tensorflow 教程仍然使用已弃用的功能来处理文件处理(阅读数据教程:https://www.tensorflow.org/api_guides/python/reading_data)。
另一方面,虽然有很好的使用 'modern' 方法的文档(导入数据教程:https://www.tensorflow.org/guide/datasets),但仍然存在旧教程,可能会引导很多人,就像我一样,首先使用已弃用的。这就是为什么人们想要将已弃用的方法干净利落地翻译成 'modern' 方法,并且此翻译的示例可能非常有用。
#!/usr/bin/env python3
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import shutil
import os
if not os.path.exists('example'):
shutil.rmTree('example');
os.mkdir('example');
batch_sz = 10; epochs = 2; buffer_size = 30; samples = 0;
for i in range(50):
_x = np.random.randint(0, 256, (10, 10, 3), np.uint8);
plt.imsave("example/image_{}.jpg".format(i), _x)
images = tf.train.match_filenames_once('example/*.jpg')
fname_q = tf.train.string_input_producer(images,epochs, True);
reader = tf.WholeFileReader()
_, value = reader.read(fname_q)
img = tf.image.decode_image(value)
img_batch = tf.train.batch([img], batch_sz, shapes=([10, 10, 3]));
with tf.Session() as sess:
sess.run([tf.global_variables_initializer(),
tf.local_variables_initializer()])
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for _ in range(epochs):
try:
while not coord.should_stop():
sess.run(img_batch)
samples += batch_sz;
print(samples, "samples have been seen")
except tf.errors.OutOfRangeError:
print('Done training -- epoch limit reached')
finally:
coord.request_stop();
coord.join(threads)
这段代码对我来说运行得非常好,打印到控制台:
10 samples have been seen
20 samples have been seen
30 samples have been seen
40 samples have been seen
50 samples have been seen
60 samples have been seen
70 samples have been seen
80 samples have been seen
90 samples have been seen
100 samples have been seen
110 samples have been seen
120 samples have been seen
130 samples have been seen
140 samples have been seen
150 samples have been seen
160 samples have been seen
170 samples have been seen
180 samples have been seen
190 samples have been seen
200 samples have been seen
Done training -- epoch limit reached
可以看出,它使用了已弃用的函数和对象,如 tf.train.string_input_producer() 和 tf.WholeFileReader()。使用 'modern' tf.data 的等效实现。需要数据集。
编辑:
已找到导入 CSV 数据的示例:Replacing Queue-based input pipelines with tf.data。我想在这里尽可能完整,假设更多的例子更好,所以我不觉得它是一个重复的问题。
这是翻译,其打印与标准输出完全相同。
#!/usr/bin/env python3
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
import shutil
if not os.path.exists('example'):
shutil.rmTree('example');
os.mkdir('example');
batch_sz = 10; epochs = 2; buffer_sz = 30; samples = 0;
for i in range(50):
_x = np.random.randint(0, 256, (10, 10, 3), np.uint8);
plt.imsave("example/image_{}.jpg".format(i), _x);
fname_data = tf.data.Dataset.list_files('example/*.jpg')\
.shuffle(buffer_sz).repeat(epochs);
img_batch = fname_data.map(lambda fname: \
tf.image.decode_image(tf.read_file(fname),3))\
.batch(batch_sz).make_initializable_iterator();
with tf.Session() as sess:
sess.run([img_batch.initializer,
tf.global_variables_initializer(),
tf.local_variables_initializer()]);
next_element = img_batch.get_next();
try:
while True:
sess.run(next_element);
samples += batch_sz
print(samples, "samples have been seen");
except tf.errors.OutOfRangeError:
pass;
print('Done training -- epoch limit reached');
主要问题是:
- 使用
tf.data.Dataset.list_files()
将文件名作为数据集加载,而不是使用已弃用的 tf.tran.string_input_producer()
生成队列来使用文件名。
- 使用迭代器处理数据集,这也需要初始化,而不是后续读取已弃用的
tf.WholeFileReader
,使用已弃用的 tf.train.batch()
函数进行批处理。
- 不需要协调器,因为队列线程(
tf.train.QueueRunners
由 tf.train.string_input_producer()
创建)不再使用,但应该在数据集迭代器结束时检查它。
我希望这对很多人有用,就像实现它后对我一样。
参考:
- 正在导入数据:https://www.tensorflow.org/guide/datasets
- 中型数据集教程:https://towardsdatascience.com/how-to-use-dataset-in-tensorflow-c758ef9e4428
奖励: 数据集 + 估计器
#!/usr/bin/env python3
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
import shutil
if not os.path.exists('example'):
shutil.rmTree('example');
os.mkdir('example');
batch_sz = 10; epochs = 2; buffer_sz = 10000; samples = 0;
for i in range(50):
_x = np.random.randint(0, 256, (10, 10, 3), np.uint8);
plt.imsave("example/image_{}.jpg".format(i), _x);
def model(features,labels,mode,params):
return tf.estimator.EstimatorSpec(
tf.estimator.ModeKeys.PREDICT,{'images': features});
estimator = tf.estimator.Estimator(model,'model_dir',params={});
def input_dataset():
return tf.data.Dataset.list_files('example/*.jpg')\
.shuffle(buffer_sz).repeat(epochs).map(lambda fname: \
tf.image.decode_image(tf.read_file(fname),3))\
.batch(batch_sz);
predictions = estimator.predict(input_dataset,
yield_single_examples=False);
for p_dict in predictions:
samples += batch_sz;
print(samples, "samples have been seen");
print('Done training -- epoch limit reached');
主要问题是:
- 为自定义
estimator
处理图像的 model
函数定义,在本例中它什么都不做,因为我们只是传递它们。
input_dataset
函数的定义,用于检索估计器要使用的数据集(在本例中用于预测)。
- 在估计器上使用
tf.estimator.Estimator.predict()
而不是直接使用 tf.Session()
,加上 yield_single_example=False
来检索批量元素而不是字典预测列表中的单个元素。
在我看来,它更喜欢模块化和可重用的代码。
参考:
尽管 tensorflow 强烈建议不要使用将被 tf.data 对象替换的已弃用函数,但似乎没有好的文档可以干净地替换现代方法中已弃用的函数。此外,Tensorflow 教程仍然使用已弃用的功能来处理文件处理(阅读数据教程:https://www.tensorflow.org/api_guides/python/reading_data)。
另一方面,虽然有很好的使用 'modern' 方法的文档(导入数据教程:https://www.tensorflow.org/guide/datasets),但仍然存在旧教程,可能会引导很多人,就像我一样,首先使用已弃用的。这就是为什么人们想要将已弃用的方法干净利落地翻译成 'modern' 方法,并且此翻译的示例可能非常有用。
#!/usr/bin/env python3
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import shutil
import os
if not os.path.exists('example'):
shutil.rmTree('example');
os.mkdir('example');
batch_sz = 10; epochs = 2; buffer_size = 30; samples = 0;
for i in range(50):
_x = np.random.randint(0, 256, (10, 10, 3), np.uint8);
plt.imsave("example/image_{}.jpg".format(i), _x)
images = tf.train.match_filenames_once('example/*.jpg')
fname_q = tf.train.string_input_producer(images,epochs, True);
reader = tf.WholeFileReader()
_, value = reader.read(fname_q)
img = tf.image.decode_image(value)
img_batch = tf.train.batch([img], batch_sz, shapes=([10, 10, 3]));
with tf.Session() as sess:
sess.run([tf.global_variables_initializer(),
tf.local_variables_initializer()])
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for _ in range(epochs):
try:
while not coord.should_stop():
sess.run(img_batch)
samples += batch_sz;
print(samples, "samples have been seen")
except tf.errors.OutOfRangeError:
print('Done training -- epoch limit reached')
finally:
coord.request_stop();
coord.join(threads)
这段代码对我来说运行得非常好,打印到控制台:
10 samples have been seen
20 samples have been seen
30 samples have been seen
40 samples have been seen
50 samples have been seen
60 samples have been seen
70 samples have been seen
80 samples have been seen
90 samples have been seen
100 samples have been seen
110 samples have been seen
120 samples have been seen
130 samples have been seen
140 samples have been seen
150 samples have been seen
160 samples have been seen
170 samples have been seen
180 samples have been seen
190 samples have been seen
200 samples have been seen
Done training -- epoch limit reached
可以看出,它使用了已弃用的函数和对象,如 tf.train.string_input_producer() 和 tf.WholeFileReader()。使用 'modern' tf.data 的等效实现。需要数据集。
编辑:
已找到导入 CSV 数据的示例:Replacing Queue-based input pipelines with tf.data。我想在这里尽可能完整,假设更多的例子更好,所以我不觉得它是一个重复的问题。
这是翻译,其打印与标准输出完全相同。
#!/usr/bin/env python3
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
import shutil
if not os.path.exists('example'):
shutil.rmTree('example');
os.mkdir('example');
batch_sz = 10; epochs = 2; buffer_sz = 30; samples = 0;
for i in range(50):
_x = np.random.randint(0, 256, (10, 10, 3), np.uint8);
plt.imsave("example/image_{}.jpg".format(i), _x);
fname_data = tf.data.Dataset.list_files('example/*.jpg')\
.shuffle(buffer_sz).repeat(epochs);
img_batch = fname_data.map(lambda fname: \
tf.image.decode_image(tf.read_file(fname),3))\
.batch(batch_sz).make_initializable_iterator();
with tf.Session() as sess:
sess.run([img_batch.initializer,
tf.global_variables_initializer(),
tf.local_variables_initializer()]);
next_element = img_batch.get_next();
try:
while True:
sess.run(next_element);
samples += batch_sz
print(samples, "samples have been seen");
except tf.errors.OutOfRangeError:
pass;
print('Done training -- epoch limit reached');
主要问题是:
- 使用
tf.data.Dataset.list_files()
将文件名作为数据集加载,而不是使用已弃用的tf.tran.string_input_producer()
生成队列来使用文件名。 - 使用迭代器处理数据集,这也需要初始化,而不是后续读取已弃用的
tf.WholeFileReader
,使用已弃用的tf.train.batch()
函数进行批处理。 - 不需要协调器,因为队列线程(
tf.train.QueueRunners
由tf.train.string_input_producer()
创建)不再使用,但应该在数据集迭代器结束时检查它。
我希望这对很多人有用,就像实现它后对我一样。
参考:
- 正在导入数据:https://www.tensorflow.org/guide/datasets
- 中型数据集教程:https://towardsdatascience.com/how-to-use-dataset-in-tensorflow-c758ef9e4428
奖励: 数据集 + 估计器
#!/usr/bin/env python3
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
import shutil
if not os.path.exists('example'):
shutil.rmTree('example');
os.mkdir('example');
batch_sz = 10; epochs = 2; buffer_sz = 10000; samples = 0;
for i in range(50):
_x = np.random.randint(0, 256, (10, 10, 3), np.uint8);
plt.imsave("example/image_{}.jpg".format(i), _x);
def model(features,labels,mode,params):
return tf.estimator.EstimatorSpec(
tf.estimator.ModeKeys.PREDICT,{'images': features});
estimator = tf.estimator.Estimator(model,'model_dir',params={});
def input_dataset():
return tf.data.Dataset.list_files('example/*.jpg')\
.shuffle(buffer_sz).repeat(epochs).map(lambda fname: \
tf.image.decode_image(tf.read_file(fname),3))\
.batch(batch_sz);
predictions = estimator.predict(input_dataset,
yield_single_examples=False);
for p_dict in predictions:
samples += batch_sz;
print(samples, "samples have been seen");
print('Done training -- epoch limit reached');
主要问题是:
- 为自定义
estimator
处理图像的model
函数定义,在本例中它什么都不做,因为我们只是传递它们。 input_dataset
函数的定义,用于检索估计器要使用的数据集(在本例中用于预测)。- 在估计器上使用
tf.estimator.Estimator.predict()
而不是直接使用tf.Session()
,加上yield_single_example=False
来检索批量元素而不是字典预测列表中的单个元素。
在我看来,它更喜欢模块化和可重用的代码。
参考: