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

注意:可以在下面找到重现我的问题的自包含示例的所有代码.

我有一个tf.keras.models.Model()实例,并希望通过自定义的低级TensorFlow API训练循环来训练它.作为此训练循环的一部分,我需要确保我的自定义训练循环更新来自图层类型的所有有状态变量,例如tf.keras.layers.BatchNormalization.为了实现这一点,我从this answer年由Francois Chollet了解到我需要在每个培训步骤中评估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()调用获取下一批,然后通过feed_dict将获取的Numpy数组提供给第二个sess.run()调用.这有效,但它显然部分地违背了使用tf.data API的目的:

# Build the training-relevant part of the graph.

labels = tf.placeholder(dtype=tf.float32, shape=(None, num_classes), name='labels')

loss = tf.reduce_mean(tf.keras.backend.categorical_crossentropy(target=labels, output=model.output, from_logits=False))

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

with tf.variable_scope('metrics') as scope:
    predictions_argmax = tf.argmax(model.output, axis=-1, output_type=tf.int64)
    labels_argmax = tf.argmax(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. With BatchNorm.

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:

            b_images, b_labels = sess.run([batch_features, batch_labels])

            ret = sess.run(fetches=fetch_list, feed_dict={tf.keras.backend.learning_phase(): 1,
                                                          model.input: b_images,
                                                          labels: b_labels})

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

如上所述,这只是一个糟糕的解决方法.我怎样才能正常工作?

您可以下载TFRecord文件here.

最佳答案 问题是这一行:

model_output = model(batch_features)

在张量上调用模型通常很好,但在这种情况下会导致问题.创建模型时,其输入层创建了一个占位符张量,当您调用model.updates时,它会被馈送.不应在batch_features张量上调用模型,而应将模型的输入层设置为在创建它时构建batch_features(而不是创建占位符).也就是说,您需要在模型实例化时设置正确的输入,之后为时已晚.这样做是这样的:

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

现在运行model.updates工作得很好.

点赞