基于TensorFlow使用LeNet-5实现对MNIST手写数字识别分类代码
时间: 2024-02-25 14:57:06 浏览: 153
好的,以下是基于TensorFlow使用LeNet-5实现对MNIST手写数字识别分类的代码。
```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)
# 定义输入和输出占位符
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
# 将输入数据reshape成28x28的图像
x_image = tf.reshape(x, [-1, 28, 28, 1])
# 第一层卷积层
W_conv1 = tf.Variable(tf.truncated_normal([5, 5, 1, 6], stddev=0.1))
b_conv1 = tf.Variable(tf.constant(0.1, shape=[6]))
h_conv1 = tf.nn.relu(tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], padding='VALID') + b_conv1)
# 第一层池化层
h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# 第二层卷积层
W_conv2 = tf.Variable(tf.truncated_normal([5, 5, 6, 16], stddev=0.1))
b_conv2 = tf.Variable(tf.constant(0.1, shape=[16]))
h_conv2 = tf.nn.relu(tf.nn.conv2d(h_pool1, W_conv2, strides=[1, 1, 1, 1], padding='VALID') + b_conv2)
# 第二层池化层
h_pool2 = tf.nn.max_pool(h_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# 将第二层池化层的输出reshape成一维向量
h_pool2_flat = tf.reshape(h_pool2, [-1, 5*5*16])
# 第一层全连接层
W_fc1 = tf.Variable(tf.truncated_normal([5*5*16, 120], stddev=0.1))
b_fc1 = tf.Variable(tf.constant(0.1, shape=[120]))
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# 第二层全连接层
W_fc2 = tf.Variable(tf.truncated_normal([120, 84], stddev=0.1))
b_fc2 = tf.Variable(tf.constant(0.1, shape=[84]))
h_fc2 = tf.nn.relu(tf.matmul(h_fc1, W_fc2) + b_fc2)
# 输出层
W_fc3 = tf.Variable(tf.truncated_normal([84, 10], stddev=0.1))
b_fc3 = tf.Variable(tf.constant(0.1, shape=[10]))
y_conv = tf.matmul(h_fc2, W_fc3) + b_fc3
# 计算损失函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=y_conv))
# 使用Adam算法最小化损失函数
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# 计算模型在测试集上的准确率
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 初始化变量
init = tf.global_variables_initializer()
# 训练模型
with tf.Session() as sess:
sess.run(init)
for i in range(20000):
batch = mnist.train.next_batch(50)
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict={x: batch[0], y: batch[1]})
print("step %d, training accuracy %g" % (i, train_accuracy))
train_step.run(feed_dict={x: batch[0], y: batch[1]})
print("test accuracy %g" % accuracy.eval(feed_dict={x: mnist.test.images, y: mnist.test.labels}))
```
以上代码实现了一个简单的LeNet-5模型对MNIST手写数字进行分类。在训练过程中,每100个步骤会输出一次训练集的准确率,最终输出测试集的准确率。
阅读全文