TensorFlow基础教程:搭建简单的DNN实现手写数字识别

利用TensorFlow逐步实现DNN算法,并用MNIST数据集测试。
TensorFlow:官网
MNIST介绍:数据集

TensorFlow版本1.4.0
python版本>3.5

1.载入MNIST数据集

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

2.定义参数

import tensorflow as tf
learning_rate = 0.001
train_epochs = 20
batch_size = 64

3.定义3层网络结构单元个数

n_input = 784
n_hidden1 = 100
n_hidden2 = 100
n_classes = 10

4.定义网络输入参数(x,y)占位符

x = tf.placeholder(tf.float32, shape=[None, n_input])
y = tf.placeholder(tf.float32, shape=[None, n_classes])

5.定义3层网络的参数(权重w与偏置b)

weights = {'h1': tf.Variable(tf.random_normal([n_input, n_hidden1])),
           'h2': tf.Variable(tf.random_normal([n_hidden1, n_hidden2])),
           'out': tf.Variable(tf.random_normal([n_hidden2, n_classes]))}

biases = {'b1': tf.Variable(tf.random_normal([n_hidden1])),
          'b2': tf.Variable(tf.random_normal([n_hidden2])),
          'out': tf.Variable(tf.random_normal([n_classes]))}

6.定义前向推断过程

def inference(input_x):
    layer_1 = tf.nn.relu(tf.matmul(x, weights['h1']) + biases['b1'])
    layer_2 = tf.nn.relu(tf.matmul(layer_1, weights['h2']) + biases['b2'])
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    return out_layer

7.构建网络

logits = inference(x)
prediction = tf.nn.softmax(logits)

8.定义损失函数与优化器

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss)

9.定义评价指标(准确度)

pre_correct = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))
accuracy = tf.reduce_mean(tf.cast(pre_correct, tf.float32))

10.初始化所有变量

init = tf.global_variables_initializer()

11.开始训练

with tf.Session() as sess:
    sess.run(init)
    total_batch = int(mnist.train.num_examples / batch_size)

    for epoch in range(train_epochs):
        for batch in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            sess.run(train_op, feed_dict={x:batch_x, y:batch_y})

        if epoch % 10 == 0:
            loss_, acc = sess.run([loss, accuracy], feed_dict={x:batch_x, y:batch_y})
            print("epoch {},  loss {:.4f}, acc {:.3f}".format(epoch, loss_, acc))

    print("optimizer finished!")

    #计算测试集的准确度 
    test_acc = sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels})
    print('test accuracy', test_acc)

20轮训练后,准确度大概为93.33%, 还不错

github源码下载
https://github.com/gamersover/tensorflow_basic_tutorial/blob/master/basic_model/mlp_mnist.py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值