使用基本的低级TensorFlow训练循环训练tf.keras模型不起作用

时间:2019-02-10 22:28:28

标签: python tensorflow keras

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

我有一个tf.keras.models.Model实例,需要使用用低级TensorFlow API编写的训练循环对其进行训练。

问题: 一次使用基本的标准低级TensorFlow训练循环训练完全相同的tf.keras模型,一次使用Keras自己的model.fit()方法训练会产生完全不同的结果。我想找出我在低级TF训练循环中做错的事情。

该模型是我在Caltech256上训练的简单图像分类模型(链接到下面的tfrecords)。

在低级TensorFlow训练循环中,训练损失首先会按预期减少,但随后仅经过1000个训练步骤,损失达到平稳状态,然后又开始增加:

enter image description here

另一方面,使用正常的Keras训练循环在相同数据集上训练相同模​​型,则按预期工作:

enter image description here

我的低级TensorFlow训练循环中缺少什么?

以下是重现该问题的代码(下载TFRecords,底部的链接):

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 tf.data.Dataset from TFRecords.

tfrecord_directory = 'path/to/tfrecords/directory'

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()
features, labels = iterator.get_next()

# Build a simple model.

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

这是简单的TensorFlow训练循环:

# Build the training-relevant part of the graph.

model_output = model(features)

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.stop_gradient(labels), logits=model_output))

train_op = 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(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)

# Run the training

epochs = 3
steps_per_epoch = 1000

fetch_list = [mean_loss_value,
              acc_value,
              train_op,
              mean_loss_update_op,
              acc_update_op]

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(fetch_list, feed_dict={tf.keras.backend.learning_phase(): 1})

            tr.set_postfix(ordered_dict={'loss': ret[0],
                                         'accuracy': ret[1]})

下面是标准的Keras训练循环,可以正常运行。请注意,为了使Keras循环正常工作,需要将以上模型中的密集层的激活从None更改为“ softmax”。

epochs = 3
steps_per_epoch = 1000

model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

history = model.fit(dataset,
                    epochs=epochs,
                    steps_per_epoch=steps_per_epoch)

您可以下载Caltech256数据集here(约850 MB)的TFRecords。

更新:

我设法解决了这个问题:替换了低级TF损失函数

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.stop_gradient(labels), logits=model_output))

等效于Keras

loss = tf.reduce_mean(tf.keras.backend.categorical_crossentropy(target=labels, output=model_output, from_logits=True))

可以解决问题。现在,低级的TensorFlow训练循环的行为就像model.fit()

这提出了一个新问题:

tf.keras.backend.categorical_crossentropy()会做什么,tf.nn.softmax_cross_entropy_with_logits_v2()不会导致后者的表现更差吗? (我知道后者需要logit,而不是softmax输出,所以这不是问题)

2 个答案:

答案 0 :(得分:4)

替换低级TF损失功能

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.stop_gradient(labels), logits=model_output))

等效于Keras

loss = tf.reduce_mean(tf.keras.backend.categorical_crossentropy(target=labels, output=model_output, from_logits=True))

可以解决问题。现在,低级的TensorFlow训练循环的行为就像model.fit()

但是,我不知道为什么。如果有人知道为什么tf.keras.backend.categorical_crossentropy()表现不佳而tf.nn.softmax_cross_entropy_with_logits_v2()却根本不起作用,请发布答案。

另一个重要说明:

为了使用低级TF训练循环和tf.keras对象训练tf.data.Dataset模型,通常不应在迭代器输出上调用该模型。也就是说,不应该这样做:

model_output = model(features)

相反,应该创建一个模型,在该模型中将输入层设置为基于迭代器输出构建,而不是像这样创建占位符:

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

在此示例中这无关紧要,但是如果模型中的任何层具有在训练期间需要运行的内部更新(例如BatchNormalization),则变得有意义。

答案 1 :(得分:0)

您在最后一层应用softmax激活

x = tf.keras.layers.Dense(num_classes, activation='softmax', kernel_initializer='he_normal')(x)

使用时,您再次应用 softmax tf.nn.softmax_cross_entropy_with_logits_v2,因为它期望未缩放的logit。从文档中:

  

警告:此操作程序期望未缩放的logit,因为它执行softmax   在内部登录以提高效率。请勿使用   softmax的输出,因为它将产生错误的结果。

因此,删除最后一层的softmax激活,它应该可以工作。

x = tf.keras.layers.Dense(num_classes, activation=None, kernel_initializer='he_normal')(x)
[...]
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.stop_gradient(labels), logits=model_output))
相关问题