tensorflow 全连接神经网络识别mnist数据

    之前没有学过tensorflow,所以使用tensorflow来对mnist数据进行识别,采用最简单的全连接神经网络,第一层是784,(输入层),隐含层是256,输出层是10

,相关注释卸载程序中。

#!/usr/bin/env python 3.6
#_*_coding:utf-8 _*_
#@Time    :2020/2/12 15:34
#@Author  :hujinzhou 
#@FileName: mnist.py

#@Software: PyCharm
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
import matplotlib.pyplot as plt
import numpy as np
from time import time
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)#通过tensorflow下载mnist数据集
"""图片的显示"""
def plot_image(image):
    plt.imshow(image.reshape(28,28),cmap=‘binary‘)#tensorflow中的数据是将图片平铺成一列的存储,
                                                  # 所以显示的时候应该reshape成28*28
    plt.show()
"""查看多项数训练数据images与labels"""
def plot_images_labels_prediction(images,labels,prediction,idx,num):#idx表示要显示的第idx个图像从idx~idx+25
    fig=plt.gcf()
    fig.set_size_inches(25,25)#设置显示尺寸
    if num>25:num=25
    for i in range(0,num):
        ax=plt.subplot(5,5,i+1)#一次显示多个子图
        ax.imshow(np.reshape(images[idx],(28,28)),cmap=‘binary‘)#将第idx个图像数据reshape成28*28的numpy并显示
        title="label="+str(np.argmax(labels[idx]))#设置图像的title,将onehot码转为数值码
        """如果有预测的prediction,则重新写title"""
        if len(prediction)>0:
            title+=",predict="+str(prediction[idx])
        ax.set_title(title,fontsize=10)
        ax.set_xticks([]);ax.set_yticks([])#设置xy轴为空,如果不设置则会有标度(像素值)
        idx+=1
    plt.show()


"""构造多层感知机"""
"""自己构造感知机"""
# def layer(output_dim, input_dim, inputs, activation=None):
#     W = tf.Variable(tf.random_normal([input_dim, output_dim]))
#     b = tf.Variable(tf.random_normal([1, output_dim]))
#     XWb = tf.matmul(inputs, W) + b
#     if activation is None:
#         outputs = XWb
#     else:
#         outputs = activation(XWb)
#     return outputs

"""采用tf包来构造感知机"""
x = tf.placeholder("float", [None, 784])
h1=tf.layers.dense(inputs=x,units=256,activation=tf.nn.relu)
# h1 = layer(output_dim=256, input_dim=784,
#            inputs=x, activation=tf.nn.relu)
y_predict = tf.layers.dense(inputs=h1,units=10,activation=None)
y_label = tf.placeholder("float", [None, 10])
loss_function = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits_v2
    (logits=y_predict,
     labels=y_label))#计算损失值
optimizer = tf.train.AdamOptimizer(learning_rate=0.001)  61     .minimize(loss_function)#使用优化器反向传播,使得损失量为最小
correct_prediction = tf.equal(tf.argmax(y_label, 1),
                              tf.argmax(y_predict, 1))#相等为1,不想等为0,统计正确的个数
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))#精度等于正确个数除以总数
"""训练过程"""
train_epoch=30
batch_size=100
loss_list=[];epoch_list=[];accuracy_list=[]
starttime=time()


sess=tf.Session()
sess.run(tf.global_variables_initializer())
for epoch in range(train_epoch):
    for i in range(550):
        batch_x, batch_y = mnist.train.next_batch(batch_size)
        sess.run(optimizer, feed_dict={x: batch_x, y_label: batch_y})#使用55000的训练集进行优化

    loss, acc = sess.run([loss_function, accuracy],
                         feed_dict={x: mnist.validation.images,
                                    y_label: mnist.validation.labels})#验证集进行验证

    epoch_list.append(epoch);
    loss_list.append(loss)
    accuracy_list.append(acc)
    print("Train Epoch:", ‘%02d‘ % (epoch + 1), "Loss=",  87           "{:.9f}".format(loss), " Accuracy=", acc)
duration = time() - starttime
print("The process has taken;{:.10f}".format(duration))
fig2=plt.gcf()
fig2.set_size_inches(4,2)#设置显示尺寸
plt.plot(epoch_list,loss_list,label="loss")

plt.ylabel(‘loss‘)
plt.xlabel(‘epoch‘)
plt.legend([‘loss‘],loc=‘upper left‘)
plt.show()
plt.plot(epoch_list,accuracy_list,label=‘acc‘)
plt.show()
# sess=tf.Session()
# init = tf.global_variables_initializer()
# sess.run(init)
#注意这个地方,不可以重新设置sess,不可以重新开启回话,重新开启会错误
print("acc:",sess.run(accuracy,feed_dict={x:mnist.test.images,y_label:mnist.test.labels}))

pre_result=sess.run(tf.argmax(y_predict,1),feed_dict={x:mnist.test.images})
plot_images_labels_prediction(mnist.test.images,mnist.test.labels,pre_result,0,25)
sess.close()

tensorflow 全连接神经网络识别mnist数据

 tensorflow 全连接神经网络识别mnist数据

 tensorflow 全连接神经网络识别mnist数据

相关推荐