吴裕雄--天生自然 pythonTensorFlow自然语言处理:PTB 语言模型
import numpy as np
import tensorflow as tf # 1.设置参数。
TRAIN_DATA = "F:\TensorFlowGoogle\\201806-github\\TensorFlowGoogleCode\\Chapter09\\ptb.train" # 训练数据路径。
EVAL_DATA = "F:\TensorFlowGoogle\\201806-github\\TensorFlowGoogleCode\\Chapter09\\ptb.valid" # 验证数据路径。
TEST_DATA = "F:\TensorFlowGoogle\\201806-github\\TensorFlowGoogleCode\\Chapter09\\ptb.test" # 测试数据路径。
HIDDEN_SIZE = 300 # 隐藏层规模。
NUM_LAYERS = 2 # 深层循环神经网络中LSTM结构的层数。
VOCAB_SIZE = 10000 # 词典规模。
TRAIN_BATCH_SIZE = 20 # 训练数据batch的大小。
TRAIN_NUM_STEP = 35 # 训练数据截断长度。 EVAL_BATCH_SIZE = 1 # 测试数据batch的大小。
EVAL_NUM_STEP = 1 # 测试数据截断长度。
NUM_EPOCH = 5 # 使用训练数据的轮数。
LSTM_KEEP_PROB = 0.9 # LSTM节点不被dropout的概率。
EMBEDDING_KEEP_PROB = 0.9 # 词向量不被dropout的概率。
MAX_GRAD_NORM = 5 # 用于控制梯度膨胀的梯度大小上限。
SHARE_EMB_AND_SOFTMAX = True # 在Softmax层和词向量层之间共享参数。
# 2.定义模型
# 通过一个PTBModel类来描述模型,这样方便维护循环神经网络中的状态。
class PTBModel(object):
def __init__(self, is_training, batch_size, num_steps):
# 记录使用的batch大小和截断长度。
self.batch_size = batch_size
self.num_steps = num_steps # 定义每一步的输入和预期输出。两者的维度都是[batch_size, num_steps]。
self.input_data = tf.placeholder(tf.int32, [batch_size, num_steps])
self.targets = tf.placeholder(tf.int32, [batch_size, num_steps]) # 定义使用LSTM结构为循环体结构且使用dropout的深层循环神经网络。
dropout_keep_prob = LSTM_KEEP_PROB if is_training else 1.0
lstm_cells = [tf.nn.rnn_cell.DropoutWrapper(tf.nn.rnn_cell.BasicLSTMCell(HIDDEN_SIZE),output_keep_prob=dropout_keep_prob) for _ in range(NUM_LAYERS)]
cell = tf.nn.rnn_cell.MultiRNNCell(lstm_cells) # 初始化最初的状态,即全零的向量。这个量只在每个epoch初始化第一个batch
# 时使用。
self.initial_state = cell.zero_state(batch_size, tf.float32) # 定义单词的词向量矩阵。
embedding = tf.get_variable("embedding", [VOCAB_SIZE, HIDDEN_SIZE]) # 将输入单词转化为词向量。
inputs = tf.nn.embedding_lookup(embedding, self.input_data) # 只在训练时使用dropout。
if is_training:
inputs = tf.nn.dropout(inputs, EMBEDDING_KEEP_PROB) # 定义输出列表。在这里先将不同时刻LSTM结构的输出收集起来,再一起提供给
# softmax层。
outputs = []
state = self.initial_state
with tf.variable_scope("RNN"):
for time_step in range(num_steps):
if time_step > 0:
tf.get_variable_scope().reuse_variables()
cell_output, state = cell(inputs[:, time_step, :], state)
outputs.append(cell_output)
# 把输出队列展开成[batch, hidden_size*num_steps]的形状,然后再
# reshape成[batch*numsteps, hidden_size]的形状。
output = tf.reshape(tf.concat(outputs, 1), [-1, HIDDEN_SIZE]) # Softmax层:将RNN在每个位置上的输出转化为各个单词的logits。
if SHARE_EMB_AND_SOFTMAX:
weight = tf.transpose(embedding)
else:
weight = tf.get_variable("weight", [HIDDEN_SIZE, VOCAB_SIZE])
bias = tf.get_variable("bias", [VOCAB_SIZE])
logits = tf.matmul(output, weight) + bias # 定义交叉熵损失函数和平均损失。
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.reshape(self.targets, [-1]),logits=logits)
self.cost = tf.reduce_sum(loss) / batch_size
self.final_state = state # 只在训练模型时定义反向传播操作。
if not is_training:
return trainable_variables = tf.trainable_variables()
# 控制梯度大小,定义优化方法和训练步骤。
grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, trainable_variables), MAX_GRAD_NORM)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1.0)
self.train_op = optimizer.apply_gradients(zip(grads, trainable_variables))
# 3.定义数据和训练过程。
# 使用给定的模型model在数据data上运行train_op并返回在全部数据上的perplexity值。
def run_epoch(session, model, batches, train_op, output_log, step):
# 计算平均perplexity的辅助变量。
total_costs = 0.0
iters = 0
state = session.run(model.initial_state)
# 训练一个epoch。
for x, y in batches:
# 在当前batch上运行train_op并计算损失值。交叉熵损失函数计算的就是下一个单
# 词为给定单词的概率。
cost, state, _ = session.run([model.cost, model.final_state, train_op],{model.input_data: x, model.targets: y,model.initial_state: state})
total_costs += cost
iters += model.num_steps # 只有在训练时输出日志。
if output_log and step % 100 == 0:
print("After %d steps, perplexity is %.3f" % (step, np.exp(total_costs / iters)))
step += 1 # 返回给定模型在给定数据上的perplexity值。
return step, np.exp(total_costs / iters) # 从文件中读取数据,并返回包含单词编号的数组。
def read_data(file_path):
with open(file_path, "r") as fin:
# 将整个文档读进一个长字符串。
id_string = ' '.join([line.strip() for line in fin.readlines()])
id_list = [int(w) for w in id_string.split()] # 将读取的单词编号转为整数
return id_list def make_batches(id_list, batch_size, num_step):
# 计算总的batch数量。每个batch包含的单词数量是batch_size * num_step。
num_batches = (len(id_list) - 1) // (batch_size * num_step) # 将数据整理成一个维度为[batch_size, num_batches * num_step]
# 的二维数组。
data = np.array(id_list[: num_batches * batch_size * num_step])
data = np.reshape(data, [batch_size, num_batches * num_step])
# 沿着第二个维度将数据切分成num_batches个batch,存入一个数组。
data_batches = np.split(data, num_batches, axis=1) # 重复上述操作,但是每个位置向右移动一位。这里得到的是RNN每一步输出所需要预测的
# 下一个单词。
label = np.array(id_list[1 : num_batches * batch_size * num_step + 1])
label = np.reshape(label, [batch_size, num_batches * num_step])
label_batches = np.split(label, num_batches, axis=1)
# 返回一个长度为num_batches的数组,其中每一项包括一个data矩阵和一个label矩阵。
return list(zip(data_batches, label_batches))
# 4.主函数。
def main():
# 定义初始化函数。
initializer = tf.random_uniform_initializer(-0.05, 0.05)
# 定义训练用的循环神经网络模型。
with tf.variable_scope("language_model", reuse=None, initializer=initializer):
train_model = PTBModel(True, TRAIN_BATCH_SIZE, TRAIN_NUM_STEP) # 定义测试用的循环神经网络模型。它与train_model共用参数,但是没有dropout。
with tf.variable_scope("language_model",reuse=True, initializer=initializer):
eval_model = PTBModel(False, EVAL_BATCH_SIZE, EVAL_NUM_STEP) # 训练模型。
with tf.Session() as session:
tf.global_variables_initializer().run()
train_batches = make_batches(read_data(TRAIN_DATA), TRAIN_BATCH_SIZE, TRAIN_NUM_STEP)
eval_batches = make_batches(read_data(EVAL_DATA), EVAL_BATCH_SIZE, EVAL_NUM_STEP)
test_batches = make_batches(read_data(TEST_DATA), EVAL_BATCH_SIZE, EVAL_NUM_STEP) step = 0
for i in range(NUM_EPOCH):
print("In iteration: %d" % (i + 1))
step, train_pplx = run_epoch(session, train_model, train_batches,train_model.train_op, True, step)
print("Epoch: %d Train Perplexity: %.3f" % (i + 1, train_pplx)) _, eval_pplx = run_epoch(session, eval_model, eval_batches,tf.no_op(), False, 0)
print("Epoch: %d Eval Perplexity: %.3f" % (i + 1, eval_pplx)) _, test_pplx = run_epoch(session, eval_model, test_batches,tf.no_op(), False, 0)
print("Test Perplexity: %.3f" % test_pplx) if __name__ == "__main__":
main()
吴裕雄--天生自然 pythonTensorFlow自然语言处理:PTB 语言模型的更多相关文章
- 吴裕雄--天生自然 pythonTensorFlow自然语言处理:文本数据预处理--生成训练文件
import sys import codecs # 1. 参数设置 MODE = "PTB_TRAIN" # 将MODE设置为"PTB_TRAIN", &qu ...
- 吴裕雄--天生自然 pythonTensorFlow自然语言处理:Attention模型--测试
import sys import codecs import tensorflow as tf # 1.参数设置. # 读取checkpoint的路径.9000表示是训练程序在第9000步保存的ch ...
- 吴裕雄--天生自然 pythonTensorFlow自然语言处理:Attention模型--训练
import tensorflow as tf # 1.参数设置. # 假设输入数据已经转换成了单词编号的格式. SRC_TRAIN_DATA = "F:\\TensorFlowGoogle ...
- 吴裕雄--天生自然 pythonTensorFlow自然语言处理:Seq2Seq模型--测试
import sys import codecs import tensorflow as tf # 1.参数设置. # 读取checkpoint的路径.9000表示是训练程序在第9000步保存的ch ...
- 吴裕雄--天生自然 pythonTensorFlow自然语言处理:Seq2Seq模型--训练
import tensorflow as tf # 1.参数设置. # 假设输入数据已经用9.2.1小节中的方法转换成了单词编号的格式. SRC_TRAIN_DATA = "F:\\Tens ...
- 吴裕雄--天生自然 pythonTensorFlow自然语言处理:交叉熵损失函数
import tensorflow as tf # 1. sparse_softmax_cross_entropy_with_logits样例. # 假设词汇表的大小为3, 语料包含两个单词" ...
- 吴裕雄--天生自然 pythonTensorFlow图形数据处理:循环神经网络预测正弦函数
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # 定义RNN的参数. HIDDEN_SIZE = ...
- 吴裕雄--天生自然 pythonTensorFlow图形数据处理:数据集高层操作
import tempfile import tensorflow as tf # 1. 列举输入文件. # 输入数据生成的训练和测试数据. train_files = tf.train.match_ ...
- 吴裕雄--天生自然 pythonTensorFlow图形数据处理:数据集基本使用方法
import tempfile import tensorflow as tf # 1. 从数组创建数据集. input_data = [1, 2, 3, 5, 8] dataset = tf.dat ...
随机推荐
- php添加openssl扩展
很多时候都会用到openssl组件,下面就介绍一下linux下php安装openssl扩展: 安 装openssl组件,一般php安装目录中都有许多扩展组件的安装包,当然也包括openssl,例如我的 ...
- [题解] CF622F The Sum of the k-th Powers
CF622F The Sum of the k-th Powers 题意:给\(n\)和\(k\),让你求\(\sum\limits_{i = 1} ^ n i^k \ mod \ 10^9 + 7\ ...
- 实验吧web-难-认真一点!(布尔盲注,py脚本)
也可用bp进行爆破,这里用py脚本. 打看网页输入1,显示You are in,输入2,显示You are not in,是个布尔注入. 然后看看过滤了什么. sql注入没有过滤:--+.or sql ...
- POJ - 1742 Coins(dp---多重背包)
题意:给定n种硬币的价值和数量,问能组成1~m中多少种面值. 分析: 1.dp[j]表示当前用了前i种硬币的情况下,可以组成面值j. 2.eg: 3 10 1 3 4 2 3 1 (1)使用第1种硬币 ...
- jQuery.ajax提交JSON数据
$.ajax({ type: 'POST', url: "URL", contentType:'application/json', //需要加contentType crossD ...
- CF940F Machine Learning(带修莫队)
首先显然应该把数组离散化,然后发现是个带修莫队裸题,但是求mex比较讨厌,怎么办?其实可以这样求:记录每个数出现的次数,以及出现次数的出现次数.至于求mex,直接暴力扫最小的出现次数的出现次数为0的正 ...
- 基础nginx配置文件
nginx的配置文件很长,如果开始就看全部的话会懵逼,以下以最简单的配置文件来学习. 目标:定义一个虚拟主机127.0.0.1 端口是8080 [root@localhost conf]# cat ...
- HTML5 之 简单汇总
参考: HTML5的十大新特性 前端面试必备之html5的新特性 HTML5 1.语义化元素 1.1结构元素 标签 描述 article 表示与上下文不相关的独立内容区域 aside 定义页面的侧边栏 ...
- WordPress迁移服务器后报Nginx404的问题
Wordpress迁移服务器后,只有主页能打开,其它页面都显示404 页面无法访问. 出现这个问题是因为我的Wordpress之前用的服务器是apache+PHP组合,换了服务器后变成了Nginx+P ...
- pycharm调试、设置汇总
目录: 1.pycharm中不能run 2.pycharm基本调试操作 3.pycharm使用技巧 4.pycharm Error running draft: Cannot run program ...