import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("captcha_dir", "./tfrecords", "验证码数据路径")
tf.app.flags.DEFINE_integer("batch_size", 100, "每批次训练的样本数")
tf.app.flags.DEFINE_integer("label_num", 4, "每个样本目标值数量")
tf.app.flags.DEFINE_integer("letter_num", 26, "每个目标值取的字母的可能性个数")
# 定义一个随机初始化权重函数
def weight_variables(shape):
w = tf.Variable(tf.random_normal(shape=shape, mean=0.0, stddev=1.0))
return w
# 定义一个随机初始化偏置函数
def bias_variables(shape):
b = tf.Variable(tf.constant(0.0, shape=shape))
return b
def read_and_decode():
"""读取验证码数据"""
# 1.构建文件独立
file_queue = tf.train.string_input_producer([FLAGS.captcha_dir])
# 2.构建阅读器,读取文件内容,默认一个样本
reader = tf.TFRecordReader()
key, value = reader.read(file_queue)
# tfrecords数据需要解析
features = tf.parse_single_example(value, features={
"image":tf.FixedLenFeature([], tf.string),
"label":tf.FixedLenFeature([], tf.string),
})
# 解码内容,字符串内容
# 1.解析图片特征值
image = tf.decode_raw(features["image"], tf.uint8)
# 2.解析目标值
label = tf.decode_raw(features["label"], tf.uint8)
# 改变形状
image_reshape = tf.reshape(image, [20, 80, 3])
label_reshape = tf.reshape(label, [4])
# 进行批处理
image_batch, label_batch = tf.train.batch([image_reshape, label_reshape], batch_size=FLAGS.batch_size, num_threads=2, capacity=10)
return image_batch, label_batch
def fc_model(image):
"""
进行预测结果
image [100, 20, 80, 3]
"""
with tf.variable_scope("model"):
# 1。随机初始化权重,偏置
weights = weight_variables([20*80*3, 4*26])
bias = bias_variables([4*26])
# 将图片数据转换成二维
image_reshape = tf.reshape(image, [-1, 20*80*3])
# 进行全连接层矩阵运算
y_predict = tf.matmul(tf.cast(image_reshape, tf.float32), weights) + bias
return y_predict
def captcharec():
"""验证码识别"""
# 1.读取验证码数据
image_batch, label_batch = read_and_decode()
# 2.通过输入图片的特征数据,建立模型,得出预测结果
# 一层,全连接层进行预测
# matrix [100, 20*80*3]*[20*80*3, 4*26] + [104] = [100, 4*26]
y_predict = fc_model(image_batch)
# 目标值[100, 4]转换成one-hot编码==>[100, 4, 26]
y_true = tf.one_hot(label_batch, depth=FLAGS.letter_num, on_value=1.0, axis=2)
# softmax计算,交叉熵损失计算
with tf.variable_scope("soft_cross"):
# 求平均交叉熵损失
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf.reshape(y_true, [FLAGS.batch_size, FLAGS.label_num*FLAGS.letter_num]), logits=y_predict))
# 梯度下降优化损失
with tf.variable_scope("optimizer"):
# 0.1是学习率,minimize表示求最小损失
train_op = tf.train.GradientDescentOptimizer(0.0001).minimize(loss)
# 计算准确率,三维比较 y_predict:[100, 4*26]==>[100, 4, 26]
with tf.variable_scope("acc"):
equal_list = tf.equal(tf.argmax(y_true, 2), tf.argmax(tf.reshape(y_predict, [FLAGS.batch_size, FLAGS.label_num, FLAGS.letter_num]), 1))
# equal_list None个样本 [1, 0, 1, 1, 0, 0.....]
accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))
# 定义初始化变量op
init_op = tf.global_variables_initializer()
# 开启会话
with tf.Session() as sess:
sess.run(init_op)
# 定义线程协调器和开启线程
coord = tf.train.Coordinator()
# 开启线程读取文件
threads = tf.train.start_queue_runners(sess, coord=coord)
# 训练数据
for i in range(5000):
sess.run(train_op)
print("第{}批次的准确率为:{}".format(i, accuracy.eval()))
# 回收线程
coord.request_stop()
coord.join(threads)
return None
if __name__ == "__nain__":
captcharec()