以mnist数据集为例,建立双隐层神经网络模型。
导入相关包
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
加载数据集
print('Download and Extract MNIST dataset')
mnist = input_data.read_data_sets('data/', one_hot=True)
print('MNIST loaded')
建立双隐层神经网络
双隐层神经网络:input_layer, layer_1, larer_2, output_layer
神经网络模型架构
# NETWORK TOPOLOGIES
n_hidden_1 = 256 # 第一个隐藏层神经元
n_hidden_2 = 128 # 第二个隐藏层神经元
n_inupt = 784 # 输入层神经元
n_classes = 10 # 输出层神经元
# INPUTS AND OUTPUTS
x = tf.placeholder('float', [None, n_inupt])
y = tf.placeholder('float', [None, n_classes])
# NETWORK PARAMETERS,参数初始化
stddev = 0.1
weights = {
'w1': tf.Variable(tf.random_normal([n_inupt, n_hidden_1], stddev=stddev)),
'w2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev=stddev)),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes], stddev=stddev)),
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes])),
}
print("NETWORK READY")
前向传播
# 前向传播
def multilayer_perceptron(_X, _weights, _biases):
layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weights['w1']), _biases['b1']))
layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, _weights['w2']), _biases['b2']))
return (tf.matmul(layer_2, _weights['out']) + _biases['out'])
# 前向传播 PREDICTION
pred = multilayer_perceptron(x, weights, biases)
反向传播
# 反向传播 COST AND OPTIMIZER
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optm = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(cost)
corr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accr = tf.reduce_mean(tf.cast(corr, 'float'))
全局初始化
# INITIALZER
init = tf.global_variables_initializer()
模型训练与预测
training_epochs = 100
batch_size = 100
display_step = 4
sess = tf.Session()
sess.run(init)
for epoch in range(training_epochs+1):
avg_cost = 0.
num_batch = int(mnist.train.num_examples/batch_size)
for i in range(num_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
feeds = {x: batch_xs, y: batch_ys}
sess.run(optm, feed_dict=feeds)
avg_cost += sess.run(cost, feed_dict=feeds)/num_batch
if epoch % display_step == 0:
feeds_train = {x: batch_xs, y: batch_ys}
feeds_test = {x: mnist.test.images, y: mnist.test.labels}
train_acc = sess.run(accr, feed_dict=feeds_train)
test_acc = sess.run(accr, feed_dict=feeds_test)
print("Epoch: %03d/%03d cost: %.9f train_acc: %.3f test_acc: %.3f"
% (epoch, training_epochs, avg_cost, train_acc, test_acc))
print('Done')
结果: