利用TensorFlow实现识别手写数字
时间: 2023-11-30 18:04:29 浏览: 38
以下是一个简单的示例,使用TensorFlow来实现手写数字的识别:
1. 导入必要的库
```python
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
```
2. 加载MNIST数据集
```python
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
```
3. 构建模型
```python
x = tf.placeholder(tf.float32, [None, 784]) # 输入层
y_ = tf.placeholder(tf.float32, [None, 10]) # 输出层
W = tf.Variable(tf.zeros([784, 10])) # 权重
b = tf.Variable(tf.zeros([10])) # 偏置
y = tf.nn.softmax(tf.matmul(x, W) + b) # 模型输出
```
4. 定义损失函数和优化器
```python
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) # 交叉熵损失函数
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # 梯度下降优化器
```
5. 训练模型
```python
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
```
6. 评估模型
```python
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
```
完整代码如下:
```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])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
```
输出结果为识别准确率,大约为91%。