python使用lenet5类实现手写数字识别
时间: 2023-12-13 11:05:00 浏览: 88
以下是一个基本的LeNet5实现,用于手写数字识别:
```python
import tensorflow as tf
class LeNet5:
def __init__(self):
self.x = tf.placeholder(tf.float32, shape=[None, 28, 28, 1])
self.y_ = tf.placeholder(tf.float32, shape=[None, 10])
self.keep_prob = tf.placeholder(tf.float32)
# Conv1
W_conv1 = self.weight_variable([5, 5, 1, 6])
b_conv1 = self.bias_variable([6])
h_conv1 = tf.nn.relu(self.conv2d(self.x, W_conv1) + b_conv1)
h_pool1 = self.max_pool_2x2(h_conv1)
# Conv2
W_conv2 = self.weight_variable([5, 5, 6, 16])
b_conv2 = self.bias_variable([16])
h_conv2 = tf.nn.relu(self.conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = self.max_pool_2x2(h_conv2)
# FC1
W_fc1 = self.weight_variable([7 * 7 * 16, 120])
b_fc1 = self.bias_variable([120])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 16])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, self.keep_prob)
# FC2
W_fc2 = self.weight_variable([120, 84])
b_fc2 = self.bias_variable([84])
h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
h_fc2_drop = tf.nn.dropout(h_fc2, self.keep_prob)
# Output
W_fc3 = self.weight_variable([84, 10])
b_fc3 = self.bias_variable([10])
self.y_conv = tf.matmul(h_fc2_drop, W_fc3) + b_fc3
# Train and evaluate
self.cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=self.y_, logits=self.y_conv))
self.train_step = tf.train.AdamOptimizer(1e-4).minimize(self.cross_entropy)
self.correct_prediction = tf.equal(tf.argmax(self.y_conv, 1), tf.argmax(self.y_, 1))
self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32))
def weight_variable(self, shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(self, shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(self, x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(self, x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
```
在使用该类进行手写数字识别时,需要进行以下步骤:
1. 导入MNIST数据集
```python
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
```
2. 创建LeNet5实例
```python
lenet5 = LeNet5()
```
3. 训练模型
```python
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(20000):
batch = mnist.train.next_batch(50)
if i % 100 == 0:
train_accuracy = lenet5.accuracy.eval(feed_dict={lenet5.x: batch[0], lenet5.y_: batch[1], lenet5.keep_prob: 1.0})
print("step %d, training accuracy %g" % (i, train_accuracy))
lenet5.train_step.run(feed_dict={lenet5.x: batch[0], lenet5.y_: batch[1], lenet5.keep_prob: 0.5})
print("test accuracy %g" % lenet5.accuracy.eval(feed_dict={lenet5.x: mnist.test.images, lenet5.y_: mnist.test.labels, lenet5.keep_prob: 1.0}))
```
4. 使用模型进行预测
```python
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# 训练模型
...
# 预测
prediction = tf.argmax(lenet5.y_conv, 1)
print(prediction.eval(feed_dict={lenet5.x: [image], lenet5.keep_prob: 1.0}))
```
其中,`image`是待预测的手写数字图像。
阅读全文