dnn手写数字识别代码
时间: 2023-08-06 22:16:18 浏览: 167
以下是基于Python和TensorFlow的手写数字识别的DNN代码实现:
```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.1
num_epochs = 50
batch_size = 128
display_step = 1
# 定义输入输出占位符
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
# 定义网络参数
n_hidden_1 = 256
n_hidden_2 = 256
n_input = 784
n_classes = 10
# 定义隐藏层和输出层的权重和偏置项
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# 定义DNN模型
def neural_net(x):
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
layer_1 = tf.nn.relu(layer_1)
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.relu(layer_2)
out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
return out_layer
# 定义损失函数和优化器
logits = neural_net(x)
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# 定义模型评估函数
correct_pred = tf.equal(tf.argmax(logits, 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)
for epoch in range(num_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples / batch_size)
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
_, c = sess.run([train_op, loss_op], feed_dict={x: batch_x, y: batch_y})
avg_cost += c / total_batch
if epoch % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost))
print("Optimization Finished!")
# 计算测试集的准确率
print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
```
在上述代码中,我们首先导入MNIST数据集,然后定义了超参数和输入输出占位符。接着定义了隐藏层和输出层的权重和偏置项,并且定义了DNN模型和损失函数。最后,我们使用Adam优化器训练模型,并且计算测试集的准确率。
阅读全文