python 简单使用MNIST数据集实现手写数字识别

一、了解MNIST数据集

import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
import matplotlib.pyplot as plt
import numpy as np

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

#1 读取训练集的一张图片与标签
batch_xs, batch_ys = mnist.train.next_batch(1)
img = tf.reshape(batch_xs,[28,28])
label = tf.argmax(batch_ys,1)

#2 读取测试集的一张图片与标签
img_tt = mnist.test.images[0]
img_t = tf.reshape(img_tt,[28,28])
label_tt = mnist.test.labels[0]
label_tt = np.reshape(label_tt,[1,10])
label_t = tf.argmax(label_tt,1)

with tf.Session() as sess:
    # 训练集 打印标签 像素值 
    print("训练集:%d"%sess.run(label))
    im = sess.run(img) 
    for i in range(28):
        for j in range(28):
            print("%d "%round(im[i][j]),end='')
        print()    
    
    #测试集 打印标签 像素值 
    print("测试集:%d"%sess.run(label_t))
    im_t = sess.run(img_t) 
    for i in range(28):
        for j in range(28):
            print("%d "%round(im_t[i][j]),end='')
        print()
        
    #显示图片
    plt.figure()
    plt.subplot(121)
    plt.imshow(im,cmap = 'gray')
    plt.subplot(122)
    plt.imshow(im_t,cmap = 'gray')    
    plt.show()
    

输出结果如下: 

python 简单使用MNIST数据集实现手写数字识别_第1张图片python 简单使用MNIST数据集实现手写数字识别_第2张图片

python 简单使用MNIST数据集实现手写数字识别_第3张图片

二、 简单的训练、测试和保存模型

import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data

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

#2 建立模型
x = tf.placeholder(tf.float32, [None, 784])
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y=tf.nn.softmax(tf.matmul(x,w)+b)

#3 损失函数   交叉熵
y_ = tf.placeholder("float", [None,10])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))

#4 优化训练
optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

#5 开启会话
with tf.Session() as sess:
    # 初始化
    sess.run(tf.global_variables_initializer())

    # 训练
    for i in range(500):
        batch_xs, batch_ys = mnist.train.next_batch(100)
        sess.run(optimizer, feed_dict={x: batch_xs, y_: batch_ys})

    # 测试模型
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}) * 100
    print(accuracy)

    # 保存模型
    model_path = "model/"
    model_name = "model_" + (str(accuracy))[:4] + "%"
    tf.train.Saver().save(sess,model_path+model_name)

三、简单的使用模型

import tensorflow as tf

#1 模型参数
x = tf.placeholder(tf.float32, [None, 784])
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y=tf.nn.softmax(tf.matmul(x,w)+b)
#y_ = tf.placeholder("float", [None,10])

#2 读取图片
img = tf.read_file('7.jpg')                                 #读取 彩色图片
im_3 = tf.image.decode_jpeg(img, channels=3)                #解码 
im_resize = tf.image.resize_images(im_3,[28,28])            #缩放成28X28
im_gry = tf.squeeze(tf.image.rgb_to_grayscale(im_resize),2) #灰度化  降维变成二维
im_reshape = tf.reshape(im_gry,[1,784])                     #改变形状 

#3 开启会话
with tf.Session() as sess:
    # 读取模型
    tf.train.Saver().restore(sess,"model/model_91.4%")
    
    # 输入待检测图像数据
    xx = sess.run(im_reshape)

    # 进行识别并输出
    result = sess.run(tf.argmax(y, 1), feed_dict={x: xx})
    print(result)
    

 结果:                   结果:

你可能感兴趣的:(人工智能,python)