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. 《DSP using MATLAB》Problem 5.24-5.25-5.26

    代码: function y = circonvt(x1,x2,N) %% N-point Circular convolution between x1 and x2: (time domain) ...

  2. java gaoji 算法

    import java.util.Scanner; public  class Main{     public static int[] Test(int[] a){         int [] ...

  3. 【BZOJ1878】【SDOI2009】 HH的项链

    莫队模板题,比较简单 原题: HH有一串由各种漂亮的贝壳组成的项链.HH相信不同的贝壳会带来好运,所以每次散步 完后,他都会随意取出一段贝壳,思考它们所表达的含义.HH不断地收集新的贝壳,因此, 他的 ...

  4. LG4196 [CQOI2006]凸多边形

    题意 题目描述 逆时针给出n个凸多边形的顶点坐标,求它们交的面积.例如n=2时,两个凸多边形如下图: 则相交部分的面积为5.233. 输入输出格式 输入格式: 第一行有一个整数n,表示凸多边形的个数, ...

  5. Jenkins部署项目

    第三首先部署好Jenkins 新建一个自由项目 svn地址,credentials是指认证,点击Ad那里添加,并选择username和password方式,并输入用户名和密码 H/5 * * * * ...

  6. Java和C++的区别杂记

    1.java中的作用域描述符(类比于C++是通过"."来实现,Java中"类名.静态成员名",C++中"类名::静态成员名" 2.java中 ...

  7. 使用tailor 轻松方便的集成web 框架react&&vue

    tailor 是一款很方便的layout 服务,类似facebook 的bigpipe,我们可以使用此工具 方便的集成各类web 框架,实现micro-fronteds 开发 参考demo https ...

  8. IAR intrinsic functions

    You can insert asm code example asm("NOP") into the c or c++ source code to get a good per ...

  9. No MaterialLocalizations found (Flutter)

    在显示SimpleDialog时候程序报错 No MaterialLocalizations found 没有找到 MaterialLocalizations 搜索找到原因 runApp 需要先调用 ...

  10. django配置setting文件

    添加app到INSTALLED_APPS列表中 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.co ...