如何使用 Tensorflow 创建输入函数来训练模型?

tensorflowserver side programmingprogramming更新于 2025/5/21 11:22:17

可以使用‘from_tensor_slices’在 Tensorflow 中创建用于训练或评估模型的输入函数方法并创建鸢尾花数据集特征字典。

阅读更多: 什么是 TensorFlow,以及 Keras 如何与 TensorFlow 配合使用来创建神经网络?

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

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

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

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

示例

print("Input function that is used to train or evaluate")
def input_fn(features, labels, training=True, batch_size=256):
   dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))
   if training:
      dataset = dataset.shuffle(1000).repeat()
   return dataset.batch(batch_size)

输出

Input function that is used to train or evaluate

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

解释

  • 输入函数可能会生成特征字典和标签列表。

  • 使用 pandas 加载数据,并根据内存数据构建输入管道


相关文章