首页 > 解决方案 > 如何在 Tensorflow 中测试(不验证)估计器

问题描述

我使用估计器 API 在 tensorflow 中创建模型。我已经训练并验证了一个模型,并在 tensorboard 中看到了训练过程。但是,我也想在训练期间进行测试,以便检查是否存在过度拟合。到目前为止,我只能在训练后调用评估函数。有没有办法在培训期间使用另一组数据,来现场检查培训情况?

这是我的代码:

def model_fn(features, labels, mode):
    # Build the neural network
    logits = neural_net(features)

    # Predictions
    pred_classes = tf.argmax(logits, axis=1)
    pred_probas = tf.nn.softmax(logits)

    # If prediction mode, early return
    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)

        # Define loss and optimizer
    loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits, labels=tf.cast(labels, dtype=tf.int32)))
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
    train_op = optimizer.minimize(loss_op, global_step=tf.train.get_global_step())

    # Evaluate the accuracy of the model
    acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)

    # TF Estimators requires to return a EstimatorSpec, that specify
    # the different ops for training, evaluating, ...
    estim_specs = tf.estimator.EstimatorSpec(
        mode=mode,
        predictions=pred_classes,
        loss=loss_op,
        train_op=train_op,
        eval_metric_ops={'accuracy': acc_op})

    return estim_specs


# Build the Estimator
model = tf.estimator.Estimator(model_fn,model_dir=models_path)
# Train the Model
model.train(input_fn, steps=num_steps)



# Evaluate the Model
# Define the input function for evaluating
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': testd}, y=testl,
    batch_size=batch_size, shuffle=False)
# Use the Estimator 'evaluate' method
print(model.evaluate(input_fn))

标签: pythontensorflow

解决方案


推荐阅读