keras_cnn.py 训练及建模

#!/usr/bin/env python
# coding=utf- """
利用keras cnn进行端到端的验证码识别, 简单直接暴力。
迭代100次可以达到95%的准确率,但是很容易过拟合,泛化能力糟糕, 除了增加训练数据还没想到更好的方法. __autho__: jkmiao
__email__: miao1202@.com
___date__:-- """
from keras.models import Model
from keras.layers import Dense, Dropout, Flatten, Input, merge
from keras.layers import Convolution2D, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
from PIL import Image
import os, random
import numpy as np
from keras.models import model_from_json
from util import CharacterTable
from keras.callbacks import EarlyStopping
from sklearn.model_selection import train_test_split
# from keras.utils.visualize_util import plot def load_data(path='img/clearNoise/'):
fnames = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('jpg')]
random.shuffle(fnames)
data, label = [], []
for i, fname in enumerate(fnames):
imgLabel = fname.split('/')[-].split('_')[]
if len(imgLabel)!=:
print 'error: ', fname
continue
imgM = np.array(Image.open(fname).convert('L'))
imgM = * (imgM>)
data.append(imgM.reshape((, , )))
label.append(imgLabel.lower())
return np.array(data), label ctable = CharacterTable()
data, label = load_data()
print data[].max(), data[].min()
label_onehot = np.zeros((len(label), ))
for i, lb in enumerate(label):
label_onehot[i,:] = ctable.encode(lb)
print data.shape, data[-].max(), data[-].min()
print label_onehot.shape datagen = ImageDataGenerator(shear_range=0.08, zoom_range=0.08, horizontal_flip=False,
rotation_range=, width_shift_range=0.06, height_shift_range=0.06) datagen.fit(data) x_train, x_test, y_train, y_test = train_test_split(data, label_onehot, test_size=0.1) DEBUG = False # 建模
if DEBUG:
input_img = Input(shape=(, , )) inner = Convolution2D(, , , border_mode='same', activation='relu')(input_img)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
encoder_a = Flatten()(inner) inner = Convolution2D(, , , border_mode='same', activation='relu')(input_img)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
encoder_b = Flatten()(inner) inner = Convolution2D(, , , border_mode='same', activation='relu')(input_img)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
inner = MaxPooling2D(pool_size=(,))(inner)
inner = Convolution2D(, , , border_mode='same')(inner)
encoder_c = Flatten()(inner) input = merge([encoder_a, encoder_b, encoder_c], mode='concat', concat_axis=-)
drop = Dropout(0.5)(input)
flatten = Dense()(drop)
flatten = Dropout(0.5)(flatten) fc1 = Dense(, activation='softmax')(flatten)
fc2 = Dense(, activation='softmax')(flatten)
fc3 = Dense(, activation='softmax')(flatten)
fc4 = Dense(, activation='softmax')(flatten)
fc5 = Dense(, activation='softmax')(flatten)
fc6 = Dense(, activation='softmax')(flatten)
merged = merge([fc1, fc2, fc3, fc4, fc5, fc6], mode='concat', concat_axis=-) model = Model(input=input_img, output=merged)
else:
model = model_from_json(open('model/ba_cnn_model3.json').read())
model.load_weights('model/ba_cnn_model3.h5') # 编译
# model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
model.summary()
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # plot(model, to_file='model3.png', show_shapes=True) # 训练 early_stopping = EarlyStopping(monitor='val_loss', patience=) model.fit_generator(datagen.flow(x_train, y_train, batch_size=), samples_per_epoch=len(x_train), nb_epoch=, validation_data=(x_test, y_test), callbacks=[early_stopping] ) json_string = model.to_json()
with open('./model/ba_cnn_model4.json', 'w') as fw:
fw.write(json_string)
model.save_weights('./model/ba_cnn_model4.h5') print 'done saved model cnn3' # 测试
y_pred = model.predict(x_test, verbose=)
cnt =
for i in range(len(y_pred)):
guess = ctable.decode(y_pred[i])
correct = ctable.decode(y_test[i])
if guess == correct:
cnt +=
if i%==:
print '--'*, i
print 'y_pred', guess
print 'y_test', correct
print cnt/float(len(y_pred))

apicode.py  模型使用

#!/usr/bin/env python
# coding=utf- from util import CharacterTable
from keras.models import model_from_json
from PIL import Image
import matplotlib.pyplot as plt
import os
import numpy as np
from prepare import clearNoise def img2vec(fname):
data = []
img = clearNoise(fname).convert('L')
imgM = 1.0 * (np.array(img)>)
print imgM.max(), imgM.min()
data.append(imgM.reshape((, , )))
return np.array(data), imgM ctable = CharacterTable() model = model_from_json(open('model/ba_cnn_model4.json').read())
model.load_weights('model/ba_cnn_model4.h5') def test(path):
fnames = [ os.path.join(path, fname) for fname in os.listdir(path) ][:]
correct =
for idx, fname in enumerate(fnames, ):
data, imgM = img2vec(fname)
y_pred = model.predict(data)
result = ctable.decode(y_pred[])
label = fname.split('/')[-].split('_')[]
if result == label:
correct +=
print 'correct', fname
else:
print result, label
print 'accuracy: ',idx, float(correct)/idx
print '=='*
# plt.subplot()
# plt.imshow(Image.open(fname).convert('L'), plt.cm.gray)
# plt.title(fname)
#
# plt.subplot()
# plt.imshow(imgM, plt.cm.gray)
# plt.title(result)
# plt.show() test('test')

cnn进行端到端的验证码识别改进的更多相关文章

  1. 基于tensorflow的‘端到端’的字符型验证码识别源码整理(github源码分享)

    基于tensorflow的‘端到端’的字符型验证码识别 1   Abstract 验证码(CAPTCHA)的诞生本身是为了自动区分 自然人 和 机器人 的一套公开方法, 但是近几年的人工智能技术的发展 ...

  2. 基于python语言的tensorflow的‘端到端’的字符型验证码识别源码整理(github源码分享)

    基于python语言的tensorflow的‘端到端’的字符型验证码识别 1   Abstract 验证码(CAPTCHA)的诞生本身是为了自动区分 自然人 和 机器人 的一套公开方法, 但是近几年的 ...

  3. CNN+BLSTM+CTC的验证码识别从训练到部署

    项目地址:https://github.com/kerlomz/captcha_trainer 1. 前言 本项目适用于Python3.6,GPU>=NVIDIA GTX1050Ti,原mast ...

  4. 【转】CNN+BLSTM+CTC的验证码识别从训练到部署

    [转]CNN+BLSTM+CTC的验证码识别从训练到部署 转载地址:https://www.jianshu.com/p/80ef04b16efc 项目地址:https://github.com/ker ...

  5. [验证码识别技术] 字符型验证码终结者-CNN+BLSTM+CTC

    验证码识别(少样本,高精度)项目地址:https://github.com/kerlomz/captcha_trainer 1. 前言 本项目适用于Python3.6,GPU>=NVIDIA G ...

  6. Python实现各类验证码识别

    项目地址: https://github.com/kerlomz/captcha_trainer 编译版下载地址: https://github.com/kerlomz/captcha_trainer ...

  7. 基于SVM的字母验证码识别

    基于SVM的字母验证码识别 摘要 本文研究的问题是包含数字和字母的字符验证码的识别.我们采用的是传统的字符分割识别方法,首先将图像中的字符分割出来,然后再对单字符进行识别.首先通过图像的初步去噪.滤波 ...

  8. [验证码识别技术]字符验证码杀手--CNN

    字符验证码杀手--CNN 1 abstract 目前随着深度学习,越来越蓬勃的发展,在图像识别和语音识别中也表现出了强大的生产力.对于普通的深度学习爱好者来说,一上来就去跑那边公开的大型数据库,比如I ...

  9. 强智教务系统验证码识别 Tensorflow CNN

    强智教务系统验证码识别 Tensorflow CNN 一直都是使用API取得数据,但是API提供的数据较少,且为了防止API关闭,先把验证码问题解决 使用Tensorflow训练模型,强智教务系统的验 ...

随机推荐

  1. mysql 服务器启用event_scheduler

    https://blog.csdn.net/yangzefei1991/article/details/51800867 首先在sql中查询计划事件的状态:SHOW VARIABLES LIKE 'e ...

  2. jdreact转换为H5注意事项

    1:先执行npm install 然后执行 npm run web-init  配置完后 在执行 npm run web-start(注意的是不要根据文档执行 yarn add -D @jdreact ...

  3. MySQL--NUMA与MySQL

    ============================================================= NUMA(Non-Uniform Memory Access),非一致性内存 ...

  4. 使用ipns 为ipfs 系统自定义域名

    ipns 可以帮助我们进行寻址操作,但是默认的hashid 还是太长,不好记忆,ipns 同时也支持 基于域名的解析,我们添加txt 记录就可以方便的解决ipfs 文件访问地址难记的问题,使用的是 一 ...

  5. nginx配置.htaccess伪静态

    https://blog.csdn.net/moqiang02/article/details/37695775

  6. 用Promise对象实现的 Ajax 操作

  7. JDK8中的时间API

    在Java 1.0中,对日期和时间的支持只能依赖java.util.Date类.正如类名所表达的,这个类无法表示日期,只能以毫秒的精度表示时间.更糟糕的是它的易用性,由于某些原因未知的设计决策,这个类 ...

  8. ElasticSearch(六)底层索引控制

    相似度算法 涉及到了ES的底层,首先讲一下ES的底层核心,相似度模型,ES的查询和传统的数据库查询最大的差别就在相似度查询(之前讲过,索引存储的最大差别就是讲非结构化数据转化为结构化),ES里面会给文 ...

  9. Hanlp分词之CRF中文词法分析详解

    这是另一套基于CRF的词法分析系统,类似感知机词法分析器,提供了完善的训练与分析接口. CRF的效果比感知机稍好一些,然而训练速度较慢,也不支持在线学习. 默认模型训练自OpenCorpus/pku9 ...

  10. hanlp源码解析之中文分词算法详解

    词图 词图指的是句子中所有词可能构成的图.如果一个词A的下一个词可能是B的话,那么A和B之间具有一条路径E(A,B).一个词可能有多个后续,同时也可能有多个前驱,它们构成的图我称作词图. 需要稀疏2维 ...