Tensorflow Estimator - 训练数据的高评估值

Tensorflow Estimator - High evaluation values on training data

我正在使用带有自定义 Estimator 的 Tensorflow 1.10。为了测试我的 training/evaluation 循环,我每次都将相同的 image/label 馈入网络,所以我希望网络能够快速收敛,它确实如此。

我也使用相同的图像进行评估,但得到的损失值比训练时大得多。训练 2000 步后损失为:

INFO:tensorflow:Loss for final step: 0.01181452

但计算结果为:

Eval loss at step 2000: 0.41252694

这对我来说似乎是错误的。它看起来与 this 线程中的问题相同。使用 Estimatorevaluate 方法时,有什么特别需要考虑的吗?


关于我的代码的更多细节:

我已经将我的模型 (FeatureNet) 定义为 here 作为 tf.keras.Modelinitcall 方法的继承。

我的 model_fn 看起来像这样:

def model_fn(features, labels, mode):

    resize_shape = (180, 320)
    num_dimensions = 16

    model = featurenet.FeatureNet(resize_shape, num_dimensions=num_dimensions)

    training = (mode == tf.estimator.ModeKeys.TRAIN)
    seg_pred = model(features, training)

    predictions = {
       # Generate predictions (for PREDICT mode)
       "seg_pred": seg_pred
    }
    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

    # Calculate Loss (for both TRAIN and EVAL modes)
    seg_loss = tf.reduce_mean(tf.keras.backend.binary_crossentropy(labels['seg_true'], seg_pred))
    loss = seg_loss

    # Configure the Training Op (for TRAIN mode)
    if mode == tf.estimator.ModeKeys.TRAIN:
        optimizer = tf.train.MomentumOptimizer(learning_rate=1e-4, momentum=0.9)

        train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())

        return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

    # Add evaluation metrics (for EVAL mode)
    return tf.estimator.EstimatorSpec(mode=mode, loss=loss)

然后在主要部分我使用自定义 Estimator 进行训练和评估:

# Create the Estimator
estimator = tf.estimator.Estimator(
    model_fn=model_fn,
    model_dir="/tmp/discriminative_model"
    )

def input_fn():
    features, labels = create_synthetic_image()

    training_data = tf.data.Dataset.from_tensors((features, labels))
    training_data = training_data.repeat(None)
    training_data = training_data.batch(1)
    training_data = training_data.prefetch(1)
    return training_data

estimator.train(input_fn=lambda: input_fn(), steps=2000)
eval_results = estimator.evaluate(input_fn=lambda: input_fn(), steps=50)
print('Eval loss at step %d: %s' % (eval_results['global_step'], eval_results['loss']))

其中 create_synthetic_image 每次创建相同的 image/label。

我发现 BatchNormalization 的处理会导致此类错误,如 here 所述。

control_dependenciesmodel-fn 中的使用为我 (see here) 解决了这个问题。

if mode == tf.estimator.ModeKeys.TRAIN:
    optimizer = tf.train.MomentumOptimizer(learning_rate=1e-4, momentum=0.9)

    with tf.control_dependencies(model.get_updates_for(features)):
        train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())

    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)