tensorflow dnn
时间: 2023-12-21 14:32:33 浏览: 235
以下是使用TensorFlow构建深度神经网络(DNN)进行图像分类的示例代码:
```python
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 加载MNIST数据集
mnist = input_data.read_data_sets("/tmp/data/")
# 定义输入和输出的占位符
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
# 定义DNN的结构
hidden1 = tf.layers.dense(inputs=x, units=256, activation=tf.nn.relu)
hidden2 = tf.layers.dense(inputs=hidden1, units=256, activation=tf.nn.relu)
output = tf.layers.dense(inputs=hidden2, units=10)
# 定义损失函数和优化器
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)
# 定义准确率评估指标
correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 训练模型
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
if epoch % 100 == 0:
acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
print("Epoch:", epoch, "Accuracy:", acc)
# 使用训练好的模型进行预测
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver = tf.train.import_meta_graph('/tmp/model.ckpt.meta')
saver.restore(sess, "/tmp/model.ckpt")
test_image = mnist.test.images[0]
prediction = sess.run(output, feed_dict={x: [test_image]})
predicted_label = tf.argmax(prediction, 1).eval()
print("Predicted Label:", predicted_label)
```
这段代码使用MNIST数据集训练了一个简单的DNN模型,并在每个epoch结束时计算了模型在测试集上的准确率。最后,使用训练好的模型对测试集中的一张图像进行预测,并输出预测结果。
阅读全文