根据自己理解写的代码注释importtimeimportnumpy asnpimporttensorflow astfimportreader

#flags = tf.flags#logging = tf.logging#flags.DEFINE_string("save_path", None,#                    "Model output directory.")#flags.DEFINE_bool("use_fp16", False,#                  "Train using 16-bit floats instead of 32bit floats")#FLAGS = flags.FLAGS#def data_type():#  return tf.float16 if FLAGS.use_fp16 else tf.float32#输入数据classclassPTBInput(object):"""The input data."""def__init__(self, config, data, name=None):self.batch_size = batch_size = config.batch_sizeself.num_steps = num_steps = config.num_steps#LSTM展开步数self.epoch_size = ((len(data) // batch_size) - 1) // num_steps#每个epoch需要多少轮训练的迭代self.input_data, self.targets = reader.ptb_producer(data, batch_size, num_steps, name=name)#返回Tensor,并且每个shape为[batch_size, num_steps]#######################################################语言模型classclassPTBModel(object):"""The PTB model."""#训练标记is_training,配置参数config,PTBInput类的实例input_def__init__(self, is_training, config, input_):self._input = input_

batch_size = input_.batch_size
num_steps = input_.num_steps
size = config.hidden_size#LSTM隐含节点数vocab_size = config.vocab_size#词汇表大小# Slightly better results can be obtained with forget gate biases# initialized to 1 but the hyperparameters(超参数) of the model would need to be# different than reported in the paper.#BasicLSTMCell类是最基本的LSTM循环神经网络单元。 num_units: LSTM cell层中的单元数#forget_bias: forget gates中的偏置 。state_is_tuple: 还是设置为True吧, 返回 (c_state , m_state)的二元组deflstm_cell():returntf.contrib.rnn.BasicLSTMCell(size, forget_bias=0.0, state_is_tuple=True)
attn_cell = lstm_cell#如果在训练状态,且dropout的keep_prob<1,则在前面的lstm_cell之后,接一个dropout层ifis_training andconfig.keep_prob < 1:defattn_cell():returntf.contrib.rnn.DropoutWrapper(lstm_cell(), output_keep_prob=config.keep_prob)#RNN堆叠函数将前面构造的lstm_cell多层堆叠得到cell,堆叠次数为config.num_layerscell = tf.contrib.rnn.MultiRNNCell([attn_cell() for_ inrange(config.num_layers)], state_is_tuple=True)#LSTM单元初始化状态为0self._initial_state = cell.zero_state(batch_size, tf.float32)

withtf.device("/cpu:0"):#embedding矩阵[vocab_size, size],size为hidden_size,即LSTM隐含节点数。name="embedding"embedding = tf.get_variable("embedding", [vocab_size, size], dtype=tf.float32)#Looks up `ids` in a list of embedding tensors.params=embedding,ids=input_.input_data#ids有索引的意思#返回的张量tensor,shape为shape(ids) + shape(params)[1:]# print(embedding.shape)#(10000, 200)# print(input_.input_data.shape)#(20, 20)# print(np.shape(embedding)[1:])#(200,)#我们需要对批数据中的单词建立嵌套向量inputs = tf.nn.embedding_lookup(embedding, input_.input_data)# print(inputs.shape)#(20, 20, 200)#如果为训练状态,且dropout的keep_prob<1,再添上一层dropout。跟rnn的dropout有所不同ifis_training andconfig.keep_prob < 1:
inputs = tf.nn.dropout(inputs, config.keep_prob)

# Simplified version of models/tutorials/rnn/rnn.py's rnn().# This builds an unrolled LSTM for tutorial purposes only.# In general, use the rnn() or state_saving_rnn() from rnn.py.## The alternative version of the code below is:## inputs = tf.unstack(inputs, num=num_steps, axis=1)# outputs, state = tf.nn.rnn(cell, inputs,#                            initial_state=self._initial_state)outputs = []
state = self._initial_state#表示各个batch中的状态withtf.variable_scope("RNN"):fortime_step inrange(num_steps):iftime_step > 0:#scope范围,reuse重复使用。tf.get_variable_scope().reuse_variables()#允许共享当前scope下的所有变量(cell_output, state) = cell(inputs[:, time_step, :], state)#按照顺序向cell输入文本数据outputs.append(cell_output)

#tf.concat拼接concat(values, axis, name='concat')output = tf.reshape(tf.concat(outputs, 1), [-1, size])
softmax_w = tf.get_variable("softmax_w", [size, vocab_size], dtype=tf.float32)
softmax_b = tf.get_variable("softmax_b", [vocab_size], dtype=tf.float32)
logits = tf.matmul(output, softmax_w) + softmax_b#y=wx+b#计算输出logits和targets的偏差loss = tf.contrib.legacy_seq2seq.sequence_loss_by_example([logits],[tf.reshape(input_.targets, [-1])],[tf.ones([batch_size * num_steps], dtype=tf.float32)])self._cost = cost = tf.reduce_sum(loss) / batch_sizeself._final_state = state

if notis_training:return#定义学习速率变量_lr,并设置为不可训练self._lr = tf.Variable(0.0, trainable=False)
tvars = tf.trainable_variables()#获取模型中全部可训练参数(trainable=True),得到一个列表#gradients针对前面得到的cost,计算tvars的梯度#clip_by_global_norm设置梯度最大范数max_grad_normgrads, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars),config.max_grad_norm)
optimizer = tf.train.GradientDescentOptimizer(self._lr)#apply_gradients将前面clip(修剪)过的梯度应用到所有可训练的参数tvars上#使用train.get_or_create_global_step生成全局统一的训练步数self._train_op = optimizer.apply_gradients(zip(grads, tvars),global_step=tf.train.get_or_create_global_step())

#_new_lr(new learning rate)placeholder用以控制学习速率self._new_lr = tf.placeholder(tf.float32, shape=[], name="new_learning_rate")#定义操作_lr_update,assign将_new_lr的值赋给当前学习速率_lrself._lr_update = tf.assign(self._lr, self._new_lr)

#函数作用是在外部控制模型的学习速率,方法是将学习速率值传入_new_lr这个placeholder,并执行_lr_update操作来完成对学习速率的修改defassign_lr(self, session, lr_value):
session.run(self._lr_update, feed_dict={self._new_lr: lr_value})

#######################################################  @property装饰器可以将返回变量设置为只读,防止修改变量引发的问题@propertydefinput(self):returnself._input

@propertydefinitial_state(self):returnself._initial_state

@propertydefcost(self):returnself._cost

@propertydeffinal_state(self):returnself._final_state

@propertydeflr(self):returnself._lr

@propertydeftrain_op(self):returnself._train_op

######################################################classSmallConfig(object):"""Small config."""init_scale = 0.1#网络中权重值的初始scalelearning_rate = 1.0#学习速率初始值max_grad_norm = 5#梯度的最大范数num_layers = 2#LSTM可堆叠的层数num_steps = 20#LSTM梯度反向传播的展开步数hidden_size = 200#LSTM隐含层节点数max_epoch = 4#初始学习速率可训练的epoch数,在此之后需要调整学习速率max_max_epoch = 13#总共可训练的epoch数keep_prob = 1.0#dropout层的保留节点比例lr_decay = 0.5#学习速率衰减速度batch_size = 20#每个batch中样本数量vocab_size = 10000#词汇表大小classMediumConfig(object):"""Medium config."""init_scale = 0.05learning_rate = 1.0max_grad_norm = 5num_layers = 2num_steps = 35hidden_size = 650max_epoch = 6max_max_epoch = 39keep_prob = 0.5lr_decay = 0.8batch_size = 20vocab_size = 10000classLargeConfig(object):"""Large config."""init_scale = 0.04learning_rate = 1.0max_grad_norm = 10num_layers = 2num_steps = 35hidden_size = 1500max_epoch = 14max_max_epoch = 55keep_prob = 0.35lr_decay = 1/ 1.15batch_size = 20vocab_size = 10000classTestConfig(object):"""Tiny config, for testing."""init_scale = 0.1learning_rate = 1.0max_grad_norm = 1num_layers = 1num_steps = 2hidden_size = 2max_epoch = 1max_max_epoch = 1keep_prob = 1.0lr_decay = 0.5batch_size = 20vocab_size = 10000######################################################defrun_epoch(session, model, eval_op=None, verbose=False):"""Runs the model on the given data."""start_time = time.time()#当前时间costs = 0.0iters = 0state = session.run(model.initial_state)#初始化状态,并获得初始状态fetches = {"cost": model.cost,"final_state": model.final_state,}ifeval_op is not None:
fetches["eval_op"] = eval_op#如果有评测操作eval_op,一并加入fetchesforstep inrange(model.input.epoch_size):
feed_dict = {}fori, (c, h) inenumerate(model.initial_state):
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h

vals = session.run(fetches, feed_dict)
cost = vals["cost"]
state = vals["final_state"]

costs += cost
iters += model.input.num_steps

#每完成10%的epoch,就进行一次结果展示,依次为当前epoch进度,perplexity(混乱),训练速度(单词数每秒),最后返回perplexity作为函数结果#perplexity(平均cost的自然常数指数,是语言模型中,常用来比较模型性能的重要指标,越低代表模型输出的概率分布在预测样本上越好)ifverbose andstep % (model.input.epoch_size // 10) == 10:print("%.3f perplexity: %.3f speed: %.0f wps"%(step * 1.0/ model.input.epoch_size, np.exp(costs / iters),iters * model.input.batch_size / (time.time() - start_time)))

returnnp.exp(costs / iters)

#######################################################先手动解压,reader.ptb_raw_data只能读取解压后的数据raw_data = reader.ptb_raw_data('/Users/qyk/Desktop/py/tensorflow/LSTM-PTB/simple-examples/data/')
train_data, valid_data, test_data, _ = raw_data

config = SmallConfig()
eval_config = SmallConfig()
eval_config.batch_size = 1eval_config.num_steps = 1#创建默认的Graphwithtf.Graph().as_default():#设置参数初始化器,参数范围【-config.init_scale,config.init_scale】initializer = tf.random_uniform_initializer(-config.init_scale,config.init_scale)

#PTBInput和PTBModel创建用来训练的模型m,验证模型mvalid,测试模型mtestwithtf.name_scope("Train"):
train_input = PTBInput(config=config, data=train_data, name="TrainInput")withtf.variable_scope("Model", reuse=None, initializer=initializer):
m = PTBModel(is_training=True, config=config, input_=train_input)#tf.scalar_summary("Training Loss", m.cost)#tf.scalar_summary("Learning Rate", m.lr)withtf.name_scope("Valid"):
valid_input = PTBInput(config=config, data=valid_data, name="ValidInput")withtf.variable_scope("Model", reuse=True, initializer=initializer):
mvalid = PTBModel(is_training=False, config=config, input_=valid_input)#tf.scalar_summary("Validation Loss", mvalid.cost)withtf.name_scope("Test"):
test_input = PTBInput(config=eval_config, data=test_data, name="TestInput")withtf.variable_scope("Model", reuse=True, initializer=initializer):
mtest = PTBModel(is_training=False, config=eval_config,input_=test_input)

sv = tf.train.Supervisor()#创建训练管理器withsv.managed_session() assession:#使用sv.managed_session创建默认sessionfori inrange(config.max_max_epoch):
lr_decay = config.lr_decay ** max(i + 1- config.max_epoch, 0.0)
m.assign_lr(session, config.learning_rate * lr_decay)

print("Epoch: %d Learning rate: %.3f"% (i + 1, session.run(m.lr)))
train_perplexity = run_epoch(session, m, eval_op=m.train_op,verbose=True)print("Epoch: %d Train Perplexity: %.3f"% (i + 1, train_perplexity))
valid_perplexity = run_epoch(session, mvalid)print("Epoch: %d Valid Perplexity: %.3f"% (i + 1, valid_perplexity))

test_perplexity = run_epoch(session, mtest)print("Test Perplexity: %.3f"% test_perplexity)#perplexity代表模型下结论时的困惑程度,越小越好# if FLAGS.save_path:#   print("Saving model to %s." % FLAGS.save_path)#   sv.saver.save(session, FLAGS.save_path, global_step=sv.global_step)#if __name__ == "__main__":#  tf.app.run()

tensorflow实现基于LSTM的语言模型相关推荐

  1. TensorFlow 实现基于LSTM的语言模型

    一.LSTM的相关概念 博客上有很多讲解的很好的博主,我看的是这个博主的关于LSTM的介绍,感觉很全面,如果对LSTM原理不太明白的,可以点击这个链接.LSTM相关概念,这里就不多做介绍了哈! 二.G ...

  2. Tensorflow:基于LSTM生成藏头诗

    Tensorflow:基于LSTM生成藏头诗 最近在学习TensorFlow,学习到了RNN这一块,相关的资料不是很多,了解到使用RNN可以生成藏头诗之后,我就决定拿这个下手啦! 本文不介绍RNN以及 ...

  3. TensorFlow实战12:实现基于LSTM的语言模型

    1.LSTM的语言模型简介 LSTM(Long Short Term Memory),用来处理有时序联系的信息效果非常明显,在很多情况下,卷积神经网络虽然处理图片增加了其空间特征的联系,但是对于图片与 ...

  4. Tensorflow实例:实现基于LSTM的语言模型

    RNN 人每次思考时不会重头开始,而是保留之前思考的一些结果为现在的决策提供支持.例如我们对话时,我们会根据上下文的信息理解一句话的含义,而不是对每一句话重头进行分析.传统的神经网络不能实现这个功能, ...

  5. tensorflow实现基于LSTM的文本分类方法

    http://blog.csdn.net/u010223750/article/details/53334313?locationNum=7&fps=1 引言 学习一段时间的tensor fl ...

  6. 【Language model】使用RNN LSTM训练语言模型 写出45°角仰望星空的文章

    开篇 这篇文章主要是实战内容,不涉及一些原理介绍,原理介绍为大家提供一些比较好的链接: 1. Understanding LSTM Networks : RNN与LSTM最为著名的文章,贴图和内容都恰 ...

  7. java rnn生成古诗_Tensorflow:基于LSTM轻松生成各种古诗

    原标题:Tensorflow:基于LSTM轻松生成各种古诗 本文代码在公众号 datadw 里 回复古诗即可获取. RNN不像传统的神经网络-它们的输出输出是固定的,而RNN允许我们输入输出向量序列. ...

  8. DL之LSTM:基于tensorflow框架利用LSTM算法对气温数据集训练并回归预测

    DL之LSTM:基于tensorflow框架利用LSTM算法对气温数据集训练并回归预测 目录 输出结果 核心代码 输出结果 数据集 tensorboard可视化 iter: 0 loss: 0.010 ...

  9. TF之LSTM:基于tensorflow框架自定义LSTM算法实现股票历史(1990~2015数据集,6112预测后100+单变量最高)行情回归预测

    TF之LSTM:基于tensorflow框架自定义LSTM算法实现股票历史(1990~2015数据集,6112预测后100+单变量最高)行情回归预测 目录 输出结果 LSTM代码 输出结果 数据集 L ...

最新文章

  1. SpringBoot巧用 @Async 提升API接口并发能力
  2. canvas中的碰撞检测笔记
  3. 红帽虚拟化RHEV3.2创建虚拟机(图文Step by Step)
  4. 2008-08-24
  5. Eclipse自动代码补全
  6. 如何帮助金融客户“用好云”?
  7. ftp ---- 配置文件(默认配置文件解读)
  8. Entity Framework Fluent API
  9. 12.大数据架构详解:从数据获取到深度学习 --- 大数据技术开发文化
  10. ArcMap怎么导出shape文件到奥维互动地图
  11. 计算机课软件有哪些,电脑录课有哪些软件?
  12. WPS简历模板的图标怎么修改_官方发福利一起来薅羊毛啦!教你免费领WPS会员
  13. linux设备连接磁带机,Linux磁带机设备绑定
  14. 手机扫描识别Vin码识别
  15. 数据结构和算法(二):摘要算法之SHA和MD5
  16. Snipaste等截图px与浏览器内容px不一样
  17. 数据结构——树|N叉树之孩子双亲表示法——顺序存储结构+链表
  18. JVM-常见JVM参数、如何查看JVM参数、如何动态设置JVM参数
  19. 好好学习,天天向上——“C”
  20. (翻译)Few-Shot Object Detection with Attention-RPN and Multi-Relation Detector具有注意力RPN和多关系检测器的小样本目标检测

热门文章

  1. 计算机毕业设计ssm电商后台系统c83si系统+程序+源码+lw+远程部署
  2. nxn次方求和函数_数学思维之旅-从等差数列到黎曼函数
  3. Google安卓排行榜接口提示12501错误
  4. 角蜂鸟视觉套件 创意你的人工智能
  5. OptiMode应用矢量有限元法模拟表面等离子体激元
  6. 瓦刀发布,必属精品:Domino评审、表决系统V2.0
  7. 工作流程及常见问题,想做工作认真看完
  8. 解决M1处理器安装adobe闪退问题 After Effect cc AE 2020 M1直装稳定版支持M1系统 MAC苹果 M1芯片处理器
  9. (转)2018CRM系统最新排行榜
  10. 数据驱动的数字化转型:从流程驱动到数据驱动