这个模型识别车牌的准确率 简直可怕!
文章目录
一、前期工作
1.设置GPU
2.导入数据
3.数据可视化
4.标签数字化
二、构建一个tf.data.Dataset1.预处理函数
2.加载数据
3.配置数据
三、搭建网络模型
四、设置动态学习率
五、编译
六、训练
七、模型评估
八、保存和加载模型
九、预测
一、前期工作
本文将手把手教你用TensorFlow2实现车牌识别
,整个项目的完整代码都在文章了哈,大家按顺序copy即可运行。
我的环境:
语言环境:Python3.6.5 编译器:jupyter notebook 深度学习环境:TensorFlow2.4.1 数据:https://pan.baidu.com/s/1rnnRok-4fxFuWJrwB4ls9Q 提取码:povi
1.设置GPU
如果使用的是CPU可以注释掉这部分的代码,不影响运行。
import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")
if gpus:
tf.config.experimental.set_memory_growth(gpus[0], True) #设置GPU显存用量按需使用
tf.config.set_visible_devices([gpus[0]],"GPU")
2.导入数据
import matplotlib.pyplot as plt
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
import os,PIL,random,pathlib
# 设置随机种子尽可能使结果可以重现
import numpy as np
np.random.seed(1)
# 设置随机种子尽可能使结果可以重现
import tensorflow as tf
tf.random.set_seed(1)
data_dir = "D:/jupyter notebook/DL-100-days/datasets/015_licence_plate"
data_dir = pathlib.Path(data_dir)
pictures_paths = list(data_dir.glob('*'))
pictures_paths = [str(path) for path in pictures_paths]
pictures_paths[:3]
['D:\\jupyter notebook\\DL-100-days\\datasets\\015_licence_plate\\000000000_藏WP66B0.jpg',
'D:\\jupyter notebook\\DL-100-days\\datasets\\015_licence_plate\\000000001_津D8Z15T.jpg',
'D:\\jupyter notebook\\DL-100-days\\datasets\\015_licence_plate\\000000002_陕Z813VB.jpg']
image_count = len(list(pictures_paths))
print("图片总数为:",image_count)
图片总数为:619
# 获取数据标签
all_label_names = [path.split("_")[2].split(".")[0] for path in pictures_paths]
all_label_names[:3]
['藏WP66B0', '津D8Z15T', '陕Z813VB']
3.数据可视化
plt.figure(figsize=(10,5))
plt.suptitle("数据示例",fontsize=15)
for i in range(20):
plt.subplot(5,4,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
# 显示图片
images = plt.imread(pictures_paths[i])
plt.imshow(images)
# 显示标签
plt.xlabel(all_label_names[i],fontsize=13)
plt.show()
4.标签数字化
char_enum = ["京","沪","津","渝","冀","晋","蒙","辽","吉","黑","苏","浙","皖","闽","赣","鲁",\
"豫","鄂","湘","粤","桂","琼","川","贵","云","藏","陕","甘","青","宁","新","军","使"]
number = [str(i) for i in range(0, 10)] # 0 到 9 的数字
alphabet = [chr(i) for i in range(65, 91)] # A 到 Z 的字母
char_set = char_enum + 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]
二、构建一个tf.data.Dataset
1.预处理函数
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)
2.加载数据
构建 tf.data.Dataset
最简单的方法就是使用 from_tensor_slices
方法。
AUTOTUNE = tf.data.experimental.AUTOTUNE
path_ds = tf.data.Dataset.from_tensor_slices(pictures_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)).shuffle(1000)
image_label_ds
<ShuffleDataset shapes: ((50, 200, 1), (7, 69)), types: (tf.float32, tf.float64)>
train_ds = image_label_ds.take(550) # 前1000个batch
val_ds = image_label_ds.skip(550) # 跳过前1000,选取后面的
3.配置数据
先复习一下prefetch()
函数。prefetch()
功能详细介绍:CPU 正在准备数据时,加速器处于空闲状态。相反,当加速器正在训练模型时,CPU 处于空闲状态。因此,训练所用的时间是 CPU 预处理时间和加速器训练时间的总和。prefetch()
将训练步骤的预处理和模型执行过程重叠到一起。当加速器正在执行第 N 个训练步时,CPU 正在准备第 N+1 步的数据。这样做不仅可以最大限度地缩短训练的单步用时(而不是总用时),而且可以缩短提取和转换数据所需的时间。如果不使用prefetch()
,CPU 和 GPU/TPU 在大部分时间都处于空闲状态:
使用prefetch()
可显著减少空闲时间:
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
<PrefetchDataset shapes: ((None, 50, 200, 1), (None, 7, 69)), types: (tf.float32, tf.float64)>
三、搭建网络模型
目前这里主要是带大家跑通代码、整理一下思路,大家可以自行优化网络结构、调整模型参数。后续我也会针对性的出一些调优的案例的。
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(1000, activation='relu'), #全连接层,特征进一步提取
# layers.Dropout(0.2),
layers.Dense(label_name_len * char_set_len),
layers.Reshape([label_name_len, char_set_len]),
layers.Softmax() #输出层,输出预期结果
])
# 打印网络结构
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 48, 198, 32) 320
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 24, 99, 32) 0
_________________________________________________________________
conv2d_1 (Conv2D) (None, 22, 97, 64) 18496
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 11, 48, 64) 0
_________________________________________________________________
flatten (Flatten) (None, 33792) 0
_________________________________________________________________
dense (Dense) (None, 1000) 33793000
_________________________________________________________________
dense_1 (Dense) (None, 483) 483483
_________________________________________________________________
reshape (Reshape) (None, 7, 69) 0
_________________________________________________________________
softmax (Softmax) (None, 7, 69) 0
=================================================================
Total params: 34,295,299
Trainable params: 34,295,299
Non-trainable params: 0
_________________________________________________________________
四、设置动态学习率
这里先罗列一下学习率大与学习率小的优缺点。
学习率大
优点:1、加快学习速率。2、有助于跳出局部最优值。 缺点:1、导致模型训练不收敛。2、单单使用大学习率容易导致模型不精确。 学习率小
优点:1、有助于模型收敛、模型细化。2、提高模型精度。 缺点:1、很难跳出局部最优值。2、收敛缓慢。
注意:这里设置的动态学习率为:指数衰减型(ExponentialDecay)。在每一个epoch开始前,学习率(learning_rate)都将会重置为初始学习率(initial_learning_rate),然后再重新开始衰减。计算公式如下:
“learning_rate =
initial_learning_rate * decay_rate ^ (step / decay_steps)
”
# 设置初始学习率
initial_learning_rate = 1e-3
lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate,
decay_steps=50, # 敲黑板!!!这里是指 steps,不是指epochs
decay_rate=0.96, # lr经过一次衰减就会变成 decay_rate*lr
staircase=True)
# 将指数衰减学习率送入优化器
optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule)
五、编译
model.compile(optimizer=optimizer,
loss='categorical_crossentropy',
metrics=['accuracy'])
六、训练
epochs = 20
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=epochs
)
Epoch 1/20
35/35 [==============================] - 4s 27ms/step - loss: 3.8599 - accuracy: 0.0492 - val_loss: 3.3631 - val_accuracy: 0.0663
Epoch 2/20
35/35 [==============================] - 0s 9ms/step - loss: 3.3526 - accuracy: 0.0718 - val_loss: 3.2880 - val_accuracy: 0.0683
Epoch 3/20
35/35 [==============================] - 0s 9ms/step - loss: 3.2952 - accuracy: 0.0866 - val_loss: 3.1754 - val_accuracy: 0.1429
Epoch 4/20
35/35 [==============================] - 0s 9ms/step - loss: 3.1920 - accuracy: 0.1347 - val_loss: 3.0021 - val_accuracy: 0.2298
Epoch 5/20
35/35 [==============================] - 0s 12ms/step - loss: 2.9394 - accuracy: 0.2142 - val_loss: 2.3816 - val_accuracy: 0.3913
.......
Epoch 17/20
35/35 [==============================] - 0s 9ms/step - loss: 0.0191 - accuracy: 0.9984 - val_loss: 0.0141 - val_accuracy: 0.9979
Epoch 18/20
35/35 [==============================] - 0s 10ms/step - loss: 0.0115 - accuracy: 0.9997 - val_loss: 0.0126 - val_accuracy: 1.0000
Epoch 19/20
35/35 [==============================] - 0s 9ms/step - loss: 0.0094 - accuracy: 0.9992 - val_loss: 0.0120 - val_accuracy: 0.9959
Epoch 20/20
35/35 [==============================] - 0s 10ms/step - loss: 0.0070 - accuracy: 0.9997 - val_loss: 0.0051 - val_accuracy: 1.0000
七、模型评估
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/15_model.h5')
# 加载模型
new_model = tf.keras.models.load_model('model/15_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]),fontsize=15)
plt.axis("off")