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

Ale*_*lex 5 keras tensorflow

注意:用于重现我的问题的独立示例的所有代码都可以在下面找到。

我有一个 tf.keras.models.Model() 实例,希望使用自定义低级 TensorFlow API 训练循环对其进行训练。作为此训练循环的一部分,我需要确保我的自定义训练循环更新来自图层类型(例如tf.keras.layers.BatchNormalization. 为了实现这一点,我从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)
Run Code Online (Sandbox Code Playgroud)

这个sess.run()调用会抛出错误

InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,224,224,3]
Run Code Online (Sandbox Code Playgroud)

这个错误显然不应该被提出。我不需要为占位符提供值input_1,因为我在 a 上调​​用我的模型tf.data.Dataset,而不是通过 向占位符提供输入数据feed_dict

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

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

InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,224,224,3]
Run Code Online (Sandbox Code Playgroud)

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

InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,224,224,3]
Run Code Online (Sandbox Code Playgroud)

规避此问题的一个非常糟糕的解决方法是通过单独的sess.run()调用获取下一批,然后sess.run()通过feed_dict. 这是可行的,但它显然部分违背了使用 API 的目的tf.data

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]})
Run Code Online (Sandbox Code Playgroud)

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

您可以在此处下载 TFRecord 文件。

Ale*_*lex 2

问题是这一行:

model_output = model(batch_features)
Run Code Online (Sandbox Code Playgroud)

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

input_tensor = tf.keras.layers.Input(tensor=batch_features)
Run Code Online (Sandbox Code Playgroud)

现在跑步model.updates效果很好。