day15-验证码识别



# coding=utf-8
import tensorflow as tf

# 定义一些参数
FLAGES = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("data_path","../data/day09/captcha.tfrecords","训练数据的存储路径")
tf.app.flags.DEFINE_integer("batch_size",100,"训练时批量读取的数据数量")


# 定义一个初始化权重的函数
def weight_variables(shape):
    w = tf.Variable(tf.random_normal(shape=shape, mean=0.0, stddev=1.0))
    return w


# 定义一个初始化偏置的函数
def bias_variables(shape):
    b = tf.Variable(tf.constant(0.0, shape=shape))
    return b


def read_data():
    """
    读取验证码训练数据
    :return:
    """

    # 1、构造文件读取队列
    file_queue = tf.train.string_input_producer([FLAGES.data_path])

    # 2、构造tfrecords读取器
    reader = tf.TFRecordReader()

    # 3、读取数据
    key,value = reader.read(file_queue)

    # 4、解析
    features = tf.parse_single_example(value,features={
        "image":tf.FixedLenFeature([],tf.string),
        "label":tf.FixedLenFeature([],tf.string)
    })

    # 5、解码
    image = tf.decode_raw(features["image"],tf.uint8)
    label = tf.decode_raw(features["label"],tf.uint8)

    # print(image,label)

    # 6、改变形状
    image_reshape = tf.reshape(image,[20,80,3])
    label_reshape = tf.reshape(label,[4])

    # print(image_reshape,label_reshape)

    # 7、批量读取
    image_batch,label_batch = tf.train.batch([image_reshape,label_reshape],
                                             batch_size=FLAGES.batch_size,num_threads=1,capacity=FLAGES.batch_size)



    return image_batch,label_batch


def model(image_batch):

    """
    建立模型预测,使用一层全连接层
    :param image:
    :return:
    """

    # 1、随机的权重和偏置
    # 数据是[None,20 * 80 * 3] ,目标值是[None,4 * 26] ,所以权重应该为 [20 * 80 * 3 , 4 * 26]
    weights = weight_variables([20 * 80 * 3,4 * 26])
    biases = bias_variables([4 * 26])

    # 目前是[None,20,80,3] ,应该变为二维的,所以是[None,20*80*3],但是目前是uint8类型的,计算需要float类型的
    image_reshape = tf.cast(tf.reshape(image_batch,[-1,20 * 80 * 3]),tf.float32)

    # 2、计算
    y_predict = tf.matmul(image_reshape, weights) + biases


    return y_predict

def deal_label(label_batch):

    """
    将目标值转换成onehot编码格式
    :param label_batch:
    :return:
    """
    y_true = tf.one_hot(label_batch,depth=26,on_value=1.0,axis=2)

    print(y_true)

    return y_true


def yzmsb():

    # 1、读取数据
    image_batch,label_batch = read_data()

    # 2、建立模型预测
    y_predict = model(image_batch)

    # 3、处理label成onehot编码格式,此时为[None,4,26]
    y_true = deal_label(label_batch)

    # 4、交叉熵损失
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
        labels=tf.reshape(y_true,[FLAGES.batch_size,4 * 26]),
        logits=y_predict
    ))

    # 5、梯度下降优化
    train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

    # 6、计算准确率
    equal_list = tf.equal(tf.argmax(y_true,axis=2),
                          tf.argmax(tf.reshape(y_predict,[FLAGES.batch_size,4,26]),axis=2))

    acc = tf.reduce_mean(tf.cast(equal_list,tf.float32))

    # 7、准备工作
    init_op = tf.global_variables_initializer()

    # 8、训练
    with tf.Session() as sess:
        sess.run(init_op)
        # 线程管理器
        coord = tf.train.Coordinator()

        # 开启线程
        threads = tf.train.start_queue_runners(sess, coord=coord)

        for i in range(5000):

            sess.run(train_op)

            print("第%d次训练的准确率为%f" % ((i+1),sess.run(acc)))

        # 回收线程
        coord.request_stop()
        coord.join(threads)




    return None



if __name__ == '__main__':
    yzmsb()

训练后的准确率为:


第4988次训练的准确率为0.967500
第4989次训练的准确率为0.967500
第4990次训练的准确率为0.970000
第4991次训练的准确率为0.962500
第4992次训练的准确率为0.960000
第4993次训练的准确率为0.957500
第4994次训练的准确率为0.972500
第4995次训练的准确率为0.965000
第4996次训练的准确率为0.965000
第4997次训练的准确率为0.982500
第4998次训练的准确率为0.965000
第4999次训练的准确率为0.952500
第5000次训练的准确率为0.967500


训练的数据集:
链接:https://pan.baidu.com/s/1rmEQBMPNuQnnTUxCkNfCHw
提取码:7nia
复制这段内容后打开百度网盘手机App,操作更方便哦

原文地址:https://www.cnblogs.com/wuren-best/p/14321601.html