tf.keras:使用tf.data.Dataset作为输入时,评估model.updates会中断

时间:2019-02-09 21:13:06

标签: tensorflow keras

注意:下面是一个重现我的问题的独立示例的所有代码。

我有一个tf.keras.models.Model()实例,并希望使用自定义的低级TensorFlow API训练循环对其进行训练。作为此训练循环的一部分,我需要确保我的自定义训练循环更新诸如tf.keras.layers.BatchNormalization之类的图层类型的所有有状态变量。为了做到这一点,我从弗朗索瓦·乔勒(Francois Chollet)的this answer了解到,我需要在每个训练步骤中对model.updates进行评估。

问题是:当您使用feed_dict将训练数据输入模型时,此方法有效,但是当您使用tf.data.Dataset对象时,该方法无效。

请考虑以下抽象示例(您可以在下面找到一个具体的示例来重现该问题):

model = tf.keras.models.Model(...) # Some tf.keras model
dataset = tf.data.Dataset.from_tensor_slices(...) # Some tf.data.Dataset
iterator = dataset.make_one_shot_iterator()
features, labels = iterator.get_next()

model_output = model(features)

with tf.Session() as sess:
    ret = sess.run(model.updates)

sess.run()调用会引发错误

InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,224,224,3]

显然不应该引发此错误。我不需要为占位符input_1提供值,因为我是在tf.data.Dataset上调用我的模型,而不是通过feed_dict将输入数据提供给占位符。

我该怎么做才能使这项工作成功?

这是一个完全可重复的示例。这是在Caltech256上接受训练的简单图像分类器(使用本文底部的链接下载TFRecord文件):

import tensorflow as tf
from tqdm import trange
import sys
import glob
import os

sess = tf.Session()
tf.keras.backend.set_session(sess)

num_classes = 257
image_size = (224, 224, 3)

# Build a simple CNN with BatchNorm layers.

input_tensor = tf.keras.layers.Input(shape=image_size)
x = tf.keras.layers.Conv2D(64, (3,3), strides=(2,2), kernel_initializer='he_normal')(input_tensor)
x = tf.keras.layers.BatchNormalization(axis=3)(x)
x = tf.keras.layers.Activation('relu')(x)
x = tf.keras.layers.Conv2D(64, (3,3), strides=(2,2), kernel_initializer='he_normal')(x)
x = tf.keras.layers.BatchNormalization(axis=3)(x)
x = tf.keras.layers.Activation('relu')(x)
x = tf.keras.layers.Conv2D(128, (3,3), strides=(2,2), kernel_initializer='he_normal')(x)
x = tf.keras.layers.BatchNormalization(axis=3)(x)
x = tf.keras.layers.Activation('relu')(x)
x = tf.keras.layers.Conv2D(256, (3,3), strides=(2,2), kernel_initializer='he_normal')(x)
x = tf.keras.layers.BatchNormalization(axis=3)(x)
x = tf.keras.layers.Activation('relu')(x)
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = tf.keras.layers.Dense(num_classes, activation='softmax', kernel_initializer='he_normal')(x)
model = tf.keras.models.Model(input_tensor, x)

# We'll monitor whether the moving mean and moving variance of the first BatchNorm layer is being updated as it should.
moving_mean = tf.reduce_mean(model.layers[2].moving_mean)
moving_variance = tf.reduce_mean(model.layers[2].moving_variance)

# Build a tf.data.Dataset from TFRecords.

tfrecord_directory = '/path/to/the/tfrecord/files/'

tfrecord_filennames = glob.glob(os.path.join(tfrecord_directory, '*.tfrecord'))

feature_schema = {'image': tf.FixedLenFeature([], tf.string),
                  'filename': tf.FixedLenFeature([], tf.string),
                  'label': tf.FixedLenFeature([], tf.int64)}

dataset = tf.data.Dataset.from_tensor_slices(tfrecord_filennames)
dataset = dataset.shuffle(len(tfrecord_filennames)) # Shuffle the TFRecord file names.
dataset = dataset.flat_map(lambda filename: tf.data.TFRecordDataset(filename))
dataset = dataset.map(lambda single_example_proto: tf.parse_single_example(single_example_proto, feature_schema)) # Deserialize tf.Example objects.
dataset = dataset.map(lambda sample: (sample['image'], sample['label']))
dataset = dataset.map(lambda image, label: (tf.image.decode_jpeg(image, channels=3), label)) # Decode JPEG images.
dataset = dataset.map(lambda image, label: (tf.image.resize_image_with_pad(image, target_height=image_size[0], target_width=image_size[1]), label))
dataset = dataset.map(lambda image, label: (tf.image.per_image_standardization(image), label))
dataset = dataset.map(lambda image, label: (image, tf.one_hot(indices=label, depth=num_classes))) # Convert labels to one-hot format.
dataset = dataset.shuffle(buffer_size=10000)
dataset = dataset.repeat()
dataset = dataset.batch(32)

iterator = dataset.make_one_shot_iterator()
batch_features, batch_labels = iterator.get_next()

# Build the training-relevant part of the graph.

model_output = model(batch_features)

loss = tf.reduce_mean(tf.keras.backend.categorical_crossentropy(target=batch_labels, output=model_output, from_logits=False))

train_step = tf.train.AdamOptimizer().minimize(loss)

# The next block is for the metrics.
with tf.variable_scope('metrics') as scope:
    predictions_argmax = tf.argmax(model_output, axis=-1, output_type=tf.int64)
    labels_argmax = tf.argmax(batch_labels, axis=-1, output_type=tf.int64)
    mean_loss_value, mean_loss_update_op = tf.metrics.mean(loss)
    acc_value, acc_update_op = tf.metrics.accuracy(labels=labels_argmax, predictions=predictions_argmax)
    local_metric_vars = tf.contrib.framework.get_variables(scope=scope, collection=tf.GraphKeys.LOCAL_VARIABLES)
    metrics_reset_op = tf.variables_initializer(var_list=local_metric_vars, name='metrics_reset_op')

# Run the training.

epochs = 3
steps_per_epoch = 1000

fetch_list = [mean_loss_value,
              acc_value,
              moving_mean,
              moving_variance,
              train_step,
              mean_loss_update_op,
              acc_update_op] + model.updates

sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())

with sess.as_default():

    for epoch in range(1, epochs+1):

        tr = trange(steps_per_epoch, file=sys.stdout)
        tr.set_description('Epoch {}/{}'.format(epoch, epochs))

        sess.run(metrics_reset_op)

        for train_step in tr:

            ret = sess.run(fetches=fetch_list, feed_dict={tf.keras.backend.learning_phase(): 1})

            tr.set_postfix(ordered_dict={'loss': ret[0],
                                         'accuracy': ret[1],
                                         'bn1 moving mean': ret[2],
                                         'bn1 moving variance': ret[3]})

运行此代码将引发上述错误:

InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,224,224,3]

一个非常糟糕的解决方法是通过单独的sess.run()调用获取下一批,然后通过{{1将获取的Numpy数组馈送到第二个sess.run()调用}}。这种方法有效,但显然部分地破坏了使用feed_dict API的目的:

tf.data

如上所述,这只是一个不好的解决方法。我该如何使其正常工作?

您可以下载TFRecord文件here

1 个答案:

答案 0 :(得分:1)

问题是这一行:

model_output = model(batch_features)

通常可以在张量上调用模型,但是在这种情况下会引起问题。创建模型后,其输入层创建了一个占位符张量,当您调用model.updates时,该占位符张量将被输入。与其在batch_features张量上调用模型,不如在创建模型时将模型的输入层设置为建立在batch_features之上(而不是创建占位符)。也就是说,您需要在模型实例化时设置正确的输入,否则为时已​​晚。这样做是这样的:

input_tensor = tf.keras.layers.Input(tensor=batch_features)

现在运行model.updates很好。