- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我目前正在研究 tensorFlow,尽管教程完成起来有点简单,但真正的工作是在我们尝试输入自己的数据时才开始。
我使用了一个非常基本的动物和背景数据集 Composer 。
我创建了 3 个 tfrecords(训练/验证/测试)。然后我尝试阅读它们并训练一个简单的模型(这里是 Alexnet)。我尝试使用“FLAGS.num_iter”来确保我没有超出迭代范围。
此代码处理为我带来了一个不错的 RandomShuffleQueue“元素不足(请求 64,当前大小 0)”错误。
我尝试浏览网页,但没有找到问题的答案。他们在这里:我们如何解决这个问题?我们如何检查我们的 tfrecord 是否包含任何错误?我们可以写任何条件来确保我们有足够的元素吗?如果您对我的代码还有任何疑问,我会留下来!
最好的问候,
import tensorflow as tf
import os.path
from model import Model
from alexnet import Alexnet
FLAGS = tf.app.flags.FLAGS
NUM_LABELS = 2
IMAGE_WIDTH = 64
IMAGE_HEIGHT = 64
NUMBER_OF_CHANNELS = 3
#SOURCE_DIR = './data/'
#TRAINING_IMAGES_DIR = SOURCE_DIR + 'train/'
#LIST_FILE_NAME = 'list.txt'
BATCH_SIZE = 2
#TRAINING_SET_SIZE = 81112
TRAIN_FILE = '/home/sebv/SebV/datas/tfRecording/train.tfrecords'
VAL_FILE = '/home/sebv/SebV/datas/tfRecording/val.tfrecor'
def read_and_decode(filename_queue):
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
# Defaults are not specified since both keys are required.
features={
'image/encoded': tf.FixedLenFeature([], tf.string),
'image/format': tf.FixedLenFeature([], tf.string),
'image/class/label': tf.FixedLenFeature([], tf.int64),
'image/height': tf.FixedLenFeature([], tf.int64),
'image/width': tf.FixedLenFeature([], tf.int64),
})
# Convert from a scalar string tensor (whose single string has
# length mnist.IMAGE_PIXELS) to a uint8 tensor with shape
# [mnist.IMAGE_PIXELS].
image = tf.image.decode_png(features['image/encoded'], 3, tf.uint8)
# OPTIONAL: Could reshape into a 28x28 image and apply distortions
# here. Since we are not applying any distortions in this
# example, and the next step expects the image to be flattened
# into a vector, we don't bother.
# Convert from [0, 255] -> [-0.5, 0.5] floats.
image = tf.cast(image, tf.float32)# * (1. / 255) - 0.5
image = tf.reshape(image, [IMAGE_WIDTH,IMAGE_HEIGHT,NUMBER_OF_CHANNELS])
# Convert label from a scalar uint8 tensor to an int32 scalar.
label = tf.cast(features['image/class/label'], tf.int64)
return image, label
def inputs(train, filen, batch_size, num_epochs):
"""Reads input data num_epochs times.
Args:
train: Selects between the training (True) and validation (False) data.
batch_size: Number of examples per returned batch.
num_epochs: Number of times to read the input data, or 0/None to
train forever.
Returns:
A tuple (images, labels), where:
* images is a float tensor with shape [batch_size, mnist.IMAGE_PIXELS]
in the range [-0.5, 0.5].
* labels is an int32 tensor with shape [batch_size] with the true label,
a number in the range [0, mnist.NUM_CLASSES).
Note that an tf.train.QueueRunner is added to the graph, which
must be run using e.g. tf.train.start_queue_runners().
"""
if not num_epochs: num_epochs = None
filename = filen
filename_queue = tf.train.string_input_producer([filename], num_epochs=num_epochs)
# Even when reading in multiple threads, share the filename
# queue.
image, label = read_and_decode(filename_queue)
# Shuffle the examples and collect them into batch_size batches.
# (Internally uses a RandomShuffleQueue.)
# We run this in two threads to avoid being a bottleneck.
images, sparse_labels = tf.train.shuffle_batch([image, label], batch_size=batch_size, num_threads=2,capacity=20000 + 3 * batch_size,min_after_dequeue=20000)
sparse_labels = tf.reshape(sparse_labels, [batch_size])
return images, sparse_labels
def train():
model = Alexnet()
with tf.Graph().as_default():
x = tf.placeholder(tf.float32, [None, IMAGE_WIDTH,IMAGE_HEIGHT,NUMBER_OF_CHANNELS], name='x-input')
y = tf.placeholder(tf.float32, [None], name='y-input')
images, labels = inputs(train=True, filen=TRAIN_FILE, batch_size=FLAGS.batch_size,num_epochs=FLAGS.num_iter)
images_val, labels_val = inputs(train=False, filen=VAL_FILE, batch_size=FLAGS.batch_size,num_epochs=1)
keep_prob = tf.placeholder(tf.float32, name='dropout_prob')
global_step = tf.contrib.framework.get_or_create_global_step()
logits = model.inference(images, keep_prob=keep_prob)
loss = model.loss(logits=logits, labels=labels)
accuracy = model.accuracy(logits, labels)
summary_op = tf.summary.merge_all()
train_op = model.train(loss, global_step=global_step)
saver = tf.train.Saver()
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
writer = tf.summary.FileWriter(FLAGS.summary_dir, sess.graph)
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for i in xrange(FLAGS.num_iter):
_, cur_loss, summary = sess.run([train_op, loss, summary_op],
feed_dict={keep_prob: 0.5})
writer.add_summary(summary, i)
if i % 10 == 0:
batch_x = sess.run(images_val)
batch_y = sess.run(labels_val)
validation_accuracy = accuracy.eval(feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0})
print('Iter {} Accuracy: {}'.format(i, validation_accuracy))
saver.save(sess, FLAGS.checkpoint_file_path, global_step)
if i == FLAGS.num_iter:
coord.request_stop()
coord.join(threads)
def main(argv=None):
train()
if __name__ == '__main__':
tf.app.flags.DEFINE_integer('batch_size', 64, 'size of training batches')
tf.app.flags.DEFINE_integer('num_iter', 4001, 'number of training iterations') #10000
tf.app.flags.DEFINE_string('checkpoint_file_path', 'checkpoints/model.ckpt-10000', 'path to checkpoint file')
tf.app.flags.DEFINE_string('train_data', 'data', 'path to train and test data')
tf.app.flags.DEFINE_string('summary_dir', 'graphs', 'path to directory for storing summaries')
tf.app.run()
最佳答案
不推荐使用队列运行器 API 进行 I/O。相反,我建议使用 tf.data
API。以下是可与 Estimator
一起使用的 AlexNet 数据输入函数的详细示例:
def input_fn(params):
"""Passes data to the estimator as required."""
batch_size = params["batch_size"]
def parser(serialized_example):
"""Parses a single tf.Example into a 224x224 image and label tensors."""
final_image = None
final_label = None
if FLAGS.preprocessed:
features = tf.parse_single_example(
serialized_example,
features={
"image": tf.FixedLenFeature([], tf.string),
"label": tf.FixedLenFeature([], tf.int64),
})
image = tf.decode_raw(features["image"], tf.float32)
image.set_shape([224 * 224 * 3])
final_label = tf.cast(features["label"], tf.int32)
else:
features = tf.parse_single_example(
serialized_example,
features={
"image/encoded": tf.FixedLenFeature([], tf.string),
"image/class/label": tf.FixedLenFeature([], tf.int64),
})
image = tf.image.decode_jpeg(features["image/encoded"], channels=3)
image = tf.image.resize_images(
image,
size=[224, 224])
final_label = tf.cast(features["image/class/label"], tf.int32)
final_image = (tf.cast(image, tf.float32) * (1. / 255)) - 0.5
return final_image, final_label
file_pattern = os.path.join(FLAGS.data_dir, "train-*")
dataset = tf.data.Dataset.list_files(file_pattern)
if FLAGS.filename_shuffle_buffer_size > 0:
dataset = dataset.shuffle(buffer_size=FLAGS.filename_shuffle_buffer_size)
dataset = dataset.repeat()
def prefetch_map_fn(filename):
dataset = tf.data.TFRecordDataset(
filename, buffer_size=FLAGS.dataset_reader_buffer_size)
if FLAGS.prefetch_size is None:
dataset = dataset.prefetch(batch_size)
else:
if FLAGS.prefetch_size > 0:
dataset = dataset.prefetch(FLAGS.prefetch_size)
return dataset
if FLAGS.use_sloppy_interleave:
dataset = dataset.apply(
tf.contrib.data.sloppy_interleave(
prefetch_map_fn, cycle_length=FLAGS.cycle_length))
else:
dataset = dataset.interleave(
prefetch_map_fn, cycle_length=FLAGS.cycle_length)
if FLAGS.element_shuffle_buffer_size > 0:
dataset = dataset.shuffle(buffer_size=FLAGS.element_shuffle_buffer_size)
dataset = dataset.map(
parser,
num_parallel_calls=FLAGS.num_parallel_calls).prefetch(batch_size)
dataset = dataset.batch(batch_size)
dataset = dataset.prefetch(1)
images, labels = dataset.make_one_shot_iterator().get_next()
return (
tf.reshape(images, [batch_size, 224, 224, 3]),
tf.reshape(labels, [batch_size])
)
您可以了解有关 tf.data
的更多信息 API在这个programmer's guide .
关于python - Tensorflow 和随机洗牌队列 "insufficient elements (requested 64, current size 0)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47796396/
我有一个 jQuery 日期选择器。我想将默认日期设置为“当前月份、当前日期(当前年份-18)”,但在设置 defaultDate 属性时遇到问题。显示的默认年份是 1920 年,据说是 1995 年
我有下面的 C 程序来实现升序链表。问题出在 buildList() 函数中,因此您可以忽略除 main() 和 buildList() 之外的其他函数。 #include #include stru
嗯,想象一下 current.txt 文件: asdf base.txt 文件: asdf 其他.txt文件: asdf 当我进行三向 merge 时 git merge-file current.t
我试图在鼠标悬停时生成一个 :after 伪元素。例如: .email{ width:100px; overflow:hidden; text-overflow:ellipsi
为什么 $('a.current').removeClass('current'); 不适用于此 jquery 选项卡? http://jsfiddle.net/laukstein/ytnw9/8/
我正在创建一个应用程序(Outlook 的 Office 加载项) 我遇到的问题是更新我的屏幕。我知道我需要调用 Dispatcher,但是它在我的 ViewModel 中始终为 null p
我为客户开发网络和移动应用程序。在我当前的架构中,许多资源在 Web 访问和移动访问之间共享。 aspx 页面可以显示在网络上,也可以在移动应用程序中调用 WebView 。我的问题是: WebOpe
我通过调用 IEnumerable.GetEnumerator() 得到了一个枚举器,然后我称它为MoveNext()直到它返回false,然后访问它的Current属性(property)。令我惊讶
我正在尝试动态查找当前运行的函数(此函数)的名称,即 (defun my-func () (remove-hook 'some-hook this-function) (do-
阅读了短语 "The current SynchronizationContext is a property of the current thread" correct" ,我有点懵了…… 在 V
集成 IOS STRIPE TERMINAL SDK对于BBPOS Chipper 2X BT使用 swift 。我们已经开发并测试了该系统,并且运行良好。但是当我们将它交给其他国家的客户时,他们收到
当我在训练期间编写的类上实现 IEnumerable 和 IEnumerator 时,我注意到我需要为属性“Current”指定两个实现。 public class PeopleEnumerator
我原以为对实现了 IEnumerable 的空集合执行以下代码会抛出异常: var enumerator = collection.GetEnumerator(); enumerator.MoveNe
应Application.Current.Shutdown()不用作关闭 WPF 应用程序的最佳实践? 我有一个小的多窗口应用程序,“关机”似乎对我所有的退出命令都很好。但是,我被告知要始终使用 Ap
在 XPath 1.0 中,有一个函数 current() 可以派上用场,当我根据我当时所在的节点引用 XML 中其他地方的节点时。我的 XML 具有如下结构:
在 MVC 中,这两者有什么区别? 它们看起来相同,甚至返回相同的类型/类System.Web.Security.RolePrincipal,但有一些微妙之处。 例如。当针对通过 ClaimsPrin
这个问题在这里已经有了答案: What is the difference between an App and Application in c#.net? (1 个回答) 关闭 7 年前。 这两
我正在为我的团队开发一个代码生成器 (VSIX),在我与 VSIX 可扩展性框架作斗争之后,我打算使用 Roslyn 作为基础引擎。 我的代码生成器目前能够为解决方案生成一个新的 csproj,并且能
为什么 $('a.current').parent('li').addClass('current'); 和 $(this).hasClass('current')。 parent('li').add
当我使用 Xcode 调试我的 iOS 程序时,gdb 将其显示在控制台 View 上,并且没有发生任何错误。 我只想知道输出“Current language: auto; currently ob
我是一名优秀的程序员,十分优秀!