活动地址:CSDN21天学习挑战赛
前言
本周的任务有3个,预测股票,识别验证码,识别眼睛状态。因为任务不同,那么可能会使用到不同的预处理、网络等等。
本节主要学习验证码识别。
一、拆解任务
首先需要了解这次需要处理的任务,这里贴一张老师的数据展示图。
数据分为图片及其对应的标签,且这个标签包含数字和字母。
二、学习内容
这个任务比较不一样的是他的表情是一串字符。传统的ocr的做法应该是先定位裁剪每个字符,然后一个个字(符)解析。
1. 数据处理
(1)先读数据
data_dir = "D:/jupyter notebook/DL-100-days/datasets/captcha"
data_dir = pathlib.Path(data_dir)
all_image_paths = list(data_dir.glob('*'))
all_image_paths = [str(path) for path in all_image_paths]
# 打乱数据
random.shuffle(all_image_paths)
# 获取数据标签
all_label_names = [path.split("\\")[5].split(".")[0] for path in all_image_paths]
image_count = len(all_image_paths)
print("图片总数为:",image_count)
(2)处理标签
这里的做法是 把 标签转为数字。
假如 a-> 0 b->2 1->28,那么标签可以转为ab1 -> [ 0 2 28 ]。
number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
char_set = number + alphabet
char_set_len = len(char_set)
label_name_len = len(all_label_names[0])
# 将字符串数字化
def text2vec(text):
vector = np.zeros([label_name_len, char_set_len])
for i, c in enumerate(text):
idx = char_set.index(c)
vector[i][idx] = 1.0
return vector
all_labels = [text2vec(i) for i in all_label_names]
(3)对图片进行预处理
这里的预处理是读图片、变为灰度图、resize、归一化。
def preprocess_image(image):
image = tf.image.decode_jpeg(image, channels=1)
image = tf.image.resize(image, [50, 200])
return image/255.0
def load_and_preprocess_image(path):
image = tf.io.read_file(path)
return preprocess_image(image)
(4)加载数据、配置数据
这里有一个特别的东西,如何优化计算资源。
在做训练的时候,一般分为两种资源,cpu和gpu。
cpu主要对io进行读写,对数据做预处理。gpu主要是进行深度学习计算。
要提高计算速度,最理想的情况就是,gpu在做当轮计算的时候,cpu执行下一轮的图片、预处理等执行,prefetch就是执行以上的函数。
第一张图是不使用prefetch,第二张图是使用prefetch。使用prefetch能更合理减少系统空闲时间。
具体实现代码:
AUTOTUNE = tf.data.experimental.AUTOTUNE
path_ds = tf.data.Dataset.from_tensor_slices(all_image_paths)
image_ds = path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)
label_ds = tf.data.Dataset.from_tensor_slices(all_labels)
image_label_ds = tf.data.Dataset.zip((image_ds, label_ds))
image_label_ds
train_ds = image_label_ds.take(1000) # 前1000个batch
val_ds = image_label_ds.skip(1000) # 跳过前1000,选取后面的
BATCH_SIZE = 16
train_ds = train_ds.batch(BATCH_SIZE)
train_ds = train_ds.prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.batch(BATCH_SIZE)
val_ds = val_ds.prefetch(buffer_size=AUTOTUNE)
val_ds
2. 建立神经网络
老师给了一个简单的神经网络。这里先用老师的模型测试,后面再试着优化模型。
from tensorflow.keras import datasets, layers, models
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(50, 200, 1)),#卷积层1,卷积核3*3
layers.MaxPooling2D((2, 2)), #池化层1,2*2采样
layers.Conv2D(64, (3, 3), activation='relu'), #卷积层2,卷积核3*3
layers.MaxPooling2D((2, 2)), #池化层2,2*2采样
layers.Flatten(), #Flatten层,连接卷积层与全连接层
layers.Dense(1000, activation='relu'), #全连接层,特征进一步提取
layers.Dense(label_name_len * char_set_len),
layers.Reshape([label_name_len, char_set_len]),
layers.Softmax() #输出层,输出预期结果
])
# 打印网络结构
model.summary()
2.训练神经网络
训练过程,其实和之前做过的例子都没啥差别。
model.compile(optimizer="adam",
loss='categorical_crossentropy',
metrics=['accuracy'])
3.预测和模型评估
预测和评估也是和之前的练习相似。
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
# 保存模型
model.save('model/12_model.h5')
# 加载模型
new_model = tf.keras.models.load_model('model/12_model.h5')
# 预测
def vec2text(vec):
"""
还原标签(向量->字符串)
"""
text = []
for i, c in enumerate(vec):
text.append(char_set[c])
return "".join(text)
plt.figure(figsize=(10, 8)) # 图形的宽为10高为8
for images, labels in val_ds.take(1):
for i in range(6):
ax = plt.subplot(5, 2, i + 1)
# 显示图片
plt.imshow(images[i])
# 需要给图片增加一个维度
img_array = tf.expand_dims(images[i], 0)
# 使用模型预测验证码
predictions = model.predict(img_array)
plt.title(vec2text(np.argmax(predictions, axis=2)[0]))
plt.axis("off")
总结
本章从验证码识别出发,了解了一些其它标签要怎么处理。本节里面只是跑通了老师的模型,后续要试着优化模型~