基于tensorflow手写数字识别构建三层神经网络的代码
时间: 2023-11-14 15:19:35 浏览: 95
以下是基于TensorFlow实现手写数字识别的三层神经网络代码,供您参考:
```python
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 读取MNIST数据集
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 定义网络超参数
learning_rate = 0.01
training_epochs = 100
batch_size = 100
display_step = 1
# 定义网络参数
n_hidden_1 = 256
n_hidden_2 = 256
n_input = 784
n_classes = 10
# 定义占位符
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])
# 定义权重和偏置变量
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
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]))
}
# 定义三层神经网络的模型
def multilayer_perceptron(x):
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
layer_1 = tf.nn.relu(layer_1)
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.relu(layer_2)
out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
return out_layer
# 定义损失函数和优化器
pred = multilayer_perceptron(x)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# 初始化变量
init = tf.global_variables_initializer()
# 开始训练模型
with tf.Session() as sess:
sess.run(init)
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
avg_cost += c / total_batch
if epoch % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
print("Optimization Finished!")
# 测试模型
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
```
代码中首先读取MNIST数据集,并定义网络的超参数和参数,包括输入层784个节点,两个隐藏层分别有256个节点,输出层10个节点等。接着定义了占位符、权重和偏置变量,以及三层神经网络的模型和损失函数、优化器。然后初始化变量,并开始训练模型。最后测试模型,并计算准确率。
阅读全文