Tensorflow - Estimator入门

1. Estimator作用

Estimator的核心想法就是:把工作网络封装成一个,训练、评估、预测都是类方法

在这种封装里面,首先隐藏了网络结构,对于程序运行者,只需要考虑输入输出。同时,包含了对参数数据的保存、对训练状态的保存,使得训练过程可复现,可追溯。

Estimator 是 TensorFlow 中的高阶 API。它会处理 initialization、logging、saving、restoring 等细节,以便研究人员专注于模型。Estimator API 中有不少的内置 Estimator。当然,除了这些内置 Estimator,你可以自定义 Estimator。推荐在解决问题时将内置 Estimator 作为一个 baseline。


 

2. 使用Estimator的两种方法

2.1 使用内置Estimator 

使用内置 Estimator 解决问题时,一般遵循以下流程:

创建一个或多个输入函数。
定义模型的 feature columns。
实例化 Estimator,指定 feature columns 和各种超参数。
调用 Estimator 对象的一个或多个方法,传递合适的输入函数作为数据源。

https://blog.csdn.net/u014061630/article/details/82812507 (highly recommend)

使用内置 Estimator 的 TF 程序一般包含以下四步:

1. 编写一个或多个数据集导入函数。

例如:创建一个函数来导入训练数据集,另一个函数来导入测试数据集。每一个数据集导入函数必须返回两个对象:

  • 一个字典。字典的键名为特征的名字,键值为 表示特征数据的 Tensor 或 Sparse Tensor。
  • 一个 Tensor。该 Tensor 包含一个或多个 label。

2. 定义 feature columns。

每一个 tf.feature_column 定义了一个 feature 的名字、类型、预处理。例如,下面的代码片段定义了三个 feature columns 来 Hold 整数、浮点 类型的数据。前两个 feature columns 只是简单的定义了特征的名字和类型。第三个 feature column 还使用了一个 lambda 函数来缩放原始数据。

3.实例化相应的内置 Estimator。

4.调用一个 training、evaluation、inference 方法。

https://blog.csdn.net/u014061630/article/details/82384853

 推荐使用 TensorFlow 的 Dataset API,它可以解析各种数据。

detailed introduction:  https://blog.csdn.net/u014061630/article/details/82812507

2.2 自定义 Estimator

https://blog.csdn.net/u014061630/article/details/83013435  (highly recommend)

There are also several examples.

e.g.1  (highly recommend)

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('D:/vsCode_tensorflow/PKU_TF/PKU_TF_shuzi/data2', one_hot=False)
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

# TensorFlow-Examples/neural_network.ipynb at master · aymericdamien/TensorFlow-Examples
# https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/3_NeuralNetworks/neural_network.ipynb

learning_rate = 0.1
num_steps = 1000
batch_size = 128
display_step = 100

# Network Parameters
n_hidden_1 = 256 # 1st layer number of neurons
n_hidden_2 = 256 # 2nd layer number of neurons
num_input = 784 # MNIST data input (img shape: 28*28)
num_classes = 10 # MNIST total classes (0-9 digits)

# Define the input function for training
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': mnist.train.images}, y=mnist.train.labels, batch_size=batch_size, num_epochs=None, shuffle=True)


# Define the neural network
def neural_net(x_dict):
    # TF Estimator input is a dict, in case of multiple inputs
    x = x_dict['images']
    # Hidden fully connected layer with 256 neurons
    layer_1 = tf.layers.dense(x, n_hidden_1)
    # Hidden fully connected layer with 256 neurons
    layer_2 = tf.layers.dense(layer_1, n_hidden_2)
    # Output fully connected layer with a neuron for each class
    out_layer = tf.layers.dense(layer_2, num_classes)
    return out_layer


# Define the model function (following TF Estimator Template)
def model_fn(features, labels, mode):
    # Build the neural network
    logits = neural_net(features)

    # Predictions
    pred_classes = tf.argmax(logits, axis=1)
    pred_probas = tf.nn.softmax(logits)

    # If prediction mode, early return
    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)

    # Define loss and optimizer
    loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits, labels=tf.cast(labels, dtype=tf.int32)))
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
    train_op = optimizer.minimize(loss_op, global_step=tf.train.get_global_step())

    # Evaluate the accuracy of the model
    acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)

    # TF Estimators requires to return a EstimatorSpec, that specify
    # the different ops for training, evaluating, ...
    estim_specs = tf.estimator.EstimatorSpec(
        mode=mode,
        predictions=pred_classes,
        loss=loss_op,
        train_op=train_op,
        eval_metric_ops={'accuracy': acc_op})

    return estim_specs


# Build the Estimator
model = tf.estimator.Estimator(model_fn)


# Train the Model
model.train(input_fn, steps=num_steps)

# Evaluate the Model
# Define the input function for evaluating
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': mnist.test.images}, y=mnist.test.labels,
    batch_size=batch_size, shuffle=False)
# Use the Estimator 'evaluate' method
model.evaluate(input_fn)


# Predict single images
n_images = 4
# Get images from test set
test_images = mnist.test.images[:n_images]
# Prepare the input data
input_fn = tf.estimator.inputs.numpy_input_fn(x={'images': test_images}, shuffle=False)
# Use the model to predict the images class
preds = list(model.predict(input_fn))

# Display
for i in range(n_images):
    plt.imshow(np.reshape(test_images[i], [28, 28]), cmap='gray')
    plt.show()
    print("Model prediction:", preds[i])

e.g. 2

The following blog shows how to use the Estimator API. This example is similar to the previous one, but more complex.

tensorflow estimator使用总结_未来战警-CSDN博客
https://blog.csdn.net/wwangfabei1989/article/details/90516318

https://github.com/AlbertBJ/estimator/blob/master/estimator.ipynb 

References:

TensorFlow Estimator 中文官方文档_黑暗星球-CSDN博客

https://blog.csdn.net/u014061630/article/details/83049781

TensorFlow Estimator 官方文档之----内置Estimator_黑暗星球-CSDN博客

https://blog.csdn.net/u014061630/article/details/82812507

TensorFlow Estimator 官方文档之----自定义Estimator_黑暗星球-CSDN博客

https://blog.csdn.net/u014061630/article/details/83013435

TensorFlow Estimator 教程之----快速入门_黑暗星球-CSDN博客

https://blog.csdn.net/u014061630/article/details/82384853

Tensorflow之Estimator初探_New hope-CSDN博客

https://blog.csdn.net/weixin_31767897/article/details/79356651

发布了18 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Zhou_Dao/article/details/103931777