转载地址:
/p/45828b18f133
上一篇文章tensorflow 实现端到端的OCR:二代身份证号识别实现了定长18位数字串的识别,并最终达到了98%的准确率。但是实际应用场景中,常常需要面对无法确定字串长度的情况,这时候除了需要对识别字符模型参数进行训练外,还需要对字符划分模型进行训练,本文实现了上文提到的方法2,使用LSTM+CTC识别不定长的数字串。
环境依赖
环境依赖与上一篇基本一致
知识准备
LSTM(长短时记忆网络):是一种特殊结构的RNN,能够解决普通RNN不能解决的长期依赖问题。具体介绍可参看这篇译文[译] 理解 LSTM 网络
CTC :Connectionist Temporal Classifier 一般译为联结主义时间分类器 ,适合于输入特征和输出标签之间对齐关系不确定的时间序列问题,CTC可以自动端到端地同时优化模型参数和对齐切分的边界。比如本文例子,32 x 256大小的图片,最大可切分256列,也就是输入特征最大256,而输出标签的长度最大设定是18,这种就可以用CTC模型进行优化。关于CTC模型,笔者认为可以这样理解,假设32 x 256的图片,数字串标签是"123",把图片按列切分(CTC会优化切分模型),然后分出来的每块再去识别数字,找出这块是每个数字或者特殊字符的概率(无法识别的则标记为特殊字符"-"),这样就得到了基于输入特征序列(图片)的每一个相互独立建模单元个体(划分出来的块)(包括“-”节点在内)的类属概率分布。基于概率分布,算出标签序列是"123"的概率P(123),当然这里设定"123"的概率为所有子序列之和,这里子序列包括'-'和'1'、'2'、'3'的连续重复,如下图所示:
所有子序列概率和
本文采用TF框架的CTC封装实现,tf.nn.ctc_loss,我们最后的目标是最小化ctc_loss官方定义如下:
ctc_loss(labels,inputs,sequence_length,preprocess_collapse_repeated=False,ctc_merge_repeated=True,time_major=True)
inputs: 输入(训练)数据,是一个三维float型的数据结构[max_time_step , batch_size , num_classes],当修改time_major = False时,[batch_size,max_time_step,num_classes]。
总体的数据流:
image_batch
->[batch_size,max_time_step,num_features]->lstm
->[batch_size,max_time_step,cell.output_size]->reshape
->[batch_sizemax_time_step,num_hidden]->affine projection AW+b
->[batch_size*max_time_step,num_classes]->reshape
->[batch_size,max_time_step,num_classes]->transpose
->[max_time_step,batch_size,num_classes]
本文输入图片大小是(32,256),则num_features是32,max_time_step是256 代表最大划分序列,其中cell.output_size == num_hidden,num_hidden及num_classes的值见下文常量定义
labels:OCR识别结果的标签,是一个稀疏矩阵,下文训练数据生成部分会有相关解释
sequence_length: 一维数据,[max_time_step,…,max_time_step]长度为batch_size,值为max_time_step
因此我们需要做的就是将图片的标签label(需要OCR出的结果),图片数据,以及图片的长度转换为labels,inputs,和sequence_length
正文
定义一些常量
#定义一些常量#图片大小,32 x 256OUTPUT_SHAPE = (32,256)#训练最大轮次num_epochs = 10000#LSTMnum_hidden = 64num_layers = 1obj = gen_id_card()num_classes = obj.len + 1 + 1 # 10位数字 + blank + ctc blank#初始化学习速率INITIAL_LEARNING_RATE = 1e-3DECAY_STEPS = 5000REPORT_STEPS = 100LEARNING_RATE_DECAY_FACTOR = 0.9 # The learning rate decay factorMOMENTUM = 0.9DIGITS='0123456789'BATCHES = 10BATCH_SIZE = 64TRAIN_SIZE = BATCHES * BATCH_SIZE
训练数据集生成
训练数据集的生成基本与上文一致,唯一变化就是增加生成随机长度串的选项,对应方法如下:
def gen_text(self, is_ran=False):text = ''vecs = np.zeros((self.max_size * self.len))//唯一变化,随机设定长度if is_ran == True:size = random.randint(1, self.max_size)else:size = self.max_sizefor i in range(size):c = random.choice(self.char_set)vec = self.char2vec(c)text = text + cvecs[i*self.len:(i+1)*self.len] = np.copy(vec)return text,vecs
# 生成一个训练batchdef get_next_batch(batch_size=128):obj = gen_id_card()#(batch_size,256,32)inputs = np.zeros([batch_size, OUTPUT_SHAPE[1],OUTPUT_SHAPE[0]])codes = []for i in range(batch_size):#生成不定长度的字串image, text, vec = obj.gen_image(True)#np.transpose 矩阵转置 (32*256,) => (32,256) => (256,32)inputs[i,:] = np.transpose(image.reshape((OUTPUT_SHAPE[0],OUTPUT_SHAPE[1])))#标签转成列表保存在codescodes.append(list(text))#比如batch_size=2,两条数据分别是"12"和"1",则targets [['1','2'],['1']]targets = [np.asarray(i) for i in codes]#targets转成稀疏矩阵sparse_targets = sparse_tuple_from(targets)#(batch_size,) sequence_length值都是256,最大划分列数seq_len = np.ones(inputs.shape[0]) * OUTPUT_SHAPE[1]return inputs, sparse_targets, seq_len
这里我们来了解一下什么是稀疏矩阵,下面是百度百科的定义
对于那些零元素数目远远多于非零元素数目,并且非零元素的分布没有规律的矩阵称为稀疏矩阵(sparse)
其实很容易理解这里为什么OCR识别训练的标签labels是一个稀疏矩阵,假设我们生成的batch_size 是64的样本,每个样本是长度为1~18的数字串,则生成一个(64,18)的矩阵,矩阵有数字的是非零元素,无数字的是零元素,且因为这个标签是不定长的,所以非零元素的分布没有规律,标签在存储数字串的同时还要存储位置信息。
我们来看一下tensorflow中,如何把targets转成一个稀疏矩阵的
#转化一个序列列表为稀疏矩阵 def sparse_tuple_from(sequences, dtype=np.int32):"""Create a sparse representention of x.Args:sequences: a list of lists of type dtype where each element is a sequenceReturns:A tuple with (indices, values, shape)"""indices = []values = []for n, seq in enumerate(sequences):indices.extend(zip([n] * len(seq), xrange(len(seq))))values.extend(seq)indices = np.asarray(indices, dtype=np.int64)values = np.asarray(values, dtype=dtype)shape = np.asarray([len(sequences), np.asarray(indices).max(0)[1] + 1], dtype=np.int64)return indices, values, shape
indices:二维int64的矩阵,代表非0的坐标点
values:二维tensor,代表indice位置的数据值
dense_shape:一维,代表稀疏矩阵的大小
仍然拿刚才的两个串"12"和"1"做例子,转成的稀疏矩阵应该是
indecs = [[0,0],[0,1],[1,0]]
values = [1,2,1]
dense_shape = [2,2] (两个数字串,最大长度为2)
代表dense tensor:
[[1,2],[1,0]]
有了序列列表转稀疏矩阵的方法,反过来,当然也需要稀疏矩阵转序列列表的方法:
def decode_sparse_tensor(sparse_tensor):decoded_indexes = list()current_i = 0current_seq = []for offset, i_and_index in enumerate(sparse_tensor[0]):i = i_and_index[0]if i != current_i:decoded_indexes.append(current_seq)current_i = icurrent_seq = list()current_seq.append(offset)decoded_indexes.append(current_seq)result = []for index in decoded_indexes:result.append(decode_a_seq(index, sparse_tensor))return resultdef decode_a_seq(indexes, spars_tensor):decoded = []for m in indexes:str = DIGITS[spars_tensor[1][m]]decoded.append(str)return decoded
构建网络,开始训练
数据准备工作完成,则开始构建LSTM+CTC的训练模型,其中TF实现LSTM的方法就不做过多解释,请读者自行百度。
def get_train_model():inputs = tf.placeholder(tf.float32, [None, None, OUTPUT_SHAPE[0]])#定义ctc_loss需要的稀疏矩阵targets = tf.sparse_placeholder(tf.int32)#1维向量 序列长度 [batch_size,]seq_len = tf.placeholder(tf.int32, [None])#定义LSTM网络cell = tf.contrib.rnn.LSTMCell(num_hidden, state_is_tuple=True)stack = tf.contrib.rnn.MultiRNNCell([cell] * num_layers, state_is_tuple=True)outputs, _ = tf.nn.dynamic_rnn(cell, inputs, seq_len, dtype=tf.float32)shape = tf.shape(inputs)#[batch_size,256]batch_s, max_timesteps = shape[0], shape[1]#[batch_size*max_time_step,num_hidden]outputs = tf.reshape(outputs, [-1, num_hidden])W = tf.Variable(tf.truncated_normal([num_hidden,num_classes],stddev=0.1), name="W")b = tf.Variable(tf.constant(0., shape=[num_classes]), name="b")#[batch_size*max_timesteps,num_classes]logits = tf.matmul(outputs, W) + b#[batch_size,max_timesteps,num_classes]logits = tf.reshape(logits, [batch_s, -1, num_classes])#转置矩阵,第0和第1列互换位置=>[max_timesteps,batch_size,num_classes]logits = tf.transpose(logits, (1, 0, 2))return logits, inputs, targets, seq_len, W, b
训练模型
def train():global_step = tf.Variable(0, trainable=False)learning_rate = tf.train.exponential_decay(INITIAL_LEARNING_RATE,global_step,DECAY_STEPS,LEARNING_RATE_DECAY_FACTOR,staircase=True)logits, inputs, targets, seq_len, W, b = get_train_model()#tragets是一个稀疏矩阵loss = tf.nn.ctc_loss(labels=targets,inputs=logits, sequence_length=seq_len)cost = tf.reduce_mean(loss)#optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate,momentum=MOMENTUM).minimize(cost, global_step=global_step)optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss,global_step=global_step)#前面说的划分块之后找每块的类属概率分布,ctc_beam_search_decoder方法,是每次找最大的K个概率分布#还有一种贪心策略是只找概率最大那个,也就是K=1的情况ctc_ greedy_decoderdecoded, log_prob = tf.nn.ctc_beam_search_decoder(logits, seq_len, merge_repeated=False)acc = tf.reduce_mean(tf.edit_distance(tf.cast(decoded[0], tf.int32), targets))init = tf.global_variables_initializer()def report_accuracy(decoded_list, test_targets):original_list = decode_sparse_tensor(test_targets)detected_list = decode_sparse_tensor(decoded_list)true_numer = 0if len(original_list) != len(detected_list):print("len(original_list)", len(original_list), "len(detected_list)", len(detected_list)," test and detect length desn't match")returnprint("T/F: original(length) <-------> detectcted(length)")for idx, number in enumerate(original_list):detect_number = detected_list[idx]hit = (number == detect_number)print(hit, number, "(", len(number), ") <-------> ", detect_number, "(", len(detect_number), ")")if hit:true_numer = true_numer + 1print("Test Accuracy:", true_numer * 1.0 / len(original_list))def do_report():test_inputs,test_targets,test_seq_len = get_next_batch(BATCH_SIZE)test_feed = {inputs: test_inputs,targets: test_targets,seq_len: test_seq_len}dd, log_probs, accuracy = session.run([decoded[0], log_prob, acc], test_feed)report_accuracy(dd, test_targets)def do_batch():train_inputs, train_targets, train_seq_len = get_next_batch(BATCH_SIZE)feed = {inputs: train_inputs, targets: train_targets, seq_len: train_seq_len}b_loss,b_targets, b_logits, b_seq_len,b_cost, steps, _ = session.run([loss, targets, logits, seq_len, cost, global_step, optimizer], feed)print b_cost, stepsif steps > 0 and steps % REPORT_STEPS == 0:do_report()save_path = saver.save(session, "ocr.model", global_step=steps)return b_cost, stepswith tf.Session() as session:session.run(init)saver = tf.train.Saver(tf.global_variables(), max_to_keep=100)for curr_epoch in xrange(num_epochs):print("Epoch.......", curr_epoch)train_cost = train_ler = 0for batch in xrange(BATCHES):start = time.time()c, steps = do_batch()train_cost += c * BATCH_SIZEseconds = time.time() - startprint("Step:", steps, ", batch seconds:", seconds)train_cost /= TRAIN_SIZEtrain_inputs, train_targets, train_seq_len = get_next_batch(BATCH_SIZE)val_feed = {inputs: train_inputs,targets: train_targets,seq_len: train_seq_len}val_cost, val_ler, lr, steps = session.run([cost, acc, learning_rate, global_step], feed_dict=val_feed)log = "Epoch {}/{}, steps = {}, train_cost = {:.3f}, train_ler = {:.3f}, val_cost = {:.3f}, val_ler = {:.3f}, time = {:.3f}s, learning_rate = {}"print(log.format(curr_epoch + 1, num_epochs, steps, train_cost, train_ler, val_cost, val_ler, time.time() - start, lr))
训练结果
训练到第80个epoch的时候,64个测试样本的准确率达到64%
训练第80次后测试结果
训练到第100个epoch的时候,64个测试样本的准确率达到100%了,后续基本上准确率都是100%了
测试准确率达到100%
后记
最后完整的代码托管在我的Github下
训练产生的图片数据属于比较理想,无噪音的环境下,所以才会在100个epoch的时候准确率就达到100%了,实际应用中图片可能会有些线段或者离散点的噪音,读者可以自行在生成训练集中增加一些噪音,测试模型训练效果
本文生成的串的所属类别仅是0~9的10个类别,如果后续加上26*2个大小写英文字母,或者加上3500+常用中文汉字去组成串,随着所属类别的不断扩大,模型还能不能很好的识别?模型收敛的速度如何?
在编写本文示例代码的过程中,较多的参考了别人的代码和模型,很多东西深层的原理基本没去了解。先做下记录,后续再研究那些数学模型和推导公式之类的。
作者:某杰
链接:/p/45828b18f133
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
如果觉得《tensorflow LSTM+CTC实现端到端的不定长数字串识别》对你有帮助,请点赞、收藏,并留下你的观点哦!