python构建单隐层的神经网络实现MNIST数据集的分类任务。配置不同隐层结点数量、不同学习率、不同激活函数等网络参数观察分类准确率与总体均方误差。
以下是一个示例代码:
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 加载MNIST数据集
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 定义神经网络的参数
n_input = 784 # 输入层的节点数
n_hidden = 256 # 隐层的节点数
n_output = 10 # 输出层的节点数
learning_rate = 0.01
n_epochs = 20
batch_size = 100
# 定义输入和输出的placeholder
X = tf.placeholder(tf.float32, [None, n_input])
Y = tf.placeholder(tf.float32, [None, n_output])
# 定义隐层的权重和偏置
W1 = tf.Variable(tf.random_normal([n_input, n_hidden]))
b1 = tf.Variable(tf.random_normal([n_hidden]))
# 定义输出层的权重和偏置
W2 = tf.Variable(tf.random_normal([n_hidden, n_output]))
b2 = tf.Variable(tf.random_normal([n_output]))
# 定义隐层的输出和输出层的输出
hidden_output = tf.nn.sigmoid(tf.matmul(X, W1) + b1)
output = tf.matmul(hidden_output, W2) + b2
# 定义损失函数和优化器
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# 定义评估模型准确率的操作
correct_pred = tf.equal(tf.argmax(output, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# 在Session中训练和测试模型
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
n_batches = int(mnist.train.num_examples / batch_size)
for epoch in range(n_epochs):
avg_cost = 0
for batch in range(n_batches):
batch_X, batch_Y = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict={X: batch_X, Y: batch_Y})
avg_cost += c / n_batches
print("Epoch:", '%02d' % (epoch + 1), "cost=", "{:.4f}".format(avg_cost))
print("Accuracy:", accuracy.eval({X: mnist.test.images, Y: mnist.test.labels}))
在上述代码中,我们使用了一个单隐层的神经网络,其中隐层的节点数为256,学习率为0.01,训练轮数为20,每批次训练数据量为100。我们使用sigmoid作为隐层的激活函数,softmax作为输出层的激活函数,交叉熵作为损失函数,Adam优化器进行优化。在训练过程中,我们输出每轮的平均损失和测试集上的分类准确率。
你可以尝试修改上述代码中的参数,比如改变隐层节点数、学习率、激活函数等,观察它们对分类准确率和总体均方误差的影响
原文地址: http://www.cveoy.top/t/topic/dFcb 著作权归作者所有。请勿转载和采集!