9.使用卷积神经网络实现mnist数据集分类。卷积层、池化层的数量可自行调整,优化器策略和学习率也可自行调整,输出分类准确率。
时间: 2024-02-12 19:06:26 浏览: 67
好的,这是一个很好的机器学习问题。这里提供一份使用TensorFlow实现的代码,可以在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)
# 定义参数
learning_rate = 0.001
training_iters = 20000
batch_size = 128
display_step = 10
# 定义网络参数
n_input = 784 # MNIST数据输入 (img shape: 28*28)
n_classes = 10 # MNIST总共的类别 (0-9 digits)
dropout = 0.75 # Dropout, probability to keep units
# 占位符输入
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32) # dropout (keep probability)
# 卷积操作
def conv2d(name, l_input, w, b, s):
return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(l_input, w, strides=[1, s, s, 1], padding='SAME'), b), name=name)
# 池化操作
def max_pool(name, l_input, k):
return tf.nn.max_pool(l_input, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME', name=name)
# 正则化操作
def norm(name, l_input, lsize=4):
return tf.nn.lrn(l_input, lsize, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name=name)
# 定义整个网络
def alex_net(_X, _weights, _biases, _dropout):
# 向量转为矩阵
_X = tf.reshape(_X, shape=[-1, 28, 28, 1])
# 卷积层1
conv1 = conv2d('conv1', _X, _weights['wc1'], _biases['bc1'], 1)
# 池化层1
pool1 = max_pool('pool1', conv1, k=2)
# 正则化层1
norm1 = norm('norm1', pool1, lsize=4)
# Dropout层1
norm1 = tf.nn.dropout(norm1, _dropout)
# 卷积层2
conv2 = conv2d('conv2', norm1, _weights['wc2'], _biases['bc2'], 1)
# 池化层2
pool2 = max_pool('pool2', conv2, k=2)
# 正则化层2
norm2 = norm('norm2', pool2, lsize=4)
# Dropout层2
norm2 = tf.nn.dropout(norm2, _dropout)
# 卷积层3
conv3 = conv2d('conv3', norm2, _weights['wc3'], _biases['bc3'], 1)
# 池化层3
pool3 = max_pool('pool3', conv3, k=2)
# 正则化层3
norm3 = norm('norm3', pool3, lsize=4)
# Dropout层3
norm3 = tf.nn.dropout(norm3, _dropout)
# 全连接层1,将三维数据转为一维数据
dense1 = tf.reshape(norm3, [-1, _weights['wd1'].get_shape().as_list()[0]])
dense1 = tf.nn.relu(tf.matmul(dense1, _weights['wd1']) + _biases['bd1'], name='fc1')
# Dropout层4
dense1 = tf.nn.dropout(dense1, _dropout)
# 全连接层2
dense2 = tf.nn.relu(tf.matmul(dense1, _weights['wd2']) + _biases['bd2'], name='fc2')
# Dropout层5
dense2 = tf.nn.dropout(dense2, _dropout)
# 输出层
out = tf.matmul(dense2, _weights['out']) + _biases['out']
return out
# 存储所有的网络参数
weights = {
'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64])),
'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128])),
'wc3': tf.Variable(tf.random_normal([3, 3, 128, 256])),
'wd1': tf.Variable(tf.random_normal([4 * 4 * 256, 1024])),
'wd2': tf.Variable(tf.random_normal([1024, 1024])),
'out': tf.Variable(tf.random_normal([1024, 10]))
}
biases = {
'bc1': tf.Variable(tf.random_normal([64])),
'bc2': tf.Variable(tf.random_normal([128])),
'bc3': tf.Variable(tf.random_normal([256])),
'bd1': tf.Variable(tf.random_normal([1024])),
'bd2': tf.Variable(tf.random_normal([1024])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# 构建模型
pred = alex_net(x, weights, biases, keep_prob)
# 定义损失函数和优化器
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# 测试网络
correct_pred = tf.equal(tf.argmax(pred, 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)
step = 1
# 循环训练
while step * batch_size < training_iters:
batch_x, batch_y = mnist.train.next_batch(batch_size)
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y, keep_prob: dropout})
if step % display_step == 0:
# 计算损失和准确率
loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x, y: batch_y, keep_prob: 1.})
print("Iter " + str(step * batch_size) + ", Minibatch Loss= " + "{:.6f}".format(
loss) + ", Training Accuracy= " + "{:.5f}".format(acc))
step += 1
print("Optimization Finished!")
# 计算测试集的准确率
print("Testing Accuracy:",
sess.run(accuracy, feed_dict={x: mnist.test.images[:256], y: mnist.test.labels[:256], keep_prob: 1.}))
```
运行代码后,可以得到模型在测试集上的准确率,一般在98%以上。
阅读全文