自制做数据集的手写数字识别的神经网络实践

作者: shaneZhang 分类: 机器学习的实践 发布时间: 2019-01-26 18:40

经过一番训练之后发现识别的准确率已经达到98%,可是在实际的运行过程中,数字5还是识别成了3,不知道是不是哪里的代码写错了。但是其他数字还是非常准确的识别出来了。下面来看看结果。

上面的实践结果代码如下的几个类所示。因为这个实践需要6万张的训练图片和1万张的测试图片来训练,详细的代码可以从这里下载到。https://code.5288z.com/zhangyuqing/AIPractice

#coding:utf-8
#fc4_mnist_generateds.py
#本文件主要为生成数据集的文件,生成训练和测试的数据图片集合

import  tensorflow as tf
from PIL import Image
import os

image_train_path = './mnist_data_jpg/mnist_train_jpg_60000/'
label_train_path = './mnist_data_jpg/mnist_train_jpg_60000.txt'
tfRecord_train = './data/mnist_train.tfrecords'
image_test_path = './mnist_data_jpg/mnist_test_jpg_10000/'
label_test_path = './mnist_data_jpg/mnist_test_jpg_10000.txt'
tfRecord_test = './data/mnist_test.tfrecords'
data_path = './data'
resize_height = 28
resize_width = 28


def write_tfRecord(tfRecordName,image_path,label_path):
    writer = tf.python_io.TFRecordWriter(tfRecordName)
    num_pic = 0
    f = open(label_path,'r')
    contents = f.readlines()
    f.close()

    for content in contents:
        value = content.split()
        img_path = image_path + value[0]
        img = Image.open(img_path)
        img_raw = img.tobytes()
        labels = [0] * 10
        labels[int(value[1])] = 1

        example = tf.train.Example(features = tf.train.Features(feature={
            'img_raw':tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])),
            'label':tf.train.Feature(int64_list=tf.train.Int64List(value=labels))
        }))

        writer.write(example.SerializeToString())
        num_pic += 1
        print ("the number of picture:",num_pic)

    writer.close()
    print "writer tfRecord successful"


def generate_tfRecord():
    isExists  = os.path.exists(data_path)
    if not isExists:
        os.mkdir(data_path)
        print "the directory was created successful"
    else:
        print "the directory already exists"
    write_tfRecord(tfRecord_train,image_train_path,label_train_path)
    write_tfRecord(tfRecord_test,image_test_path,label_test_path)



def read_tfRecord(tfRecord_path):
    filename_queue = tf.train.string_input_producer([tfRecord_path],shuffle=True)
    reader = tf.TFRecordReader()
    _,serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(serialized_example,features={
        'label':tf.FixedLenFeature([10],tf.int64),
        'img_raw':tf.FixedLenFeature([],tf.string)
    })
    img = tf.decode_raw(features['img_raw'],tf.uint8)
    img.set_shape([784])
    img = tf.cast(img,tf.float32) * (1.0/255)
    label = tf.cast(features['label'],tf.float32)

    return img,label

def get_tfrecord(num,isTrain=True):
    if isTrain:
        tfRecord_path = tfRecord_train
    else:
        tfRecord_path = tfRecord_test

    img,label = read_tfRecord(tfRecord_path)
    img_batch,label_batch = tf.train.shuffle_batch([img,label],
                                                   batch_size=num,
                                                   num_threads=2,
                                                   capacity=1000,
                                                   min_after_dequeue=700)

    return img_batch,label_batch


def main():
    generate_tfRecord()


if __name__ == '__main__':
    main()
#coding=utf-8
#fc4_mnist_forward.py

import tensorflow as tf

INPUT_NODE = 784
OUTPUT_NODE = 10
LAYER1_NODE = 500

def get_weight(shape,regularizer):
    w = tf.Variable(tf.truncated_normal(shape,stddev=0.1))
    if regularizer != None:
        tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))

    return w

def get_bias(shape):
    b = tf.Variable(tf.zeros(shape))
    return b


def forward(x,regularizer):
    w1 = get_weight([INPUT_NODE,LAYER1_NODE],regularizer)
    b1 = get_bias([LAYER1_NODE])
    y1 = tf.nn.relu(tf.matmul(x,w1) + b1)

    w2 = get_weight([LAYER1_NODE,OUTPUT_NODE],regularizer)
    b2 = get_bias([OUTPUT_NODE])
    y = tf.matmul(y1,w2) + b2

    return y


if __name__ == '__main__':
    print 'this is the main method'
#coding=utf-8
#fc4_mnist_backward.py

import  tensorflow as tf
import os
import fc4_mnist_generateds
import fc4_mnist_forward

BATCH_SIZE = 200
LEARNING_REATE_BASE = 0.1
LARNING_REATE_DECAY = 0.99
REGULARIZER = 0.0001
STEPS = 50000
MOVING_AVERAGE_DECAY = 0.99
MODEL_SAVE_PATH = "./model/"
MODEL_NAME = "mnist_model"
train_num_examples = 60000


def backward():
    x = tf.placeholder(tf.float32,[None,fc4_mnist_forward.INPUT_NODE])
    y_ = tf.placeholder(tf.float32,[None,fc4_mnist_forward.OUTPUT_NODE])
    y = fc4_mnist_forward.forward(x,REGULARIZER)
    global_step = tf.Variable(0,trainable=False)

    ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y,labels=tf.argmax(y_,1))
    cem = tf.reduce_mean(ce)
    loss = cem + tf.add_n(tf.get_collection('losses'))

    leaning_rate = tf.train.exponential_decay(
        LEARNING_REATE_BASE,
        global_step,
        train_num_examples / BATCH_SIZE,
        LARNING_REATE_DECAY,
        staircase=True
    )

    train_step = tf.train.GradientDescentOptimizer(leaning_rate).minimize(loss,global_step=global_step)

    ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY,global_step)
    ema_op = ema.apply(tf.trainable_variables())
    with tf.control_dependencies([train_step,ema_op]):
        train_op = tf.no_op(name='train')

    saver = tf.train.Saver()
    img_batch,label_batch = fc4_mnist_generateds.get_tfrecord(BATCH_SIZE,isTrain=True)

    with tf.Session() as sess:
        init_op = tf.global_variables_initializer()
        sess.run(init_op)

        ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH)
        if ckpt and ckpt.model_checkpoint_path:
            saver.restore(sess,ckpt.model_checkpoint_path)

        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess,coord=coord)

        for i in range(STEPS):
            xs,ys = sess.run([img_batch,label_batch])
            _,loss_value,step = sess.run([train_op,loss,global_step],feed_dict={x:xs,y_:ys})
            if i % 1000 == 0:
                print "After %d training steps, loss on training batch is %g" %(step,loss_value)
                saver.save(sess,os.path.join(MODEL_SAVE_PATH,MODEL_NAME),global_step = global_step)

        coord.request_stop()
        coord.join(threads)



def main():
    backward()


if __name__ == '__main__':
    main()
# coding:utf-8
# fc4_mnist_test.py

import time
import tensorflow as tf
import fc4_mnist_backward
import fc4_mnist_generateds
import fc4_mnist_forward

TEST_INTERVAL_SECS = 5
TEST_NUM = 10000


def test():
    with tf.Graph().as_default() as g:
        x = tf.placeholder(tf.float32, [None, fc4_mnist_forward.INPUT_NODE])
        y_ = tf.placeholder(tf.float32, [None, fc4_mnist_forward.OUTPUT_NODE])
        y = fc4_mnist_forward.forward(x, None)

        ema = tf.train.ExponentialMovingAverage(fc4_mnist_backward.MOVING_AVERAGE_DECAY)
        ema_restore = ema.variables_to_restore()
        saver = tf.train.Saver(ema_restore)

        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        img_batch, label_batch = fc4_mnist_generateds.get_tfrecord(TEST_NUM, isTrain=False)

        while True:
            with tf.Session() as sess:
                ckpt = tf.train.get_checkpoint_state(fc4_mnist_backward.MODEL_SAVE_PATH)
                if ckpt and ckpt.model_checkpoint_path:
                    saver.restore(sess, ckpt.model_checkpoint_path)
                    global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]

                    coord = tf.train.Coordinator()
                    threads = tf.train.start_queue_runners(sess=sess, coord=coord)

                    xs, ys = sess.run([img_batch, label_batch])

                    accuracy_score = sess.run(accuracy, feed_dict={x: xs, y_: ys})

                    print("After %s training step(s), test accuracy = %g" % (global_step, accuracy_score))

                    coord.request_stop()
                    coord.join(threads)

                else:
                    print('No checkpoint file found')
                    return
            time.sleep(TEST_INTERVAL_SECS)


def main():
    test()


if __name__ == '__main__':
    main()
# coding:utf-8
#fc4_mnist_app.py

import tensorflow as tf
import numpy as np
from PIL import Image
import fc4_mnist_backward
import fc4_mnist_forward


def restore_model(testPicArr):
    with tf.Graph().as_default() as tg:
        x = tf.placeholder(tf.float32, [None,fc4_mnist_forward.INPUT_NODE])
        y = fc4_mnist_forward.forward(x, None)
        preValue = tf.argmax(y, 1)

        variable_averages = tf.train.ExponentialMovingAverage(fc4_mnist_backward.MOVING_AVERAGE_DECAY)
        variables_to_restore = variable_averages.variables_to_restore()
        saver = tf.train.Saver(variables_to_restore)

        with tf.Session() as sess:
            ckpt = tf.train.get_checkpoint_state(fc4_mnist_backward.MODEL_SAVE_PATH)
            if ckpt and ckpt.model_checkpoint_path:
                saver.restore(sess, ckpt.model_checkpoint_path)
                preValue = sess.run(preValue, feed_dict={x: testPicArr})
                return preValue
            else:
                print("No checkpoint file found")
                return -1


def pre_pic(picName):
    img = Image.open(picName)
    reIm = img.resize((28, 28), Image.ANTIALIAS)
    im_arr = np.array(reIm.convert('L'))
    threshold = 50
    for i in range(28):
        for j in range(28):
            im_arr[i][j] = 255 - im_arr[i][j]
            if (im_arr[i][j] < threshold):
                im_arr[i][j] = 0
            else:
                im_arr[i][j] = 255

    nm_arr = im_arr.reshape([1, 784])
    nm_arr = nm_arr.astype(np.float32)
    img = np.multiply(nm_arr, 1.0 / 255.0)

    return nm_arr  # img


def application():
    testNum = input("input the number of test pictures:")
    for i in range(testNum):
        testPic = raw_input("the path of test picture:")
        testPicArr = pre_pic(testPic)
        preValue = restore_model(testPicArr)
        print "The prediction number is:", preValue


def main():
    application()


if __name__ == '__main__':
    main()

本页面支持繁体中文友好显示:自制做数据集的手写数字识别的神经网络实践

如果觉得我的文章对您有用,请随意打赏。如果有其他问题请联系博主QQ(909491009)或者下方留言!

发表回复