tensorflow学习2

        上篇简单的梳理了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])

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值