深度神经网络实现手写数据集识别完整代码
时间: 2023-12-05 17:03:55 浏览: 33
以下是使用深度神经网络实现手写数字识别的 Python 代码,使用的是 TensorFlow 框架:
```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)
# 定义输入和输出的占位符
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)
# 定义准确率计算方法
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 初始化变量
init = tf.global_variables_initializer()
# 启动会话
with tf.Session() as sess:
sess.run(init)
# 迭代训练
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})
# 每隔100步输出一次准确率
if i % 100 == 0:
acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})
print("Step %d, accuracy: %f" % (i, acc))
```
在上面的代码中,我们首先加载了 MNIST 数据集,并使用 `tf.placeholder` 定义了输入和输出的占位符。然后,我们定义权重和偏置变量,并使用 `tf.nn.softmax` 定义了模型。接着,我们使用交叉熵损失函数和梯度下降优化器进行训练,并使用 `tf.equal` 和 `tf.reduce_mean` 定义了准确率计算方法。最后,我们在会话中初始化变量并进行训练,每隔100步输出一次准确率。