tensorflow学习笔记(2):创建自定义Estimator

本文档介绍了如何创建自定义的TensorFlow Estimator,包括编写输入函数、创建特征列、定义模型函数以及实现训练、评估和预测。通过实例详细阐述了从构建输入管道、定义特征列到构建神经网络模型的全过程。
摘要由CSDN通过智能技术生成

详细教程:https://www.tensorflow.org/get_started/custom_estimators
预创建的 Estimator 是 tf.estimator.Estimator 基类的子类,而自定义 Estimator 是 tf.estimator.Estimator 的实例:
预创建的 Estimator 和自定义 Estimator 都是 Estimator。
模型函数(即 model_fn)会实现机器学习算法。采用预创建的 Estimator 和自定义 Estimator 的唯一区别是:

  • 如果采用预创建的 Estimator,则有人已为您编写了模型函数。
  • 如果采用自定义 Estimator,则您必须自行编写模型函数。

步骤

  • 编写输入函数
  • 创建特征列
  • 编写模型函数
  • 定义模型
  • 实现训练、评估和预测

#1. 编写输入函数

def train_input_fn(features, labels, batch_size):
    """An input function for training"""
    # Convert the inputs to a Dataset.
    dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))

    # Shuffle, repeat, and batch the examples.
    dataset = dataset.shuffle(1000).repeat().batch(batch_size)

    # Return the read end of the pipeline.
    return dataset.make_one_shot_iterator().get_next()

此输入函数会构建可以生成批次 (features, labels) 对的输入管道,其中 features 是字典特征。
#2. 创建特征列
定义模型的特征列来指定模型应该如何使用每个特征。
以下代码为每个输入特征创建一个简单的 numeric_column,表示应该将输入特征的值直接用作模型的输入:

# Feature columns describe how to use the input.
my_feature_columns = []
for key in train_x.keys():
    my_feature_columns.append(tf.feature_column.numeric_column(key=key))

#3. 编写模型函数
我们要使用的模型函数具有以下调用签名:

def my_model_fn(
   features, # This is batch_features from input_fn
   labels,   # This is batch_labels from
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值