上篇简单的梳理了tensorflow的流程,这次使用api同样对mnist做识别,很简单的结构,识别率也不高,简单的梳理一下api主要是estimator和layers的使用。代码记录一下。
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
tf.logging.set_verbosity(tf.logging.ERROR)
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('../data/mnist/', one_hot=False)
learning_rate = 0.1
num_steps = 1000
batch_size = 128
display_step = 100
n_hidden_1 = 256
n_hidden_2 = 256
num_inputs = 784
num_classes = 10
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
)
def neural_net(x_dict):
x = x_dict['images']
layer_1 = tf.layers.dense(x, n_hidden_1)
layer_2 = tf.layers.dense(layer_1, n_hidden_2)
out_layer = tf.layers.dense(layer_2, num_classes)
return out_layer
def model_fn(features, labels, mode):
logits = neural_net(features)
pred_classes = tf.argmax(logits, 1)
pred_probas = tf.nn.softmax(logits)
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)
# tf.cast:将x的数据格式转化成dtype
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())
acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)
estim_specs = tf.estimator.EstimatorSpec(
mode=mode,
predictions=pred_classes,
loss=loss_op,
train_op=train_op,
eval_metric_ops={'accuravy':acc_op}
)
return estim_specs
is_train = False
# 定义model_dir之后,每次 train、eval 或 predict 方法时,Estimator 根据最近写入的检查点中存储的数据来初始化新模型的权重
model = tf.estimator.Estimator(model_fn, model_dir='../model/sample_nn2/')
model.train(input_fn, steps=num_steps)
input_fn = tf.estimator.inputs.numpy_input_fn(
x={'images':mnist.test.images}, y=mnist.test.labels,
batch_size=batch_size, shuffle=False
)
print(model.evaluate(input_fn))
n_images = 4
test_images = mnist.test.images[:n_images]
input_fn = tf.estimator.inputs.numpy_input_fn(
x={'images':test_images}, shuffle=False
)
preds = list(model.predict(input_fn))
for i in range(n_images):
plt.imshow(np.reshape(test_images[i], [28, 28]), cmap='gray')
plt.show()
print('Model prediction', preds[i])