机器学习我爱编程

Captchatool一个验证码识别模块(python,tens

2018-04-06  本文已影响143人  MMMzq

Captchatool是一个简单易用的验证码识别的小型模块,其开发之初就是以快捷,简单为目的的工具模块,利用了python语言和tensorflow深度学习框架开发而成!

第一部分


安装

使用

    from cnn_code_tool import Code_tool
    ct=Code_tool(charset,model_path,train_path,test_path,label_resolve)
    # charset 验证码的所有字符集
    # model_path 模型路径,训练完后模型将会保存在此路径下,推测验证码时模型将会从该路径下导入模型
    # train_path 训练数据路径,模型训练时使用
    # test_path 测试数据路径,模型训练时使用
    # label_resolve 从文件名解析出标签的函数,模型训练时使用
    ct.train()
    captcha=ct.infer_file('captcha_img_filename') # 导入并推测验证码图片的验证码

帮助

第二部分

致爱学习的程序员的一部分


说明

开始

train()代码

```python
'''
参数:
    epochs:     训练集迭代次数
    target_ac:  target_ac目标命中率,当模型达到该命中率时不管是否达到迭代次数都会退出训练
    retrain:    True表示重新训练,False表示导入self.__model_path路径下最近更新的一个模型继续训练
    keep_prob:  即tf.nn.dropout(x, keep_prob)的第二个参数,该参数在测试集测试时将不会生效
'''
def train(self, epochs=10, target_ac=1.,keep_prob=1.,retrain=True):
    if self.__input_path is None or self.__test_input_path is None:
        print('__input_path或__test_input_path缺失')
        return
    self.__startwork(epochs)
    #   开始训练
    with tf.Session() as sess:
        if retrain:
            self.__init_cnn()
            save = tf.train.Saver()
            sess.run(tf.global_variables_initializer())
            step = 0
        else:
            cp = tf.train.latest_checkpoint(self.__model_path)
            save = tf.train.import_meta_graph(cp + '.meta')
            save.restore(sess, cp)
            step = int(sess.run('g_v:0'))
        while True:
            try:
                img, label = self.__generate_next_batch()
            except NullDataException:
                break
            loss, _ = sess.run(['loss:0', 'train'],
                               feed_dict={'i_p:0': img, 'l_p:0': label, 'k_p:0': keep_prob})
            print('步数为:{}\tloss:{}'.format(step, loss))
            if step % 50 == 0:
                test_img, test_label = self.__test_queue.get()
                # 这里的命中率是针对单个字符的不代表真正的命中率
                actual_ac = sess.run('accuracy:0',
                                     feed_dict={'i_p:0': test_img, 'l_p:0': test_label,
                                                'k_p:0': 1.})
                print('步数为:{}--------------------------------------命中率:{}'.format(step, actual_ac))
                if actual_ac >= target_ac:
                    break
            step += 1
        # 保存
        tf.summary.FileWriter(self.__model_path, sess.graph)            
        g_step = tf.get_default_graph().get_tensor_by_name('g_v:0')
        tf.assign(g_step, step, name='update')
        sess.run('update:0')
        self.__endwork()
        print('保存模型中请等待!')
        save.save(sess, self.__model_path + 'model', global_step=step)
        print('完成')
```

定义模型

    if retrain:
        self.__init_cnn()
        save = tf.train.Saver() # 在这里不重要
        sess.run(tf.global_variables_initializer())
        step = 0    # 在这里不重要

训练模型

    # self.__init_cnn()方法内部使用了标准的正态分布来初始化卷积核
    weight = tf.Variable(w_alpha * tf.random_normal(ksize),name=w_name) # 初始化卷积核
    # weight = tf.Variable(w_alpha * tf.zeros(ksize),name=w_name) 全初始化为0,请不要这做!!
    loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=label_b, logits=out),name='loss')
    train_op = tf.train.AdamOptimizer().minimize(loss, name='train') # 训练的operations
    tf.run(train_op,args......) # 把返回的变量直接传进run方法内
    # tf.run('train',args......)  或者通过operations的name属性

结语

这篇文章断断续续写了一个星期,基本上把我认为比较重要都写了,有的地方觉得写的不好,反复改了几次。如果有什么写错,或者写的不好请多多谅解,或者你可以通过简书私信告知我,我会虚心接受。

上一篇下一篇

猜你喜欢

热点阅读