写一个DNN代码
时间: 2024-02-17 21:05:00 浏览: 20
以下是一个简单的DNN代码,用于分类MNIST数据集中的手写数字:
```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])
# 定义隐藏层
W1 = tf.Variable(tf.truncated_normal([784, 256], stddev=0.1))
b1 = tf.Variable(tf.zeros([256]))
hidden1 = tf.nn.relu(tf.matmul(x, W1) + b1)
# 定义输出层
W2 = tf.Variable(tf.truncated_normal([256, 10], stddev=0.1))
b2 = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(hidden1, W2) + b2)
# 定义损失函数和优化器
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))
# 训练模型
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})
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict={x: batch_xs, y_: batch_ys})
print("step %d, training accuracy %g"%(i, train_accuracy))
# 评估模型
test_accuracy = accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})
print("test accuracy %g"%test_accuracy)
```
这个DNN包括一个输入层(784个神经元)、一个隐藏层(256个神经元)和一个输出层(10个神经元)。使用交叉熵作为损失函数,使用梯度下降优化器进行训练。在训练完成后,使用测试集对模型进行评估。