深度学习之验证码识别

1.处理数据(图片与标签文件一一对应)
2.识别验证码:从tfrecords读取,每一张图片和其label对应,一次读取100张,数据shape为[100, 20, 80, 3], 张数,图片的高,宽,channel; 建立模型,直接将数据输入模型; 建立损失,softmax,求交叉熵; 梯度优化

eg:
import tensorflow as tf
tf.app.flags.DEFINE_integer(“batch_size”, 100, “每批次训练的样本数”)
tf.app.flags.DEFINE_string(“captcha_dir”, “./tfrecords…”, “验证码数据保存路径”)
tf.app.flags.DEFINE_integer(“letter”,26,“每个目标值可能取得的字母个数”)
tf.app.flags.DEFINE_integer(“label_num”,4,“每个样本目标值数量”)
#这样写是为了以后代码好改

def read_and_decode():

    #读取验证码数据API,返回image_batch, label_batch

    #1.构建文件队列
    file_queue=tf.train.string_input_producer([FLAGS.captcha_dir])

    #2.构建阅读器,读取文件内容,默认一次读一个样本
    reader=tf.TFReader()

    #3.读取内容,这里value是tfrecords中example格式,是需要解析的
    #这里内部features是string,所以外面的feature也是string格式
    
    key,value=reader.read(file_queue)
    features=tf.parse_single_example(value,features={"image":
                                                     tf.FixedLenFeature([],tf.string),
                                                     "label":
                                                     tf.FixedLenFeature([],tf.string)}
                                     )

    #解码,内容是字符串格式
    #因为是string,所以二进制文件
    tf.decode_raw(features["image"],tf.unit8)  #先解析图片特征值
    label=tf.decode_raw(features["label"],tf.unit8)

    #4.改变shape(因为要batch批处理,其形状必须是固定的)
    image_reshape=tf.reshape(image,[20,80,3])
    label_reshape=tf.reshape(label,[4])

    #5.进行批处理,capacity指的是队列大小,一般和批处理大小相同
    image_batch,label_batch=tf.traain.batch([image_reshape,label_reshape],
                                            batch_size=FLAGS.batch_size,
                                            num_threads=1,
                                            capacity=FLAGS.batch_size)

    return image_batch,label_batch

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

def bias_variable(shape):
b=tf.Variable(tf.constant(0.0, shape=shape))
return b

#定义模型
def fc_model(image):
#image:100张图片,返回y_predict,shape为[100,4*26]

    with tf.variable_scope("model"):
            #随机初始化权重和偏执
            #matrix的shape为[100,20*80*3] * [20*8*3,4*26] +[104]=[100,4*26]

            weights=weight_variable([20*8*3,4*26])
            bias=bias_variable([104])

            #进行全连接计算,一定要先将图片的数据形状转换成二维,
            #而且矩阵计算必须要求数据是float类型,但这里image是tf.unit8,
            #所以要先强行转换类型
            image_reshape=tf.reshape(tf.cast(image,tf.float32),[100,20*80*3])
            y_predict=tf.matmul(image_reshape,weights)+bias
            
    return y_predict

def predict_to_onehot(label):
#将读取文件中的目标值转换成one_hot编码
#输入:label,shape:[100,4]
#输出:one_hot

    label_onehot=tf.one_hot(label,depth=FLAGS.letter_num,on_value=1.0,axis=2)
    
    return label_onehot

def captcharec():
#1.读取验证码数据文件 label_batch, [100,4]

    image_batch,label_batch=read_and_decode()

    #2.通过输入图片特征数据,建立模型,得出预测结果
    #一层,全连接神经网络进行预测
    #matrix [100,20*80*3] * [20*8*3,4*26] +[104]=[100,4*26]

    y_predict=fc_model(image_batch)

    #3.先把目标值转换成one_hot编码,[100,4,26]

    y_true=predict_to_onehot(label_batch)

    #4.softmax计算,交叉熵损失计算

    with tf.variable_scope("soft_cross"):
            #求平均交叉熵损失,y_true从[100,4,26]变成[100,4*26]
            loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
                    labels=tf.reshape(y_true,[FLAGS.batch_siaze,FLAS.label_num,FLAGS.letter_num]),
                    logits=y_predict))
            
    #5.梯度下降
    
    with tf.variable_scope("optimizer"):
            train_op=tf.train.GradientDescentOptimizer(0.01).minimizer(loss)

    #6.求出样本每批次的预测准确率

    with tf.variable_scope("acc"):
            #比较每个预测值和目标值位置是否一样,y_predict [100,4*26] 变成[100,4,26]
            equal_list=tf.equal(tf.argmax(y_true,2),tf.argmax(tf.reshape(y_predict,[FLAGS.batch_size,FLAGS.label_num,FLAGS.letter_num])))
            accuracy=tf.reduce_mean(tf.cast(equal_list,tf.float32))

    #定义初始化变量op
    init_op=tf.global_variables_initializer()

    #开启会话训练
    with tf.Session() as sess:
            sess.run(init_op)

            #定义线程协调器并开启线程(因为有文件读取过程)
            coord=tf.train.Coordinator()

            #开启线程去读取文件操作
            threads=tf.train.start_queue_runner(sess.coord=coord)

            #训练识别程序
            for i in range(5000):
                    sess.run(train_op)
                    print("第%d批次的准确率为:%f"  %(i,accuracy.eval()))

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

    return None

if name ==“main”:
captcharec()

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值