gpt4 book ai didi

tensorflow - tf.keras : Evaluating model. 使用 tf.data.Dataset 作为输入时更新中断

转载 作者:行者123 更新时间:2023-12-03 13:10:30 28 4
gpt4 key购买 nike

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

我有一个 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() 获取下一批。调用然后将获取的 Numpy 数组提供给第二个 sess.run()调用 feed_dict .这行得通,但显然部分违背了使用 tf.data 的目的。接口(interface):

# 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工作得很好。

关于tensorflow - tf.keras : Evaluating model. 使用 tf.data.Dataset 作为输入时更新中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610806/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com