MNIST手写数字识别进阶:多层神经网络及应用(1)

# 一、载入数据
import tensorflow as tf
import numpy as np
#导入tensorflow提供的读取MNIST的模块
import tensorflow.examples.tutorials.mnist.input_data as input_data

#读取MNIST数据
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)

#1.构建输入层
x = tf.placeholder(tf.float32,[None,784],name="X")
y = tf.placeholder(tf.float32,[None,10],name="Y")

#2.构建隐藏层
H1_NN = 256

W1 = tf.Variable(tf.random_normal([784,H1_NN]))
b1 = tf.Variable(tf.zeros([H1_NN]))

Y1 = tf.nn.relu(tf.matmul(x,W1) + b1)

#3.构建输出层
W2 = tf.Variable(tf.random_normal([H1_NN,10]))
b2 = tf.Variable(tf.zeros([10]))

forward = tf.matmul(Y1,W2) + b2
pred = tf.nn.softmax(forward)

#1.构建输入层
x = tf.placeholder(tf.float32,[None,784],name="X")
y = tf.placeholder(tf.float32,[None,10],name="Y")

#2.构建隐藏层
H1_NN = 256

W1 = tf.Variable(tf.random_normal([784,H1_NN]))
b1 = tf.Variable(tf.zeros([H1_NN]))

Y1 = tf.nn.relu(tf.matmul(x,W1) + b1)

#3.构建输出层
W2 = tf.Variable(tf.random_normal([H1_NN,10]))
b2 = tf.Variable(tf.zeros([10]))

forward = tf.matmul(Y1,W2) + b2
pred = tf.nn.softmax(forward)

# 评估模型
accu_test = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print("Test Accuracy:",accu_test)

# 应用模型
# 由于pred预测结果是one-hot编码格式,所以需要转换为0~9数字
prediction_result=sess.run(tf.argmax(pred,1),feed_dict={x:mnist.test.images})

#查看预测结果中的前10项
prediction_result[0:10]

# 找出预测结果
compare_lists = prediction_result==np.argmax(mnist.test.labels,1)
print(compare_lists)
err_lists = [i for i in range(len(compare_lists)) if compare_lists[i]==False]
print(err_lists,len(err_lists))

# 定义一个输出错误分类的函数
def print_predict_errs(labels,prediction):      #标签列表、预测值列表
    count=0
    compare_lists = (prediction==np.argmax(labels,1))
    err_lists = [i for i in range(len(compare_lists)) if compare_lists[i]==False]
    for x in err_lists:
        print("index="+str(x)+"标签值=",np.argmax(labels[x]),"预测值=",prediction[x])
        count = count + 1
    print("总计:"+str(count))
    
print_predict_errs(labels=mnist.test.labels,prediction=prediction_result)

# 可视化查看预测错误的样本
import matplotlib.pyplot as plt
#定义可视化函数
def plot_images_labels_prediction(images,labels,prediction,index,num=10):           #图像列表、标签列表、预测值列表、从第index个开始显示、缺省一次显示十幅
    fig=plt.gcf()       #获取当前图表,Get Current figure
    fig.set_size_inches(10,12)        #1英寸等于2.54cm
    if num>25:
        num = 25               #最多显示25个子图
    for i in range(0,num):
        ax = plt.subplot(5,5,i+1)                 #获取当前要处理的子图
        ax.imshow(np.reshape(images[index],(28,28)),           #显示第index个图象
                 cmap='binary')
        title = "label=" + str(np.argmax(labels[index]))    #构建该图上要显示的title信息
        if len(prediction)>0:
            title += ",predict=" + str(prediction[index])
            
        ax.set_title(title,fontsize=10)     #显示图上的title信息
        ax.set_xticks([]);          #不显示坐标轴
        ax.set_yticks([])
        index += 1
    plt.show()
plot_images_labels_prediction(mnist.test.images,mnist.test.labels,prediction_result,610,20)

                                  ————代码内容来源于《深度学习应用开发Tensorflow实践》

posted @ 2019-01-31 16:42  泰初  阅读(843)  评论(1编辑  收藏  举报