如何使用Estimators在Python中使用Tensorflow评估模型?

如何使用Estimators在Python中使用Tensorflow评估模型?

Tensorflow 可以与 Estimators 一起使用,利用 classifier 模块中的 ‘evaluate’ 方法来评估模型。

更多Python相关文章,请阅读:Python 教程

我们将使用 Keras Sequential API 来建立一个顺序模型,该模型用于处理一系列层,每个层都有一个输入张量和一个输出张量。

至少包含一个层的神经网络被称为卷积层。我们可以使用卷积神经网络来构建学习模型。

TensorFlow Text 包含与 TensorFlow 2.0 一起使用的一组文本相关的类和操作。TensorFlow Text 可用于预处理序列建模。

我们将使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 有助于在浏览器上运行 Python 代码,需要零配置,并具有免费访问GPU(图形处理单元)。

Estimator 是 TensorFlow 的完整模型的高级表示。它旨在易于扩展和异步训练。

该模型是使用 iris 数据集进行训练的。

例子

eval_result = classifier.evaluate(input_fn=lambda: input_fn(test, test_y, training=False))
print('\nTest dataset accuracy is: {accuracy:0.3f}\n'.format(**eval_result))

代码来源: https://www.tensorflow.org/tutorials/estimator/premade#first_things_first

输出

INFO:tensorflow:Calling model_fn.
WARNING:tensorflow:Layer dnn is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2. The layer has dtype float32 because its dtype defaults to floatx.
If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this warning is likely only an issue if you are porting a TensorFlow 1.X model to TensorFlow 2.
To change all layers to have dtype float64 by default, call `tf.keras.backend.set_floatx('float64')`. To change just this layer, pass dtype='float64' to the layer constructor. If you are the author of this layer, you can disable autocasting by passing autocast=False to the base Layer constructor.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Starting evaluation at 2020-09-10T01:40:47Z
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmp/tmpbhg2uvbr/model.ckpt-5000
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Inference Time : 0.21153s
INFO:tensorflow:Finished evaluation at 2020-09-10-01:40:47
INFO:tensorflow:Saving dict for global step 5000: accuracy = 0.96666664, average_loss = 0.42594802, global_step = 5000, loss = 0.42594802
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 5000: /tmp/tmpbhg2uvbr/model.ckpt-5000
Test dataset accuracy is: 0.967

说明

  • 一旦模型训练完毕,可以获得有关性能的一些信息。

  • ‘evalue’函数没有传递任何参数。

  • eval的input_fn只产生单个周期的数据。

  • eval_result字典包含的是average_loss(每个样本的平均损失)、loss(每个小批次的平均损失)和估计量的global_step(它所经历的训练次数)的值。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程