以lstm+ctc对汉字识别为例对tensorflow 中的lstm,ctc loss的调试
#-*-coding:utf8-*- __author = "buyizhiyou"
__date = "2017-11-21" '''
单步调试,结合汉字的识别学习lstm,ctc loss的tf实现,tensorflow1.4
'''
import tensorflow as tf
import numpy as np
import pdb
import random def create_sparse(batch_size, dtype=np.int32):
'''
创建稀疏张量,ctc_loss中labels要求是稀疏张量,随机生成序列长度在150~180之间的labels
'''
indices = []
values = []
for i in range(batch_size):
length = random.randint(150,180)
for j in range(length):
indices.append((i,j))
value = random.randint(0,779)
values.append(value) indices = np.asarray(indices, dtype=np.int64)
values = np.asarray(values, dtype=dtype)
shape = np.asarray([batch_size, np.asarray(indices).max(0)[1] + 1], dtype=np.int64) #[64,180] return [indices, values, shape] W = tf.Variable(tf.truncated_normal([200,781],stddev=0.1), name="W")#num_hidden=200,num_classes=781(想象成780个汉字+blank),shape (200,781)
b = tf.Variable(tf.constant(0., shape=[781]), name="b")#
global_step = tf.Variable(0, trainable=False)#全局步骤计数 #构造输入
inputs = tf.random_normal(shape=[64,60,3000], dtype=tf.float32)#为了测试,随机batch_size=64张图片,h=60,w=3000,w可以看成lstm的时间步,即lstm输入的time_step=3000,h看成是每一时间步的输入tensor的size
shape = tf.shape(inputs)#array([ 64, 3000, 60], dtype=int32)
batch_s, max_timesteps = shape[0], shape[1] #64,3000
output = create_sparse(64)#创建64张图片对应的labels,稀疏张量,序列长度变长
seq_len = np.ones(64)*180 #180为变长序列的最大值
labels = tf.SparseTensor(values=output[1],indices=output[0],dense_shape=output[2]) pdb.set_trace()
cell = tf.nn.rnn_cell.LSTMCell(200, state_is_tuple=True)
inputs = tf.transpose(inputs,[0,2,1])#转置,因为默认的tf.nn.dynamic_rnn中参数time_major=false,即inputs的shape 是`[batch_size, max_time, ...]`, '''
tf.nn.dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, paralle
l_iterations=None, swap_memory=False, time_major=False, scope=None)
'''
outputs1, _ = tf.nn.dynamic_rnn(cell, inputs, seq_len, dtype=tf.float32)#(64, 3000, 200)动态rnn实现了输入变长问题的解决方案http://blog.csdn.net/u010223750/article/details/71079036 outputs = tf.reshape(outputs1, [-1, 200])#(64×3000,200)
logits0 = tf.matmul(outputs, W) + b
logits1 = tf.reshape(logits0, [batch_s, -1, 781])
logits = tf.transpose(logits1, (1, 0, 2))#(3000, 64, 781) '''
tf.nn.ctc_loss(labels, inputs, sequence_length, preprocess_collapse_repeated=False, ctc_merge
_repeated=True, ignore_longer_outputs_than_inputs=False, time_major=True)
'''
loss = tf.nn.ctc_loss(logits, labels, seq_len)#关于ctc loss解决rnn输出和序列不对齐问题
#http://blog.csdn.net/left_think/article/details/76370453
#https://zhuanlan.zhihu.com/p/23293860
cost = tf.reduce_mean(loss)
optimizer = tf.train.MomentumOptimizer(learning_rate=0.01,
momentum=0.9).minimize(cost, global_step=global_step)
#decoded, log_prob = tf.nn.ctc_beam_search_decoder(logits, seq_len, merge_repeated=False)#or "tf.nn.ctc_greedy_decoder"一种解码策略
#acc = tf.reduce_mean(tf.edit_distance(tf.cast(decoded[0], tf.int32), labels))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print (outputs.get_shape())
print (sess.run(loss))
以lstm+ctc对汉字识别为例对tensorflow 中的lstm,ctc loss的调试的更多相关文章
- 在TensorFlow中基于lstm构建分词系统笔记
在TensorFlow中基于lstm构建分词系统笔记(一) https://www.jianshu.com/p/ccb805b9f014 前言 我打算基于lstm构建一个分词系统,通过这个例子来学习下 ...
- tensorflow中的lstm的state
考虑 state_is_tuple Output, new_state = cell(input, state) state其实是两个 一个 c state,一个m(对应下图的 ...
- tensorflow源码分析——CTC
CTC是2006年的论文Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurren ...
- Python中利用LSTM模型进行时间序列预测分析
时间序列模型 时间序列预测分析就是利用过去一段时间内某事件时间的特征来预测未来一段时间内该事件的特征.这是一类相对比较复杂的预测建模问题,和回归分析模型的预测不同,时间序列模型是依赖于事件发生的先后顺 ...
- tensorflow实现基于LSTM的文本分类方法
tensorflow实现基于LSTM的文本分类方法 作者:u010223750 引言 学习一段时间的tensor flow之后,想找个项目试试手,然后想起了之前在看Theano教程中的一个文本分类的实 ...
- 一文详解如何用 TensorFlow 实现基于 LSTM 的文本分类(附源码)
雷锋网按:本文作者陆池,原文载于作者个人博客,雷锋网已获授权. 引言 学习一段时间的tensor flow之后,想找个项目试试手,然后想起了之前在看Theano教程中的一个文本分类的实例,这个星期就用 ...
- 用tensorflow搭建RNN(LSTM)进行MNIST 手写数字辨识
用tensorflow搭建RNN(LSTM)进行MNIST 手写数字辨识 循环神经网络RNN相比传统的神经网络在处理序列化数据时更有优势,因为RNN能够将加入上(下)文信息进行考虑.一个简单的RNN如 ...
- 在Keras中可视化LSTM
作者|Praneet Bomma 编译|VK 来源|https://towardsdatascience.com/visualising-lstm-activations-in-keras-b5020 ...
- LSTM(长短期记忆网络)及其tensorflow代码应用
本文主要包括: 一.什么是LSTM 二.LSTM的曲线拟合 三.LSTM的分类问题 四.为什么LSTM有助于消除梯度消失 一.什么是LSTM Long Short Term 网络即为LSTM,是一种 ...
随机推荐
- 用CSS模拟魔兽世界技能冷却的效果
效果演示 上面的效果看起来还不错吧.在网页里,除了用Flash,我们还是有不少方法可以实现它. 显然这种效果不复杂,一张背景图片,加上前面带有透明度的多边形图层,在脚本控制下就可以转起来了.但问题 ...
- DP———1.最大子连续子序列和
最大连续子序列 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Sub ...
- jquery offset tip
/* * 这是一张 JavaScript 代码草稿纸. * * 输入一些 JavaScript,然后可点击右键或从“执行”菜单中选择: * 1. 运行 对选中的文本求值(eval) (Ctrl+R): ...
- Java笔记(一)
1. ConcurrentModificationException 在遍历容器的同时修改容器里的成员对象可能会抛出该异常 http://www.blogjava.net/EvanLiu/archiv ...
- [ CodeVS冲杯之路 ] P1294
不充钱,你怎么AC? 题目:http://codevs.cn/problem/1294/ 随手一打就是这么漂亮的全排列,想当年我初一还是初二的时候,调了1个多小时才写出来(蒟蒻一枚) 直接DFS每次枚 ...
- centos 下文件夹共享
[root@localhost share]# yum install samba -y[root@localhost share]# cp /etc/samba/smb.conf /etc/samb ...
- FIRST SCRAPY PRJ
zpc@Lenovo-PC:/prj/pyscrapy/a$ scrapy startproject helloword New Scrapy project 'helloword' created ...
- 如何在Android 或Linux 下,做Suspend /Resume 的Debug【转】
转自:http://blog.csdn.net/jacobywu/article/details/24735521 目录(?)[-] Question Answer 加boot 參數 no_conso ...
- MTK_GPIO口的定制
http://blog.csdn.net/zuoyioo7/article/details/77863291如果需要定制GPIO口呢,需要使用mediatek/dct/DrvGen.exe工具,点击O ...
- C++笔试题目大全(笔试宝典)(不断完善中)
1.new . delete . malloc . free 关系 delete 会调用对象的析构函数 , 和 new 对应 free 只会释放内存, new 调用构造函数. malloc 与 fre ...