lenet5手写数字识别代码
时间: 2023-09-02 11:10:04 浏览: 93
以下是使用TensorFlow实现的LeNet-5手写数字识别代码:
```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.001
training_iters = 20000
batch_size = 128
display_step = 10
# 定义网络参数
n_input = 784 # MNIST数据输入(img shape: 28*28)
n_classes = 10 # MNIST总共有10个分类
dropout = 0.75 # Dropout, probability to keep units
# 占位符定义
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):
# 将输入转换为28x28大小的图像
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)
# 使用Dropout减少过拟合
fc1 = tf.nn.dropout(fc1, dropout)
# 输出层,使用softmax进行分类
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))
# 初始化变量
init = tf.global_variables_initializer()
# 开始训练
with tf.Session() as sess:
sess.run(init)
step = 1
# 训练直到达到指定的训练次数
while step * batch_size < training_iters:
batch_x, batch_y = mnist.train.next_batch(batch_size)
# 运行优化器进行训练
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y, keep_prob: dropout})
if step % display_step == 0:
# 计算损失和准确率
loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x, y: batch_y, keep_prob: 1.})
print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc))
step += 1
print("Optimization Finished!")
# 计算测试集上的准确率
print("Testing Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images[:256], y: mnist.test.labels[:256], keep_prob: 1.}))
```
运行该代码可以训练一个LeNet-5模型,并在测试集上进行验证。
阅读全文