Tensorflow 如何结合 Estimator 来转换特征列?

tensorflowserver side programmingprogramming更新于 2025/5/20 3:22:17

Tensorflow 可以结合 Estimator 来转换特征列,首先将数据集的第一行转换为字典,然后使用独热编码来转换此特征列,即‘性别’列。

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

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

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

我们使用 Google Colaboratory 运行以下代码。Google Colab 或 Colaboratory 有助于在浏览器上运行 Python 代码,无需配置,可以免费访问 GPU(图形处理单元)。Colaboratory 建立在 Jupyter Notebook 之上。

估算器是 TensorFlow 对完整模型的高级表示。它旨在轻松扩展和异步训练。估算器使用特征列来描述模型如何解释原始输入特征。估算器需要数字输入向量,而特征列将有助于描述模型应如何转换数据集中的每个特征。

选择和使用正确的特征列集对于学习有效的模型至关重要。

示例

print("An example transformation produced by a feature column")
example = dict(dftrain.head(1))
class_fc = tf.feature_column.indicator_column(tf.feature_column.categorical_column_with_vocabulary_list('class', ('First', 'Second', 'Third')))
print('Feature value is: "{}"'.format(example['class'].iloc[0]))
print('One-hot encoded is: ', tf.keras.layers.DenseFeatures([class_fc])(example).numpy())

代码来源 −https://www.tensorflow.org/tutorials/estimator/boosted_trees

输出

An example transformation produced by a feature column
Feature value is: "Third"
One-hot encoded is: [[0. 0. 1.]]

解释

  • 可以看到特征列产生的转换。

  • 可以在控制台上查看单个示例上的 indicator_column 的输出。


相关文章