如何在Tensorflow中测试(不验证)估计量

时间:2018-09-17 08:28:31

标签: python tensorflow

我使用estimator API在tensorflow中创建模型。我已经训练并验证了模型,并在张量板上看到了训练过程。但是,我也想在训练中进行测试,因此我可以检查是否存在过度拟合的问题。到目前为止,我只能在培训后调用。有没有办法在培训期间使用使用另一组数据来现场检查培训?

这是我的代码:

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))

0 个答案:

没有答案