ypwhs / captcha_break Goto Github PK
View Code? Open in Web Editor NEW验证码识别
License: MIT License
验证码识别
License: MIT License
用ctc的方式训练完成,model保存为loss_ctc_best.h5, best_model保存为ctc_best.h5,我以什么样的方式能重新载入这个模型继续进行训练呢?
大佬 能讲一下为什么训练的是model而测试的是base_model呢?我看了你的解释但是没看懂
out = K.get_value(K.ctc_decode(y_pred, input_length=np.ones(shape[0]) * shape[1])[0][0])[:, :4]
每个字符的概率该如何读出,我对RNN不熟悉,请大佬指点迷津,万分感谢
可以不动模型参数吗?还是说要改动输入呢?
y = [np.zeros((batch_size, n_class), dtype=np.uint8) for i in range(n_len)] 这里应该怎么修改呢
def ctc_lambda_func(args):
y_pred, labels, input_length, label_length = args
y_pred = y_pred[:, 2:, :]
return K.ctc_batch_cost(labels, y_pred, input_length, label_length)
Can any one explain the mean of y_pred[:, 2:, :]?
Does this "2" have any particular mean?
Thanks a lot.
Hi @ypwhs,
I tired to load the 'model.h5' weights to the CTC model, by using Keras 2.1 and Python 3.6
The network architecture is as the same as yours.
After evaluation, the accuracy is 0.005.
Any ideas on it?
Thanks.
I found it can only recognize captcha generate from the python captcha lib.
It didn't work when I give it different style 4 size char+number .
Since it is hard to mock a captcha with different style every time. I wonder is there any more generic way to do this?
What I can imagine is :
Could you give me some tips?
加了ctc_loss gru后, 为啥输入的图片需要旋转, 而水平输入到gru呢?
使用过程中发现,代码里面需要提前定义训练集图片的大小(width,height),即训练集的图片像素必须统一,这样导致模型泛化能力很弱,不能预测其他像素的图片
您说:添加 workers=4 参数让 Keras 自动实现多进程生成数据,摆脱 python 单线程效率低的缺点。
然而我加了后反而没法运行,这是为什么?怀疑和版本有关,能提供keras版本吗?
还有个问题,图片不用变成灰度图吗,用彩图训练不太好吧
假设训练集**有10000张图片,在D盘下的test子目录下,图片从1.jpg-10000.jpg。
pytorch版本使用的是1.1.0;
系统是Ubuntu16.04;
代码基本没有修改,只是改了输入图片的尺寸为96*34
后,对应的生成器其中的参数n_input_length = 6
也进行了修改,并未报错。
训练中,loss总是会变为nan,尝试着改batch_size和lr,也只能让其晚出现2个epoch左右,acc至多变为70左右。
求指点啊TAT
In this place, I got the error:
13 x = Reshape(target_shape=(int(conv_shape[1]), int(conv_shape[2]*conv_shape[3])))(x)
14
---> 15 x = Dense(32, activation='relu')(x)
16
17 gru_1 = GRU(rnn_size, return_sequences=True, init='he_normal', name='gru1')(x)
请问怎么启动项目?
报错是这样的: ValueError: Unknown loss
function:《lambda》
然后我改成这样
model = load_model(os.path.join(KERAS_MODEL_PATH, 'cnn.h5'),
custom_objects={'ctc': lambda y_true, y_pred: y_pred})
还是报错,求解。谢谢
如果我想把训练好的模型保存下来,并做成一个服务,你这个模型改怎么保存啊?
您好,请问模型中的四层全连接层是否对应着验证码中的四个字符?或者说全连接层的个数和验证码中字符的个数有无对应关系,因为当我再减小全连接层个数的时候会报错模型期望的数组个数和实际得到的数组个数不一致,但是当将n_class参数也进行相应的修改,比如n_class变为5,全连接层也为5个时,就不会报错。
我的环境如下:
win10 Anaconda3 python3.6 tensorflow1.13.1-gpu cudn10.0
tensorflow已经安装好,并且使用import tensorflow as tf测试安装没有问题
运行ctc_2019.ipynb时,前面都通过,运行到训练脚本部分,后台一直报错如下:
Traceback (most recent call last):
File "", line 1, in
File "d:\softwares\anaconda3-64\envs\shy\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "d:\softwares\anaconda3-64\envs\shy\lib\multiprocessing\spawn.py", line 115, in _main
self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'CaptchaSequence' on <module 'main' (built-in)>
Traceback (most recent call last):
File "", line 1, in
File "d:\softwares\anaconda3-64\envs\shy\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "d:\softwares\anaconda3-64\envs\shy\lib\multiprocessing\spawn.py", line 115, in _main
self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'CaptchaSequence' on <module 'main' (built-in)>
Traceback (most recent call last):
File "", line 1, in
File "d:\softwares\anaconda3-64\envs\shy\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "d:\softwares\anaconda3-64\envs\shy\lib\multiprocessing\spawn.py", line 115, in _main
self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'CaptchaSequence' on <module 'main' (built-in)>
Traceback (most recent call last):
File "", line 1, in
File "d:\softwares\anaconda3-64\envs\shy\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "d:\softwares\anaconda3-64\envs\shy\lib\multiprocessing\spawn.py", line 115, in _main
self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'CaptchaSequence' on <module 'main' (built-in)>
[I 10:42:01.964 NotebookApp] Saving file at /ctc_2019.ipynb
比如自己测试集在“当前目录的test的文件夹”里面
因为我使用的keras版本是keras2, 所以把网络结构定义和训练的代码做了一些修改,但是输出的每个字符的准确率一直在0.028左右徘徊,这个就是完全随机1/36的概率,烦请看一下代码是不是有问题
我使用的python版本是2.7.13,keras版本是2.0.2,都是使用anaconda安装的
我已经尝试过修改参数初始化方式(使用Xavier方法),修改优化方法(sgd,RMSprop等),调节学习率(0.1-10),修改batch_size等都没有效果。
我修改后的代码如下:
from keras.models import *
from keras.layers import *
from keras.optimizers import *
input_tensor = Input(shape = (height, width, 3))
x = input_tensor
for i in range(4):
x = Conv2D(32 * 2 ** i, (3, 3), activation = 'relu')(x)
x = Conv2D(32 * 2 ** i, (3, 3), activation = 'relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Flatten()(x)
x = Dropout(rate = 0.25)(x)
x = [Dense(n_class, activation='softmax', name='c{}'.format(i))(x) for i in range(n_len)]
model = Model(inputs = input_tensor, outputs = x)
model.compile(optimizer = 'adadelta', loss='categorical_crossentropy', metrics=['accuracy'])
from keras.callbacks import EarlyStopping
#early_stop = EarlyStopping(monitor='val_loss', patience=2)
model.fit_generator(gen(), steps_per_epoch = 1600, epochs = 10, validation_steps = 40, validation_data = gen())
如题,非常感谢,请问您有什么建议吗?
您好,在运行ctc_2019.ipynb时,一个epoch跑完以后,进入到evaluate()函数后,就一直不在进行第二个epoch,电脑的性能很好,8G的显卡,是不是evaluate()函数的计算时间太长了,这个跟用不用GPU版的加速训练有关系吗?
你好!
我在使用Python3执行到这一句时报错了:
from keras.utils.visualize_util import plot
提示无法找到模块
搜索之后发现visualize_util已经被更名为了vis_utils,
plot被更名为了plot_model.
is possible break this?
here are generator https://github.com/letarg0/obrazy
仓库里只有ctc的模型,没找到cnn的。
可以的话麻烦提供下,谢谢。
您好,我看到您了程序,有3点疑惑:
1)由于我们使用的是循环神经网络,所以默认丢掉前面两个输出,因为它们通常无意义,且会影响模型的输出。
请问这是为什么啊?还有,“前面两个输出”指的是什么?
2) “y_pred 是模型的输出,是按顺序输出的37个字符的概率,因为我们这里用到了循环神经网络,所以需要一个空白字符的概念;”, 为什么“用到了循环神经网络,所以需要一个空白字符的概念”?
3)如果是实际中一段的语音,比如 0.2s---1.8s 是“哦”, 3.4s----6.4s是“嗨”, 这样的事件,该如何制作相应的标签?
希望您可以留下邮箱或者QQ微信,希望可以得到您的回复。
您好!我将从ctc_pytorch改为py文件运行,在我本地电脑运行没有错误,改为远程服务器时出现以下错误:
liurui@eversec-desktop:~/yzmre$ python ctc.py
File "ctc.py", line 64
modules[f'conv{name}'] = nn.Conv2d(in_channels, out_channels, kernel_size, padding=(1, 1) if kernel_size == 3 else 0)
^
SyntaxError: invalid syntax
请问您知道这是什么原因吗
TensorFlow版本使用的是1.12.0;
系统是Ubuntu16.04;
代码基本没有修改,只是改了输入图片的尺寸后,对应的生成器其中的参数也进行了修改并未报错。
在运行
model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=Adam(1e-3, amsgrad=True))
model.fit_generator(train_data, epochs=100, validation_data=valid_data, workers=4, use_multiprocessing=True,
callbacks=callbacks)
当运行到第一个epoch的999step的时候就停止了,输入只有:
Epoch 1/100
999/1000 [============================>.] - ETA: 0s - loss: 4.6288WARNING:tensorflow:From /home/shizai/anaconda3/envs/baiqiao/lib/python3.6/site-packages/tensorflow/python/keras/backend.py:4831: sparse_to_dense (from tensorflow.python.ops.sparse_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Create a `tf.sparse.SparseTensor` and use `tf.sparse.to_dense` instead.
求解答。
WARNING:tensorflow:From /home/qgb/.local/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
/root/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:8: UserWarning: Update your Conv2D
call to the Keras 2 API: Conv2D(32, (3, 3), activation="relu")
Conv2D
call to the Keras 2 API: Conv2D(32, (3, 3), activation="relu")
GRU
call to the Keras 2 API: GRU(128, return_sequences=True, name="gru1", kernel_initializer="he_normal")
GRU
call to the Keras 2 API: GRU(128, return_sequences=True, go_backwards=True, name="gru1_b", kernel_initializer="he_normal")
TypeError Traceback (most recent call last)
in
17 gru_1 = GRU(rnn_size, return_sequences=True, init='he_normal', name='gru1')(x)
18 gru_1b = GRU(rnn_size, return_sequences=True, go_backwards=True, init='he_normal', name='gru1_b')(x)
---> 19 gru1_merged = merge([gru_1, gru_1b], mode='sum')
20
21 gru_2 = GRU(rnn_size, return_sequences=True, init='he_normal', name='gru2')(gru1_merged)
TypeError: 'module' object is not callable
这个验证码识别平台有人用过吗 http://www.damagou.top 注册就送100提分,我注册试了下,还可以
现在运行ctc'代码时出现这个问题,我想问下你当初的tensorflow的版本是哪个
在构建cnn模型的时候:
input_tensor = Input((height, width, 3))
x = input_tensor
for i, n_cnn in enumerate([2, 2, 2, 2, 2]):
############
for j in range(n_cnn):
# 这里为什么要循环两次呢?
x = Conv2D(32 * 2 ** min(i, 3), kernel_size=3, padding='same', kernel_initializer='he_uniform')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = MaxPooling2D(2)(x)
x = Flatten()(x)
x = [Dense(n_class, activation='softmax', name='c%d' % (i + 1))(x) for i in range(n_len)]
model = Model(inputs=input_tensor, outputs=x)
Hello ypwhs,
On the ctc code you are creating a model called model:
model = Model(input=[input_tensor, labels, input_length, label_length], output=[loss_out])
And that is the one you train, but when you make the prediction you use a the model called base_model.
y_pred = base_model.predict(X_test)
Why is that? Is it correct?
Shouldn't you use model.predict
? If yes, what would be a correct way to call it, since is waiting for 4 parameters, what should it be sent on "labels", "input_length" and "label_length".
Thank you.
这个不需要对图片中字符进行字符切割吗?captcha 验证码
我现在把需要训练的图片存入到samples文件下,比如:AB67HG.jpeg,然后我读入数据
rnn_size = 128
characters = string.digits + string.ascii_uppercase
width,height,n_len,n_class= 140,44,6,len(characters)
folder = "sample"
imageList = os.listdir(folder)
imageList = [os.path.join(folder,item) for item in imageList if os.path.isfile(os.path.join(folder,item))]
image_size = len(imageList)
image_array = np.zeros((image_size,height,width,3),dtype=np.uint8)
image_names = []
for i in range(image_size):
img = Image.open(imageList[i])
image_array [i]=img
image_names.append(imageList[i][-11:-5].upper()
def gen(batch_size=128):
X = np.zeros((batch_size, width, height, 3), dtype=np.uint8)
y = np.zeros((batch_size, n_len), dtype=np.uint8)
while True:
for i in range(batch_size):
num = random.randint(0, image_size - 1)
random_str = image_names[num]
X[i] = np.array(image_array[num]).transpose(1, 0, 2)
y[i] = [characters.find(x) for x in random_str]
yield [X, y, np.ones(batch_size) * int(conv_shape[1] - 2), np.ones(batch_size) * n_len], np.ones(batch_size)
显示这个错误,
InvalidArgumentError (see above for traceback): Saw a non-null label (index >= num_classes - 1) following a null label, batch: 75 num_classes: 36 labels:
[[Node: ctc/CTCLoss = CTCLoss[ctc_merge_repeated=true, ignore_longer_outputs_than_inputs=false, preprocess_collapse_repeated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](ctc/Log/_97, ctc/ToInt64/_99, ctc/ToInt32_2/_101, ctc/ToInt32_1/_103)]]
我使用的keras是2.0.3,tensorflow-gpu(1.2.1),用cpu可以运行,但是gpu出问题
input_length = Input(name='input_length', shape=[1], dtype='int64')
这个形状是(?,1)把最后的?是怎么变为15的
您好,我的标签是四位,训练完了后看效果是,发现还有输出结果只有3位的情况
你好,我使用你的cnn模型时并不能收敛,loss越来越高。我加了BN解决了问题,但是我不太明白为什么一定需要加BN。
此外,我发现在使用ImageCaptcha生成验证码的时候,当使用单一字体验证码时,模型能够很好的学习,但我使用20种不同字体去生成验证码,训练集能够很好的学习,但是验证集一直的loss一直没有下降,样本数量30000,这种过拟合的情况需要怎么解决呢?谢谢。
yield [X, y, np.ones(batch_size)*int(conv_shape[1]-2), np.ones(batch_size)*n_len], np.ones(batch_size)
为什么这里要返回一个np.ones(batch_size)是为了和fit_generate要求的输入匹配吗,不返回真实的label也不会出现问题吗?
我的python是3.7版本的,tensorflow-gpu 安装不了了,最好能把依赖包版本给出来比较好。
我已经完成原版keras的使用,但ctc版本有所不同,关于生成器参数多出来两个,请问这两个参数的具体用途是?请问这两个参数该如何理解?
因为要读取PNG, 所以将参数改为
width, height, n_len, n_classes = 120, 32, 4, len(characters)
last_channel = 4
model = Model(n_classes, input_shape=(4, height, width))
报错信息是:
“RuntimeError: Expected input_lengths to have value at most 7, but got value 12 (while checking arguments for ctc_loss_gpu)”
烦请指教,谢谢!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.