将分开的图片数据和标签数据存储为tfrecords文件
import os
import tensorflow as tf
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
"""
设置tf相关的log输出信息:
"0":INFO
"1":WARNING
"2":ERROR
"3":FATAL
"""
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("tfrecords_dir", "./tfrecords/captcha.tfrecords", "验证码tfrecords文件")
tf.app.flags.DEFINE_string("captcha_dir", "./data/Genpics/", "验证码图片路径")
tf.app.flags.DEFINE_string("letter", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "验证码字符种类")
def dealwithlabel(label_str):
# 构建字符索引{0:"A", 1:"B", ...}
num_letter = dict(enumerate(list(FLAGS.letter)))
# 键值反转
letter_num = dict(zip(num_letter.values(), num_letter.keys()))
print(letter_num)
array = []
# 构建标签的列表
for string in label_str:
letter_list = [] # [1,2,3,4]
# 修改编码,b'FVQJ'到字符串,并且循环找到每张验证码的字符对应的数字标记
for letter in string.decode("utf-8"):
letter_list.append(letter_num[letter]) # 取出字符对应的数字并添加到列表中
array.append(letter_list)
print(array)
label = tf.constant(array)
return label
def get_captcha_image():
"""
获取验证码图片数据
:return: image
"""
# 构造文件名
filename = []
for i in range(6000):
string = str(i) + ".jpg"
filename.append(string)
# 构造文件+路径
file_list = [os.path.join(FLAGS.captcha_dir, file) for file in filename]
# 构造文件队列
file_queue = tf.train.string_input_producer(file_list, shuffle=False)
# 构造文件阅读器
reader = tf.WholeFileReader()
# 读取图片数据内容
key, value = reader.read(file_queue)
# 解码图片数据
image = tf.image.decode_jpeg(value)
image.set_shape([20, 80, 3])
# 批处理数据[6000, 20, 80, 3]
image_batch = tf.train.batch([image], batch_size=6000, num_threads=1, capacity=6000)
return image_batch
def get_captcha_label():
"""
读取验证码图片标签数据
:return: label
"""
file_queue = tf.train.string_input_producer(['./Genpics/labels.csv'], shuffle=False)
reader = tf.TextLineReader()
key, value = reader.read(file_queue)
records = [[1], ["None"]] #None表示处理的是字符串
number, label = tf.decode_csv(value, record_defaults=records)
#批处理数据[["NZPP"], ["WKHK"]]
label_batch = tf.train.batch([label], batch_size=6000, num_threads=1, capacity=6000)
return label_batch
def write_to_tfrecords(image_batch, label_batch):
"""
将图片内容和标签写入到tfrecords文件当中
:param image_batch: 特征值
:param label_batch: 标签值
:return: None
"""
# 转换类型
label_batch = tf.cast(label_batch, tf.uint8)
print(label_batch)
# 建立tfrecords存储器
writer = tf.io.TFRecordWriter(FLAGS.tfrecords_dir)
# 循环将每一个图片上的数据构造example协议块,序列化后写入
for i in range(6000):
image_string = image_batch[i].eval().tostring()
label_string = label_batch[i].eval().tostring()
example = tf.train.Example(features=tf.train.Features(
feature={
"image": tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_string])),
"label": tf.train.Feature(bytes_list=tf.train.BytesList(value=[label_string]))
}
))
writer.write(example.SerializeToString())
# 关闭文件
writer.close()
return None
if __name__ == "__main__":
# 获取验证码文件中的图片
image_batch = get_captcha_image()
#获取验证码文件中的标签数据
label = get_captcha_label()
print(image_batch, label)
with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
#[b"NZPP", ...]
label_str = sess.run(label)
print(label_str)
#处理字符串标签到数字张量
label_batch = dealwithlabel(label_str)
print(label_batch)
#将图片数据和内容写入到tfrecords文件当中
write_to_tfrecords(image_batch, label_batch)
coord.request_stop()
coord.join(threads)
用tfrecords文件进行训练
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("captcha_dir", "./tfrecords/captcha.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 read_and_decode():
"""
读取验证码数据API
:return: image_batch, label_batch
"""
# 构建文件队列
file_queue = tf.train.string_input_producer([FLAGS.captcha_dir])
# 构建阅读器读取文件内容
reader = tf.TFRecordReader()
# 读取内容
key, value = reader.read(file_queue) # 注意:这里的value是一个tfrecords文件,需要解析examle文件
# 解析tfrecords
features = tf.parse_single_example(value, features={
"image": tf.FixedLenFeature([], tf.string), # 因为存的时候是string类型,所以解析出来也是string类型
"label": tf.FixedLenFeature([], tf.string) # label存的时候也是string类型
}) # feature是string类型,也需要解码
# 解码features
# 先解析图片的特征值
image = tf.decode_raw(features["image"], tf.uint8) # 将二进制文件解码成uint8类型
# 解码图片的目标值
label = tf.decode_raw(features["label"], tf.uint8) # 将二进制文件解码成uint8类型
print(image, label)
# 改变形状
image_reshape = tf.reshape(image, [20, 80, 3])
label_reshape = tf.reshape(label, [4])
print(image_reshape, label_reshape)
# 进行批处理
image_batch, label_batch = tf.train.batch([image_reshape, label_reshape], batch_size=FLAGS.batch_size,
num_threads=1, capacity=FLAGS.batch_size)
print(image_batch, label_batch)
return image_batch, label_batch
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 fc_model(image):
"""
进行预测结果
:param image:100图片特征值
:return: y_predict预测值[100, 4*26]
"""
with tf.variable_scope("model"):
# 将图片数据形状转换成2维的
image_reshape = tf.reshape(image, [-1, 20 * 80 * 3])
# 随机初始化权重,偏置
weights = weight_variables([20 * 80 * 3, 4 * 26])
bias = bias_variables([4 * 26])
# 进行全连接层运算
y_predict = tf.matmul(tf.cast(image_reshape, tf.float32), weights) + bias
return y_predict
def predict_to_onehot(label):
"""
将读取文件当中的目标值转换成One-hot编码
:param label: [100, 4]: [[13, 25, 15, 15], ..]
:return: onehot
"""
# 进行one_hot编码转换,提供给交叉熵损失计算,准确率计算[100, 4, 26]
label_onehot = tf.one_hot(label, depth=FLAGS.letter_num, on_value=1.0, axis=2)
# 每个字母有26种情况,所以depth为26
# eg:某个位置有值(eg:13),将该位置置为1.0
# 因为是三维的,这个是对最里面的一维进行改变(one-hot),所以axis=2
print(label_onehot)
return label_onehot
def captcharec():
"""
验证码识别程序
:return:
"""
# 读取验证码的数据文件
image_batch, label_batch = read_and_decode()
# 通过输入图片特征数据建立模型得出预测结果
# 一层全连接神经网络进行预测
# matrix [100, 20 * 80 * 3] * [] + [] = [100, 4*26]
y_predict = fc_model(image_batch)
print(y_predict)
# 先把目标值转换成one-hot编码, [100, 4, 26]
y_true = predict_to_onehot(label_batch)
# softmax计算,交叉熵损失计算
with tf.variable_scope("soft_cross"):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf.reshape(y_true, shape=[-1, 4 * 26]),
logits=y_predict)) # labels:真实值, logits:预测值
# 梯度下降优化损失
with tf.variable_scope("optimizer"):
train_op = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)
# 求出样本的每批次预测的准确率:三维比较
with tf.variable_scope("accuracy"):
# 比较每个样本预测值和目标值是否位置(4)一样
equal_list = tf.equal(tf.argmax(y_true, 2),
tf.argmax(tf.reshape(y_predict, [FLAGS.batch_size, FLAGS.label_num, FLAGS.letter_num]),
2)) # argmax对第二个位置求最大值
accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))
# 开启会话训练
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)
# 训练识别程序
for i in range(10000):
sess.run(train_op)
print("第{}批次的准确率为{}".format(i, accuracy.eval()))
# 回收线程
coord.request_stop()
coord.join(threads)
if __name__ == "__main__":
captcharec()
"""部分运行结果如下
第3265批次的准确率为0.9649999737739563
第3266批次的准确率为0.9549999833106995
第3267批次的准确率为0.9574999809265137
第3268批次的准确率为0.9449999928474426
"""
网友评论