如何使用 Estimator 在 TensorFlow 中从训练好的模型进行预测?


Tensorflow 可以与 estimator 配合使用,通过 `classifier` 方法中的 `predict` 方法对新数据进行输出预测。

阅读更多: 什么是 TensorFlow 以及 Keras 如何与 TensorFlow 协作创建神经网络?

我们将使用 Keras Sequential API,它有助于构建一个顺序模型,该模型用于处理简单的层堆栈,其中每一层都只有一个输入张量和一个输出张量。

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

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

我们正在使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 帮助在浏览器上运行 Python 代码,无需任何配置,并且可以免费访问 GPU(图形处理单元)。Colaboratory 是基于 Jupyter Notebook 构建的。

Estimator 是 TensorFlow 中对完整模型的高级表示。它旨在简化扩展和异步训练。

该模型使用鸢尾花数据集进行训练。该数据集有 4 个特征和 1 个标签。

  • 萼片长度
  • 萼片宽度
  • 花瓣长度
  • 花瓣宽度

示例

print(“Generating predictions from model”)
expected = ['Setosa', 'Versicolor', 'Virginica']
predict_x = {
   'SepalLength': [5.1, 5.9, 6.9],
   'SepalWidth': [3.3, 3.0, 3.1],
   'PetalLength': [1.7, 4.2, 5.4],
   'PetalWidth': [0.5, 1.5, 2.1],
}
print(“Defining input function for prediction”)
print(“It converts inputs to dataset without labels”)
def input_fn(features, batch_size=256):
return tf.data.Dataset.from_tensor_slices(dict(features)).batch(batch_size)
predictions = classifier.predict(
   input_fn=lambda: input_fn(predict_x))

代码来源 - https://tensorflowcn.cn/tutorials/estimator/premade#first_things_first

输出

Generating predictions from model
Defining input function for prediction
It converts inputs to dataset without labels

解释

  • 训练好的模型将产生良好的结果。
  • 这可以用来根据某些未标记的测量值预测鸢尾花的种类。
  • 预测是通过单个函数调用完成的。

更新于: 2021年2月22日

200 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.