TensorFlow基于卷积神经网络的手写数字图像识别代码实现
时间: 2023-09-24 15:05:49 浏览: 107
这是一个基于TensorFlow框架实现的手写数字图像识别代码,使用的是卷积神经网络(CNN)模型。
首先,导入需要的库:
```
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
```
然后,定义一些常量和超参数:
```
learning_rate = 0.001
training_epochs = 15
batch_size = 100
n_classes = 10
dropout = 0.75
# 输入数据的维度
n_input = 784 # 28*28
```
接着,定义占位符:
```
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32)
```
定义卷积层和池化层函数:
```
def conv2d(x, W, b, strides=1):
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
def maxpool2d(x, k=2):
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')
```
接下来,定义卷积神经网络模型:
```
def conv_net(x, weights, biases, dropout):
x = tf.reshape(x, shape=[-1, 28, 28, 1])
# 第一层卷积层
conv1 = conv2d(x, weights['wc1'], biases['bc1'])
conv1 = maxpool2d(conv1, k=2)
# 第二层卷积层
conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
conv2 = maxpool2d(conv2, k=2)
# 全连接层
fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
fc1 = tf.nn.relu(fc1)
fc1 = tf.nn.dropout(fc1, dropout)
# 输出层
out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
return out
```
然后,初始化权重和偏置:
```
weights = {
'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),
'out': tf.Variable(tf.random_normal([1024, n_classes]))
}
biases = {
'bc1': tf.Variable(tf.random_normal([32])),
'bc2': tf.Variable(tf.random_normal([64])),
'bd1': tf.Variable(tf.random_normal([1024])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
```
接着,定义损失函数和优化器:
```
pred = conv_net(x, weights, biases, keep_prob)
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)
```
定义评估模型的准确率函数:
```
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
```
最后,训练模型:
```
mnist = input_data.read_data_sets('/tmp/data/', one_hot=True)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# 训练循环
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# 遍历所有批次(batch)
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
# 运行优化器
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y, keep_prob: dropout})
# 计算损失值
avg_cost += sess.run(cost, feed_dict={x: batch_x, y: batch_y, keep_prob: 1.}) / total_batch
# 显示每一轮训练的结果
if epoch % 1 == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
# 计算测试数据的准确率
print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.}))
```
这样,一个基于TensorFlow框架实现的手写数字图像识别代码就完成了。
阅读全文