1、获取MNIST数据集,每张图片像素为28 x 28
2、模型架构为包含两个隐含层的多层感知机模型
输入层维度: 28x28 = 784
第一层隐含单元数: 256
第二层隐含单元数: 256
输出层维度: 10 (MNIST数据集类别数,分别为0到9)
3、画出训练和测试过程的准确率随迭代次数变化图,画出训练和测试过程的损失随迭代次数变化图。(提交最终 分类精度、分类损失以及两张变化图)
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#导入数据
mnist = input_data.read_data_sets('mnist',one_hot=True)
#最大迭代次数
MAX_epoch=20
#学习率
learning_rate = 0.01
all_loss=[]
all_accuracy=[]
#各层的单元数目,输入数目,输出数目
#图片大小为28×28,故输入为784,每层单元数由自己决定。共有10个标签,故输出有10个
n_hidden_1 =256
n_hidden_2 =256
n_input =784
n_classes =10
X = tf.placeholder(tf.float32,[None,784],name='X_placeholder')
Y = tf.placeholder(tf.float32,[None,10],name='Y_placeholder')
weights ={
'h1': tf.Variable(tf.random_normal([n_input,n_hidden_1]),name='W1'),
'h2': tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2]),name='W2'),
'out': tf.Variable(tf.random_normal([n_hidden_2,n_classes]),name='W')
}
biases ={
'b1': tf.Variable(tf.random_normal([n_hidden_1]),name='b1'),
'b2': tf.Variable(tf.random_normal([n_hidden_2]),name='b2'),
'out': tf.Variable(tf.random_normal([n_classes]),name='bias')
}
def multilayer_perceptron(x, weights, biases):
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'], name='fc_1')
layer_1 = tf.nn.relu(layer_1, name='relu_1')
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'], name='fc_2')
layer_2 = tf.nn.relu(layer_2, name='relu_2')
out_layer = tf.add(tf.matmul(layer_2, weights['out']), biases['out'], name='fc_3')
return out_layer
pred = multilayer_perceptron(X, weights, biases)
#定义损失函数,用交叉熵
loss_all = tf.nn.softmax_cross_entropy_with_logits(labels=Y,logits=pred,name='cross_entropy')
loss = tf.reduce_mean(loss_all,name='avg_loss')
#使用Adam算法进行优化, learning_rate 是学习率
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
init =tf.global_variables_initializer()
batch_size=128
display_step =1
with tf.Session() as sess:
sess.run(init)
for epoch in range(MAX_epoch):
avg_loss =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)
_, l = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y})
avg_loss += l/total_batch
#加入每一个损失
all_loss.append(avg_loss)
#计算准确率
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
acc=accuracy.eval({X: mnist.test.images, Y: mnist.test.labels})
#加入每一个准确率,用于后面画图
all_accuracy.append(acc)
if epoch%display_step==0:
print ('Epoch:', '%04d'% (epoch+1),'loss=', "{:.9f}".format(avg_loss))
correct_prediction = tf.equal(tf.argmax(pred,1),tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,'float'))
print ('accuracy:',accuracy.eval({X:mnist.test.images, Y:mnist.test.labels}))
yy=[]
yy.extend(range(1,len(all_accuracy)+1))
plt.plot(yy, all_accuracy, c='red')
plt.title("accuracy")
plt.show()
plt.clf()
plt.plot(yy, all_loss, c='blue')
plt.title("loss")
plt.show()
需要注意的是,mnist的路径需要存在。我这里代码是直接’mnist’,但实际上的路径是看这个文件在电脑内存里的实际路径。
而关于mnist,虽然可以在代码中下载,但我更推荐在国内镜像中下载后再直接路径读取。