tensorflow实现基于LSTM的语言模型

  1. 云栖社区>
  2. 博客>
  3. 正文

tensorflow实现基于LSTM的语言模型

隐士2018 2018-01-20 13:34:26 浏览2300
展开阅读全文
根据自己理解写的代码注释


import time
import numpy as np
import tensorflow as tf
import reader

#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


#输入数据class
class PTBInput(object):
"""The input data."""

def __init__(self, config, data, name=None):
self.batch_size = batch_size = config.batch_size
self.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]


######################################################
#语言模型class
class PTBModel(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)的二元组
def lstm_cell():
return tf.contrib.rnn.BasicLSTMCell(size, forget_bias=0.0, state_is_tuple=True)
attn_cell = lstm_cell
#如果在训练状态,且dropout的keep_prob<1,则在前面的lstm_cell之后,接一个dropout层
if is_training and config.keep_prob < 1:
def attn_cell():
return tf.contrib.rnn.DropoutWrapper(lstm_cell(), output_keep_prob=config.keep_prob)
#RNN堆叠函数将前面构造的lstm_cell多层堆叠得到cell,堆叠次数为config.num_layers
cell = tf.contrib.rnn.MultiRNNCell([attn_cell() for _ in range(config.num_layers)], state_is_tuple=True)
#LSTM单元初始化状态为0
self._initial_state = cell.zero_state(batch_size, tf.float32)

with tf.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有所不同
if is_training and config.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中的状态
with tf.variable_scope("RNN"):
for time_step in range(num_steps):
if time_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_size
self._final_state = state

if not is_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_norm
grads, _ = 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的值赋给当前学习速率_lr
self._lr_update = tf.assign(self._lr, self._new_lr)

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

######################################################

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

@property
def initial_state(self):
return self._initial_state

@property
def cost(self):
return self._cost

@property
def final_state(self):
return self._final_state

@property
def lr(self):
return self._lr

@property
def train_op(self):
return self._train_op

######################################################

class SmallConfig(object):
"""Small config."""
init_scale = 0.1#网络中权重值的初始scale
learning_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#词汇表大小


class MediumConfig(object):
"""Medium config."""
init_scale = 0.05
learning_rate = 1.0
max_grad_norm = 5
num_layers = 2
num_steps = 35
hidden_size = 650
max_epoch = 6
max_max_epoch = 39
keep_prob = 0.5
lr_decay = 0.8
batch_size = 20
vocab_size = 10000


class LargeConfig(object):
"""Large config."""
init_scale = 0.04
learning_rate = 1.0
max_grad_norm = 10
num_layers = 2
num_steps = 35
hidden_size = 1500
max_epoch = 14
max_max_epoch = 55
keep_prob = 0.35
lr_decay = 1 / 1.15
batch_size = 20
vocab_size = 10000


class TestConfig(object):
"""Tiny config, for testing."""
init_scale = 0.1
learning_rate = 1.0
max_grad_norm = 1
num_layers = 1
num_steps = 2
hidden_size = 2
max_epoch = 1
max_max_epoch = 1
keep_prob = 1.0
lr_decay = 0.5
batch_size = 20
vocab_size = 10000

######################################################

def run_epoch(session, model, eval_op=None, verbose=False):
"""Runs the model on the given data."""
start_time = time.time()#当前时间
costs = 0.0
iters = 0
state = session.run(model.initial_state)#初始化状态,并获得初始状态

fetches = {"cost": model.cost,"final_state": model.final_state,}
if eval_op is not None:
fetches["eval_op"] = eval_op#如果有评测操作eval_op,一并加入fetches

for step in range(model.input.epoch_size):
feed_dict = {}
for i, (c, h) in enumerate(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的自然常数指数,是语言模型中,常用来比较模型性能的重要指标,越低代表模型输出的概率分布在预测样本上越好)
if verbose and step % (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)))

return np.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 = 1
eval_config.num_steps = 1

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

#PTBInput和PTBModel创建用来训练的模型m,验证模型mvalid,测试模型mtest
with tf.name_scope("Train"):
train_input = PTBInput(config=config, data=train_data, name="TrainInput")
with tf.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)

with tf.name_scope("Valid"):
valid_input = PTBInput(config=config, data=valid_data, name="ValidInput")
with tf.variable_scope("Model", reuse=True, initializer=initializer):
mvalid = PTBModel(is_training=False, config=config, input_=valid_input)
#tf.scalar_summary("Validation Loss", mvalid.cost)

with tf.name_scope("Test"):
test_input = PTBInput(config=eval_config, data=test_data, name="TestInput")
with tf.variable_scope("Model", reuse=True, initializer=initializer):
mtest = PTBModel(is_training=False, config=eval_config,input_=test_input)

sv = tf.train.Supervisor()#创建训练管理器
with sv.managed_session() as session:#使用sv.managed_session创建默认session
for i in range(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()

网友评论

登录后评论
0/500
评论
隐士2018
+ 关注