《人工智能实践:Tensorflow笔记》-06全连接网络实践

断点续训

ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH)
if ckpt and ckpt.model_checkpoint_path:
	# 恢复会话
	saver.restore(sess, ckpt.model_checkpoint_path)

实现了给所有的w和b赋保存在ckpt中的值,实现断点续训。


  • 如何对输入的真实图片,输出预测结果?
  • 如何制作数据集,实现特定应用?
def application():
	testNum = input("input the num 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)

input函数可以从控制台读入数字
raw_input从控制台读入字符串


app.py

import tensorflow as tf
import numpy as np
from PIL import Image
import forward
import backward


def pre_pic(picName):
    img = Image.open(picName)
    reIm = img.resize((28, 28), Image.ANTIALIAS)
    im_arr = np.array(reIm.convert('L')) # 变成灰度图
    """
    模型要求的是黑底白字
    输入的图片是白底黑字
    因此要给输入图片反色
    纯白色255
    """
    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_ready = np.multiply(nm_arr, 1.0/255.0)

    return img_ready

def restore_model(testPicArr):
    with tf.Graph().as_default() as tg:
        # 仅需要给输入x占位
        x = tf.placeholder(tf.float32, [None, forward.INPUT_MODE])
        # 计算求得输出y
        y = forward.forward(x, None)
        # 返回预测结果索引
        preValue = tf.argmax(y, 1)

        # 实例化带有滑动平均值的saver
        variable_averages = tf.train.ExponentialMovingAverage(backward.MOVING_AVERAGE_DECAY)
        variable_to_restore = variable_averages.variables_to_restore() ####
        saver = tf.train.Saver(variable_to_restore)

        with tf.Session() as sess:
            ckpt = tf.train.get_checkpoint_state(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 application():
    testNum = int(input("input the number of test pictures:"))
    for i in range(testNum):
        testPic = 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()

制作数据集

tfrecords文件
tfrecords是一种二进制文件,可先将图片和标签制作成该格式的文件。使用tfrecords进行数据读取,会提高内存利用率。

用tf.train.Example的协议存储训练数据。训练数据的特征用键值对的形式表示。
如:
‘img_raw’:值 ‘label’:值
值是Byteslist/FloatList/Int64List

用SerializeToString()把数据序列化成字符串存储。

生成tfrecords文件

# 新建一个writer
writer = tf.python_io.TFRecordWriter(tfRecordName)
for 循环遍历每张图和标签:
	# 把每章图片和标签装到exampl中
	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=lables))}))
	# 把example进行序列化
	writer.write(example.SerializeToString)
write.close()

解析tfrecords文件

filename_queue = tf.train.string_input_producer([tfRecord_path])
reader = tf.TFRecordReader() # 新建一个reader
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(serialized_example,features={'img_raw':tf.FixedLenFeature([],tf.string), 'label': tf.FixdLenFeature([10],tf.int64)})
img = tf.decode_raw(feature['img_raw'],tf.uint8)
img.set_reshape([784])
img = tf.cast(img, tf.float32)*(1./255)
label = tf.cast(features['label'], tf.float32)

在backw和test的python文件中修改图片标签获取的接口

coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
# 图片和标签的批获取
coord.request_stop()
coord.join(threads)

《人工智能实践:Tensorflow笔记》-06全连接网络实践_第1张图片
generateds.py

import tensorflow as tf
import numpy as np
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 writer_tfRecord(tfRceordName, image_path, label_path):
    writer = tf.python_io.TFRecordWriter(tfRceordName)
    # 为了显示进度创建一个计数器
    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("write tfrecord successfully")

# 接收待读取的tfrecord文件
def read_tfRecord(tfRecord_path):
    # 新建文件名队列,告知文件名队列包括哪些文件
    filename_queue = tf.train.string_input_producer([tfRecord_path])
    # 新建一个reader,把读出的每一个样本保存到serialized_example中进行解序列化
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    # 标签和图片的键名应该和制作tfrecord文件的键名相同
    # 标签要给出是几分类
    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. / 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)
    # 从总样本中顺序取出capacity组数据,打乱顺序,每次输出batch_size组
    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 generate_tfRecord():
    # 判断保存路径是否存在,不存在则新建,否则返回已存在
    isExists = os.path.exists(data_path)
    if not isExists:
        os.makedirs(data_path)
        print("The directory is created successfully")
    else:
        print("directory is exists")
    # 训练集和测试集中的图片和标签生成tfRecord文件
    writer_tfRecord(tfRecord_train, image_train_path, label_train_path)
    writer_tfRecord(tfRecord_test, image_test_path, label_test_path)

def main():
    generate_tfRecord()

if __name__ == '__main__':
    main()

forward.py

import tensorflow as tf

# 定义神经网络结构的相关参数
INPUT_MODE = 784
OUTPUT_MODE = 10
LAYER_MODE = 500

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

    w2 = get_weight([LAYER_MODE, OUTPUT_MODE], regularizer)
    b2 = get_bias([OUTPUT_MODE])
    y = tf.matmul(y1, w2) + b2
    return y

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

backward.py

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import forward
import os
import generateds


# 每轮喂入神经网络图片数量
BATCH_SIZE = 200
# 最开始的学习率
LEARNING_RATE_BASE = 0.1
# 学习率衰减率
LEARNING_RATE_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(mnist):
    x = tf.placeholder(tf.float32, [None, forward.INPUT_MODE])
    y_ = tf.placeholder(tf.float32, [None, forward.OUTPUT_MODE])
    y = 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
    loss = cem + tf.add_n(tf.get_collection('losses'))

    ## 指数衰减学习率
    learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE,
                                               global_step,
                                               # mnist.train.num_examples / BATCH_SIZE,
                                               train_num_examples / BATCH_SIZE,
                                               LEARNING_RATE_DECAY,
                                               staircase=True)
    # 定义训练过程
    train_step = tf.train.GradientDescentOptimizer(learning_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 = 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 = mnist.train.next_batch(BATCH_SIZE)
            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 step(s), loss on training batch is %g" % (i, 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():
    mnist = input_data.read_data_sets('data', one_hot=True)
    backward(mnist)

if __name__ == '__main__':
    main()

test.py

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
## 为了延迟导入time模块
import time
import forward
import backward
import generateds

TEST_INTERVAL_SECS = 5
TEST_NUM = 10000####


def test(mnist):
    # 复现计算图
    with tf.Graph().as_default() as g:
        # 定义x y_ y
        x = tf.placeholder(tf.float32, [None, forward.INPUT_MODE])
        y_ = tf.placeholder(tf.float32, [None, forward.OUTPUT_MODE])
        y = forward.forward(x, None)

        ## 实例化可还原滑动平均值的saver
        ema = tf.train.ExponentialMovingAverage(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 = generateds.get_tfRecord(TEST_NUM, isTrain=False)####

        # 计算正确率
        while True:
            with tf.Session() as sess:
                # 加载ckpt模型
                ckpt = tf.train.get_checkpoint_state(backward.MODEL_SAVE_PATH)
                # 如果已有ckpt模型则恢复
                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: mnist.test.images, y_: mnist.test.labels})
                    # 打印提示
                    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():
    mnist = input_data.read_data_sets('data', one_hot=True)
    test(mnist)

if __name__ == '__main__':
    main()

app.py

import tensorflow as tf
import numpy as np
from PIL import Image
import forward
import backward


def pre_pic(picName):
    img = Image.open(picName)
    reIm = img.resize((28, 28), Image.ANTIALIAS)
    im_arr = np.array(reIm.convert('L')) # 变成灰度图
    """
    模型要求的是黑底白字
    输入的图片是白底黑字
    因此要给输入图片反色
    纯白色255
    """
    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_ready = np.multiply(nm_arr, 1.0/255.0)

    return img_ready

def restore_model(testPicArr):
    with tf.Graph().as_default() as tg:
        # 仅需要给输入x占位
        x = tf.placeholder(tf.float32, [None, forward.INPUT_MODE])
        # 计算求得输出y
        y = forward.forward(x, None)
        # 返回预测结果索引
        preValue = tf.argmax(y, 1)

        # 实例化带有滑动平均值的saver
        variable_averages = tf.train.ExponentialMovingAverage(backward.MOVING_AVERAGE_DECAY)
        variable_to_restore = variable_averages.variables_to_restore() ####
        saver = tf.train.Saver(variable_to_restore)

        with tf.Session() as sess:
            ckpt = tf.train.get_checkpoint_state(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 application():
    testNum = int(input("input the number of test pictures:"))
    for i in range(testNum):
        testPic = 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()

你可能感兴趣的:(Tensorflow)