一、这里的案例相对比较简单,主要就是通过学习验证码的识别来认识深度学习中我们一般在工作中,需要处理的东西会存在哪些东西。
二、因为我没有数据集,没有关系,这里自己写了一个数据集,来做测试,为了方便我把这个数据集,写成了***.tfrecords**格式的文件。
三、生成数据集
1)生成验证码图片
1# 生成验证码训练集 2def gen_captcha(): 3 captcha_char_list = list("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") 4 font = ImageFont.truetype(font="font/msyh.ttf", size=36) 5 for n in range(2000): 6 image = Image.new('RGB', (200, 50), (255, 255, 255)) 7 draw = ImageDraw.Draw(image) 8 chars = "" 9 for i in range(5): 10 captcha_char = captcha_char_list[random.randint(0, 25)] 11 chars += captcha_char 12 draw.text((10 + i * 40, 0), captcha_char, (0, 0, 0), font=font) 13 image.save(open("data/captcha/" + chars + ".png", 'wb'), 'png')
说明:我这里都是采用的白底黑字的方式来写的,字体使用微软的字体。如果需要做干扰,可以自己在网上查找教程

2)写入tfrecords格式文件
1# 将图片数据和目标值写到tfrecords文件中 2def captcha_data_write(): 3 # 获取图片名称和所有数据 4 file_names, image_batch = get_image_name_batch() 5 6 # 获取目标值 7 target = get_target(file_names) 8 9 # 写入文件 10 write_tf_records(image_batch, target) 11 12def get_image_name_batch(): 13 # 1、读取图片目录,生成文件名称列表 14 file_names = os.listdir("data/captcha") 15 file_list = [os.path.join("data/captcha", file_name) for file_name in file_names] 16 print(file_list) 17 # 2、放入队列(shuffle=False,一定要设置,不然会乱序) 18 file_queue = tf.train.string_input_producer(file_list, shuffle=False) 19 # 3、读取图片数据 20 reader = tf.WholeFileReader() 21 key, value = reader.read(file_queue) 22 # 4、解码图片数据 23 image = tf.image.decode_png(value) 24 # 改变形状(根据具体的图片大小来) 25 image.set_shape([50, 200, 3]) 26 # 5、获取图片批次 27 image_batch = tf.train.batch([image], batch_size=2000, num_threads=1, capacity=2000) 28 return file_names, image_batch 29 30def get_target(file_names): 31 # 6、获取目标值 32 labels = [file_name.split(".")[0] for file_name in file_names] 33 print(labels) 34 # 7、将目标值装换成具体数值 35 captcha_char = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" 36 # 转换成字典,然后反转(0:0, 1:1, ...,z:35) 37 num_char = dict(enumerate(list(captcha_char))) 38 char_num = dict(zip(num_char.values(), num_char.keys())) 39 # 8、构建标签列表 40 array = [] 41 for label in labels: 42 nums = [] 43 for char in label: 44 nums.append(char_num[char]) 45 array.append(nums) 46 # [[2, 11, 8, 2, 7] ...] 47 print(array) 48 # 9、转换为tensor张量,注意这里的类型一定要给出来,这里我踩过坑,如果没有,读数据是存在问题的 49 target = tf.constant(array, dtype=tf.uint8) 50 return target 51 52def write_tf_records(image_batch, target): 53 # 10、上面主要准备图片数据和目标值,下面主要是写入到*.tfrecords中 54 with tf.Session() as sess: 55 coord = tf.train.Coordinator() 56 threads = tf.train.start_queue_runners(sess=sess, coord=coord) 57 # 运算获取图片批次数据 58 image_batch = sess.run(image_batch) 59 # 转换一下数据为uint8 60 image_batch = tf.cast(image_batch, tf.uint8) 61 # 写入数据 62 with tf.python_io.TFRecordWriter("data/tf_records/captcha.tfrecords") as writer: 63 for i in range(2000): 64 # 全部使用string保存 65 image_string = image_batch[i].eval().tostring() 66 label_string = target[i].eval().tostring() 67 example = tf.train.Example(features=tf.train.Features(feature={ 68 "image": tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_string])), 69 "label": tf.train.Feature(bytes_list=tf.train.BytesList(value=[label_string])) 70 })) 71 writer.write(example.SerializeToString()) 72 print("写入第%d数据" % (i + 1)) 73 coord.request_stop() 74 coord.join(threads)
四、训练和测试
1def captcha_train_test(n): 2 # 读取数据 3 image_batch, label_batch = tfrecords_read_decode() 4 5 # 1、建立占位符(数据更具图片和目标数据而定) 6 with tf.variable_scope("data"): 7 x = tf.placeholder(dtype=tf.uint8, shape=[None, 50, 200, 3], name="x") 8 label = tf.placeholder(dtype=tf.uint8, shape=[None, 5], name="label") 9 10 # 2、建立模型 11 y_predict = model(x) 12 13 # y_predict为[None, 5 * 36] label_batch为[None, 5], 因此需要one-hot[None, 5, 36] 14 y_true = tf.one_hot(label, depth=36, axis=2, on_value=1.0, name="one_hot") 15 # 需要变形为[None 5 * 36] 16 y_true_reshape = tf.reshape(y_true, [-1, 5 * 36], name="y_true_reshape") 17 18 # 4、计算损失值 19 with tf.variable_scope("loss"): 20 softmax_cross = tf.nn.softmax_cross_entropy_with_logits(labels=y_true_reshape, logits=y_predict) 21 loss = tf.reduce_mean(softmax_cross) 22 23 # 5、训练 24 with tf.variable_scope("optimizer"): 25 train_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss=loss) 26 27 # 6、计算准确率 28 with tf.variable_scope("accuracy"): 29 # 因为这里的真实值是2维结果,所以需要把y_predict,转化为2位数据 30 equal_list = tf.equal(tf.argmax(y_true, axis=2), tf.argmax(tf.reshape(y_predict, [-1, 5, 36]), 2)) 31 accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32)) 32 33 # 收集数据 34 tf.add_to_collection("y_predict", y_predict) 35 if n == 1: 36 # 7、会话 37 with tf.Session() as sess: 38 # 变量初始化 39 sess.run(tf.global_variables_initializer()) 40 41 coord = tf.train.Coordinator() 42 threads = tf.train.start_queue_runners(sess=sess, coord=coord) 43 44 saver = tf.train.Saver() 45 # 如果模型存在,则加载模型 46 if os.path.exists("model/captcha/checkpoint"): 47 saver.restore(sess, "model/captcha/captcha") 48 49 for i in range(2000): 50 # 读取数据 51 # 训练,记住这里的数据类型为uint8需要转换为tf.float32 52 image_train, label_train = sess.run([image_batch, label_batch]) 53 sess.run(train_op, feed_dict={x: image_train, label: label_train}) 54 # 保存模型 55 if (i + 1) % 100 == 0: 56 saver.save(sess, "model/captcha/captcha") 57 acc = sess.run(accuracy, feed_dict={x: image_train, label: label_train}) 58 print("第%d次,准确率%f" % ((i + 1), acc)) 59 60 coord.request_stop() 61 coord.join(threads) 62 else: 63 # 1、读取指定目录下图片数据 64 file_names_test = os.listdir("data/captcha_test") 65 file_list_test = [os.path.join("data/captcha_test", file_name) for file_name in file_names_test] 66 file_queue_test = tf.train.string_input_producer(file_list_test, shuffle=False) 67 # 2、读取和解码数据 68 reader = tf.WholeFileReader() 69 key, value = reader.read(file_queue_test) 70 image = tf.image.decode_png(value) 71 image.set_shape([50, 200, 3]) 72 # 3、批处理 73 image_batch_test = tf.train.batch([tf.cast(image, tf.uint8)], batch_size=len(file_names_test), capacity=len(file_names_test)) 74 # 4、加载模型 75 with tf.Session() as sess: 76 coord = tf.train.Coordinator() 77 threads = tf.train.start_queue_runners(sess=sess, coord=coord) 78 # 1、加载模型 79 saver = tf.train.Saver() 80 saver.restore(sess, "model/captcha/captcha") 81 82 # 4、预测[None, 5 * 36] 83 predict = sess.run(y_predict, feed_dict={x: sess.run(image_batch_test)}) 84 captcha_list = list("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") 85 for i in range(len(file_names_test)): 86 predict_reshape = tf.reshape(predict, [-1, 5, 36]) 87 captcha = "" 88 for j in range(5): 89 captcha += captcha_list[tf.argmax(predict_reshape[i][j], 0).eval()] 90 print("预测值:%s, 真实值:%s" % (captcha, file_names_test[i].split(".")[0])) 91 coord.request_stop() 92 coord.join(threads) 93 94def model(x): 95 # # 第一层卷积 96 # with tf.variable_scope("conv_1"): 97 # # 卷积[None, 50, 200, 3] -> [None, 50, 200, 32] 98 # w_1 = gen_weight([5, 5, 3, 32]) 99 # b_1 = gen_bias([32]) 100 # # 在进行模型计算的时候需要使用tf.float32数据进行计算 101 # x_conv_1 = tf.nn.conv2d(tf.cast(x, tf.float32), filter=w_1, strides=[1, 1, 1, 1], padding="SAME") + b_1 102 # # 激活 103 # x_relu_1 = tf.nn.relu(x_conv_1) 104 # # 池化[None, 50, 200, 32] -> [None, 25, 100, 32] 105 # x_pool_1 = tf.nn.max_pool(x_relu_1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") 106 # # 第二层卷积 107 # with tf.variable_scope("conv_2"): 108 # # 卷积[None, 25, 100, 32] -> [None, 25, 100, 64] 109 # w_2 = gen_weight([5, 5, 32, 64]) 110 # b_2 = gen_bias([64]) 111 # x_conv_2 = tf.nn.conv2d(x_pool_1, filter=w_2, strides=[1, 1, 1, 1], padding="SAME") + b_2 112 # # 激活 113 # x_relu_2 = tf.nn.relu(x_conv_2) 114 # # 池化[None, 25, 100, 64] -> [None, 13, 50, 64] 115 # x_pool_2 = tf.nn.max_pool(x_relu_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") 116 # # 全连接层 117 # with tf.variable_scope("full_connection"): 118 # # 生成权重和偏置 119 # # 为什么是5 * 36主要是我们的字符串个数36个,使用one-hot.每个值为36个值,一个验证码5个值,所以为5 * 36个 120 # w_fc = gen_weight([13 * 50 * 64, 5 * 36]) 121 # b_fc = gen_bias([5 * 36]) 122 # # 修改数据形状 123 # x_fc = tf.reshape(x_pool_2, shape=[-1, 13 * 50 * 64]) 124 # # [None, 5 * 36] 125 # y_predict = tf.matmul(x_fc, w_fc) + b_fc 126 with tf.variable_scope("model"): 127 # 生成权重和偏置 128 # 为什么是5 * 36主要是我们的字符串个数36个,使用one-hot.每个值为36个值,一个验证码5个值,所以为5 * 36个 129 w_fc = gen_weight([50 * 200 * 3, 5 * 36]) 130 b_fc = gen_bias([5 * 36]) 131 # 修改数据形状 132 x_fc = tf.reshape(tf.cast(x, tf.float32), shape=[-1, 50 * 200 * 3]) 133 # [None, 5 * 36] 134 y_predict = tf.matmul(x_fc, w_fc) + b_fc 135 return y_predict 136 137# 生成权重值 138def gen_weight(shape): 139 return tf.Variable(tf.random_normal(shape=shape, mean=0.0, stddev=1.0, dtype=tf.float32)) 140 141# 生成偏值 142def gen_bias(shape): 143 return tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=shape)) 144 145# 读取数据 146def tfrecords_read_decode(): 147 # 将文件加入队列 148 file_queue = tf.train.string_input_producer(["data/tf_records/captcha.tfrecords"]) 149 # 读取tfrecords文件 150 reader = tf.TFRecordReader() 151 key, value = reader.read(file_queue) 152 # value的格式为example 153 features = tf.parse_single_example(value, features={ 154 "image": tf.FixedLenFeature([], tf.string), 155 "label": tf.FixedLenFeature([], tf.string) 156 }) 157 # 解码 158 image_data = tf.decode_raw(features["image"], tf.uint8) 159 label_data = tf.decode_raw(features["label"], tf.uint8) 160 # 改变形状 161 image_reshape = tf.reshape(image_data, [50, 200, 3]) 162 label_reshape = tf.reshape(label_data, [5]) 163 # 获取批次数据 164 image_batch, label_batch = tf.train.batch([image_reshape, label_reshape], batch_size=200, num_threads=1, capacity=200) 165 return image_batch, label_batch
说明:因为我这里使用的是cpu计算,所以速度上面会很慢,为了看到效果,我这里,使用的全连接层,实际可以使用卷积神经网络测试。
one-hot:中间有一步是进行了数据one-hot处理的,也就是**[5, 23, 15, 20]-->[[0,0,0,0,1,...],[0,0,0,...,1,...],[0,0,0,...,1,...],[0,0,0,...,1,...]]**这样的形式。为什么要这样做呢?目的是为了计算,在前面的类别我们说明过,计算得出的是概率,这里的5是验证码数据的下标,不是概率。我们为了计算概率就需要得出,预测中得出每一个值的概率,然后选取最大的值。
训练结果:

测试结果:

可以看出,测试结果,还是存在错误的情况,不过从准确率上面来说还是很不错了。