# 生成一个训练batch defget_next_batch(batch_size=32):# 创建2个空数组, 用来存放一个批次的数据whileTrue:
batch_x = np.zeros((batch_size, height, width, 3))
batch_y = [np.zeros((batch_size, n_class)) for i in range(captcha_size)]
# 有时生成图像大小不是(60, 160, 3) defwrap_gen_captcha_text_and_image():whileTrue:
text, image = gen_captcha_text_and_image()
if image.shape == (60, 160, 3):
return text, image
for i in range(batch_size):
text, image = gen_captcha_text_and_image()
batch_x[i,:] = image
# one-hot编码labelfor j, ch in enumerate(text):
batch_y[j][i, :] = 0
batch_y[j][i, char_set.find(ch)] = 1yield batch_x, batch_y
5. 创建网络模型
from keras.models import *
from keras.layers import *
import numpy as np
import keras
defVGG():
input_tensor = Input((height, width, 3))
x = input_tensor
x = Conv2D(32, (3, 3), activation='relu', padding='SAME')(x)
x = Conv2D(32, (3, 3), activation='relu', padding='SAME')(x)
x = MaxPooling2D((2, 2), padding='SAME')(x)
x = Conv2D(64, (3, 3), activation='relu', padding='SAME')(x)
x = Conv2D(64, (3, 3), activation='relu', padding='SAME')(x)
x = MaxPooling2D((2, 2), padding='SAME')(x)
x = Conv2D(128, (3, 3), activation='relu', padding='SAME')(x)
x = Conv2D(128, (3, 3), activation='relu', padding='SAME')(x)
x = MaxPooling2D((2, 2), padding='SAME')(x)
x = Conv2D(256, (3, 3), activation='relu', padding='SAME')(x)
x = Conv2D(256, (3, 3), activation='relu', padding='SAME')(x)
x = MaxPooling2D((2, 2), padding='SAME')(x)
x = Flatten()(x)
x = Dropout(0.3)(x)
x = [Dense(n_class, activation='softmax', name='c%d'%(i+1))(x) for i in range(4)]
model = Model(inputs=input_tensor, outputs=x)
return model
model = VGG()
model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])