python - 如何在 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))
解决方案
推荐阅读
- python - 将熊猫数据框转换为 json 的最快方法是什么?
- java - 如何在 Xamarin 表单中为 BLE 拆分和发送 >20 字节的数据?
- linux - 中键不粘贴终端崇高文本3中的文本
- c++ - I2C 通信在 2 个 arduino 之间不起作用
- python - Python列表反转函数混淆
- typescript - 反射元数据“设计:参数类型”在 Deno 上返回未定义
- java - 在 Java Formatter 中禁用自动换行 - VSCODE
- firebase - 如何让 Firestore 索引合并工作?
- django - 如何使用 group by 并获取每个组中的每条记录?
- sapui5 - SAPUI5:sap.f.card 为基数为 0..1 的聚合定义的多个聚合的问题