TensorFlow实现MNIST多层感知机(MLP)

一、代码

# coding=utf-8
import tensorflow as tf
import tensorflow.contrib.layers as layers
from tensorflow.examples.tutorials.mnist import input_data

# 数据集
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

# 定义模型
n_classes = 10  # MNIST类别(0-9)
n_input = 784  # MNIST尺寸(28*28)

n_hidden = 30  # 隐藏层的神经元数
batch_size = 200  # 每批训练批量大小
eta = 0.001  # 学习率
max_epoch = 10  # 最大迭代数


def multilayer_perceptron(x):
    fc1 = layers.fully_connected(x, n_hidden, activation_fn=tf.nn.relu,
                                 scope='fc1')  # 全连接层,与输入相乘产生隐藏层单元的张量,隐藏层使用ReLU激活函数
    # fc2 = layers.fully_connected(fc1, 256, activation_fn=tf.nn.relu, scope='fc2')
    out = layers.fully_connected(fc1, n_classes, activation_fn=None, scope='out')
    return out


x = tf.placeholder(tf.float32, [None, n_input], name='placeholder_x')  # 输入x
y = tf.placeholder(tf.float32, [None, n_classes], name='placeholder_y')  # 标签y
y_hat = multilayer_perceptron(x)  # 多层感知机MLP

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_hat, labels=y))  # 损失函数,均方误差MSE
train = tf.train.AdamOptimizer(learning_rate=eta).minimize(loss)  # Adam梯度优化算法

# 训练
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(10):
        epoch_loss = 0.0
        batch_steps = int(mnist.train.num_examples / batch_size)
        for i in range(batch_steps):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            _, c = sess.run([train, loss], feed_dict={x: batch_x, y: batch_y})
            epoch_loss += c / batch_steps
        print('Epoch %d, Loss = %.6f' % (epoch, epoch_loss))

    # 评估
    correct_prediction = tf.equal(tf.argmax(y_hat, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print('Accuracy%:', accuracy.eval({x: mnist.test.images, y: mnist.test.labels}) * 100)

感知机:perceptron,具有学习能力的神经网络。
多层感知机:Multi-layer Perceptron。

二、结果

Accuracy%: 95.89999914169312

猜你喜欢

转载自blog.csdn.net/lly1122334/article/details/88231395