基于TensorFlow的CNN实现Mnist手写数字识别详细,带有可视化界面,中文注释
时间: 2024-05-04 21:20:43 浏览: 95
以下是基于TensorFlow实现的CNN代码,实现Mnist手写数字识别:
```python
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 导入数据
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])
# 将输入的一维向量转换成二维图像
x_image = tf.reshape(x, [-1, 28, 28, 1])
# 定义第一层卷积层
W_conv1 = tf.Variable(tf.truncated_normal([5, 5, 1, 32], stddev=0.1))
b_conv1 = tf.Variable(tf.constant(0.1, shape=[32]))
h_conv1 = tf.nn.relu(tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], padding='SAME') + b_conv1)
h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 定义第二层卷积层
W_conv2 = tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=0.1))
b_conv2 = tf.Variable(tf.constant(0.1, shape=[64]))
h_conv2 = tf.nn.relu(tf.nn.conv2d(h_pool1, W_conv2, strides=[1, 1, 1, 1], padding='SAME') + b_conv2)
h_pool2 = tf.nn.max_pool(h_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# 定义第一层全连接层
W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1024], stddev=0.1))
b_fc1 = tf.Variable(tf.constant(0.1, shape=[1024]))
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# 定义dropout层
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 定义第二层全连接层
W_fc2 = tf.Variable(tf.truncated_normal([1024, 10], stddev=0.1))
b_fc2 = tf.Variable(tf.constant(0.1, shape=[10]))
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
# 定义损失函数
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_conv), reduction_indices=[1]))
# 定义优化器
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()
# 创建会话
sess = tf.Session()
sess.run(init)
# 训练模型
for i in range(20000):
batch = mnist.train.next_batch(50)
if i % 100 == 0:
train_accuracy = accuracy.eval(session=sess, feed_dict={x: batch[0], y: batch[1], keep_prob: 1.0})
print('step %d, training accuracy %g' % (i, train_accuracy))
train_step.run(session=sess, feed_dict={x: batch[0], y: batch[1], keep_prob: 0.5})
# 评估模型
print('test accuracy %g' % accuracy.eval(session=sess, feed_dict={x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0}))
```
代码中首先导入了`input_data`模块用于读取Mnist数据集,然后定义了输入输出的占位符。接着将输入的一维向量转换成二维图像,并定义了两层卷积层和两层全连接层,其中第一层卷积层和第二层卷积层之间加入了池化层。在第一层全连接层后加入dropout层,以避免过拟合。最后定义损失函数、优化器和评估模型的准确率,并初始化变量和创建会话。在训练模型时,每次从数据集中取出50张图片进行训练,并在每训练100次后输出当前的训练准确率。最后评估模型的准确率。
阅读全文