python - 将迭代器馈送到 Tensorflow Graph

标签 python tensorflow tensorflow-datasets

我有一个使用 make_one_shot_iterator() 创建的 tf.data.Iterator 并想用它来训练我的(现有)模型。

目前我的训练是这样的

input_node = tf.placeholder(tf.float32, shape=(None, height, width, channels))

net = models.ResNet50UpProj({'data': input_node}, batch_size, keep_prob=True,is_training=True)

labels = tf.placeholder(tf.float32, shape=(None, width, height, 1))
huberloss = tf.losses.huber_loss(predictions=net.get_output(),labels=labels)

然后调用

sess.run(train_op, feed_dict={labels:output_img, input_node:input_img})

训练后我可以得到这样的预测:

pred = sess.run(net.get_output(), feed_dict={input_node: img})

现在有了一个迭代器,我尝试了这样的事情

next_element = iterator.get_next()

像这样传递输入数据:

net = models.ResNet50UpProj({'data': next_element[0]}, batch_size, keep_prob=True,is_training=True)

像这样定义损失函数:

huberloss = tf.losses.huber_loss(predictions=net.get_output(),labels=next_element[1])

并且执行训练就像在每次调用时自动迭代迭代器一样简单:

sess.run(train_op)

我的问题是:训练后我无法做出任何预测。或者更确切地说,我不知道在我的案例中使用迭代器的正确方法。

最佳答案

解决方案 1:创建一个单独的子图仅用于推理,尤其是当您具有批归一化和丢弃等层时 (is_training=False)。

# The following code assumes that you create variables with `tf.get_variable`. 
# If you create variables manually, you have to reuse them manually.
with tf.variable_scope('somename'):
    net = models.ResNet50UpProj({'data': next_element[0]}, batch_size, keep_prob=True, is_training=True)
with tf.variable_scope('somename', reuse=True):
    net_for_eval = models.ResNet50UpProj({'data': some_placeholder_or_inference_data_iterator}, batch_size, keep_prob=True, is_training=False)

解决方案 2:使用 feed_dict。您几乎可以将任何 tf.Tensor 替换为 feed dict,而不仅仅是 tf.placeholder

sess.run(huber_loss, {next_element[0]: inference_image, next_element[1]: inference_labels})

关于python - 将迭代器馈送到 Tensorflow Graph,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48350117/

相关文章:

tensorflow - Keras 网络未训练

python - 从 Tensorflow 中的多个 tf.data.Datasets 中随机抽样

python - 类型错误 : unsupported callable using Dataset with estimator input_fn

python - 在 Python 3 中使用 PIL 库中的图像模块时出现属性错误

python - Paramiko/scp - 检查远程主机上是否存在文件

python - 从列表构建点的 3D 立方体

python - Django 用户登录表单用户为无

python - 在创建自定义层时,当在 Keras 中调用构建方法时

python - Keras 内存泄漏

python - 在 TensorFlow 2.3 中规范化 BatchDataset