如何使用TensorFlow和Estimator定义用于数据集训练和评估的输入函数?
TensorFlow和Estimator可用于定义用于数据集训练和评估的输入函数,该函数使用特征和标签生成字典。这是使用“from_tensor_slices”方法实现的。此函数还将对数据集中数据进行混洗,并定义训练步骤的数量。最后,此函数将数据集的组合数据作为输出返回。此函数通过向其传递训练数据集来调用。
阅读更多: 什么是TensorFlow以及Keras如何与TensorFlow一起创建神经网络?
我们将使用Keras Sequential API,它有助于构建顺序模型,该模型用于处理简单的层堆栈,其中每一层只有一个输入张量和一个输出张量。
包含至少一层卷积层的神经网络称为卷积神经网络。我们可以使用卷积神经网络构建学习模型。
我们正在使用Google Colaboratory运行以下代码。Google Colab或Colaboratory有助于在浏览器上运行Python代码,无需任何配置,并可免费访问GPU(图形处理单元)。Colaboratory构建在Jupyter Notebook之上。
让我们了解如何使用 Estimators。
Estimator是TensorFlow对完整模型的高级表示。它旨在易于扩展和异步训练。
我们将使用tf.estimator API训练一个逻辑回归模型。该模型用作其他算法的基线。我们使用泰坦尼克号数据集,目标是根据性别、年龄、等级等特征预测乘客的生存情况。
Estimator使用特征列来描述模型如何解释原始输入特征。Estimator期望一个数值输入向量,特征列将有助于描述模型应该如何转换数据集中每个特征。
示例
print("The entire batch of dataset is used since it is small")
NUM_EXAMPLES = len(y_train)
print("Function that iterates through the dataset, in memory training")
def make_input_fn(X, y, n_epochs=None, shuffle=True):
def input_fn():
dataset = tf.data.Dataset.from_tensor_slices((dict(X), y))
if shuffle:
dataset = dataset.shuffle(NUM_EXAMPLES)
dataset = dataset.repeat(n_epochs)
dataset = dataset.batch(NUM_EXAMPLES)
return dataset
return input_fn
print("Training and evaluation input function have been defined")
train_input_fn = make_input_fn(dftrain, y_train)
eval_input_fn = make_input_fn(dfeval, y_eval, shuffle=False, n_epochs=1)代码来源 −https://tensorflowcn.cn/tutorials/estimator/boosted_trees
输出
The entire batch of dataset is used since it is small Function that iterates through the dataset, in memory training Training and evaluation input function have been defined
解释
- 需要创建输入函数。
- 它指定数据将如何读取到模型中以进行训练和推理。
- tf.data API中的from_tensor_slices方法用于直接从Pandas库读取数据。
- 这适用于较小的内存中数据集。
- 如果数据集很大,可以使用tf.data API,因为它支持各种文件格式。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP