TensorFlow Estimator学习笔记(一)通过Estimator实现全连接神经网络(mnist数据集)

导入需要用到的包

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data

将 TensorFlow 日志信息输出到

tf.logging.set_verbosity(tf.logging.INFO)
mnist = input_data.read_data_sets("/path/to/MNIST_data", one_hot=False)

指定神经网络的输入层,所有这里指定的输入都会拼接在一起作为整个神经网络的输入

feature_columns = [tf.feature_column.numeric_column("image", shape=[784])]

estimator 定义神经网络,DNNClassifier只能定义全连接神经网络

estimator = tf.estimator.DNNClassifier(
    feature_columns=feature_columns,
    hidden_units=[500],
    n_classes=10,
    optimizer=tf.train.AdamOptimizer(),
    model_dir="/path/to/log")

定义数据输入,这里的x中需要给出所有的输入数据,因为上面的feature_columns只定义了一组输入,所以这里只需要指定一个就好。如果feature_columns中指定了多个,那么这里也要需要对每一个指定的输入提供数据。y中需要提供每一个x对于的正确答案。这里要求分类的结果是一个正整数。num_epoch指定了数据循环使用的轮数。比如在测试时可以将这个参数指定为1。batch_size指定了一个batch的大小。shuffle指定了是否需要对数据进行随机打乱

train_input_fn = tf.estimator.inputs.numpy_input_fn(
    x = {"image": mnist.train.images},
    y = mnist.train.labels.astype(np.int32),
    num_epochs = None,
    batch_size = 128,
    shuffle = True)

训练模型,注意这里没有指定损失函数,通过DNNClassifier定义的模型会使用交叉熵作为损失函数

estimator.train(input_fn=train_input_fn, steps=10000)

定义测试数据输入,指定的形式和训练时的数据输入基本一致

test_input_fn = tf.estimator.inputs.numpy_input_fn(
    x = {"image": mnist.test.images},
    y = mnist.test.labels.astype(np.int32),
    num_epochs = 1,
    batch_size =128,
    shuffle = False)

通过evaluate评测训练好的模型效果

accuracy_score = estimator.evaluate(input_fn=test_input_fn)["accuracy"]
print("\nTest accuracy: %g %%" % (accuracy_score*100))

训练过程:
TensorFlow Estimator学习笔记(一)通过Estimator实现全连接神经网络(mnist数据集)_第1张图片
输出结果:
TensorFlow Estimator学习笔记(一)通过Estimator实现全连接神经网络(mnist数据集)_第2张图片

你可能感兴趣的:(TensorFlow,Estimator学习笔记)