NLP——数据的batching方法

在文本数据中,每个句子的长度不同,常使用填充的操作将句子长度补齐。然而,在自然语言处理中,句子并非随机选取,而是在上下文之间有关联的内容,我们必须将前面的句子的信息传递到后面的句子。如果模型没有大小限制,显然最理想的情况就是将整个文档前后连接起来作为一个句子来训练(如下图所示,有若干个序列,每个序列代表一个句子,每个句子中包含经过预处理的相应单词的编码)。
NLP——数据的batching方法_第1张图片
但是现实根本无法实现,由于文本中通常会包含大量的词汇,所以这种情况必然会导致计算图过大,另外序列过长还可能造成训练中梯度爆炸的问题(梯度爆炸)。为此,我们可以采用并行处理句子的方法,每一次计算可以对多个句子进行并行处理。解决方案是,先将所有的句子即序列罗列成列向量
NLP——数据的batching方法_第2张图片
之后再从中切分出若干个batch大小的数据集(程序中为data,这里只画出前几个)
NLP——数据的batching方法_第3张图片
每次训练需要处理的句子个数和句子中包含的单词数量可以由用户自由设定(即一个batch的行数和列数) 同时,我们还需从每个句子的第二个单词起按照同样的batch大小进行切分(程序中为label),每个label中包含着对应data中所有句子的需要预测的下一个单词。 该方法叫做batching方法

import codecs
import numpy as np

output_path="train.txt"  #语句中相应单词对应的编码文件
TRAIN_BATCH_SIZE = 20   #一个batch的行数
TRAIN_NUM_STEP = 35     #一个batch的列数

def read_data(file_path):
    with codecs.open(file_path, 'r', 'utf-8') as fin:
        id_string = ' '.join([line.strip() for line in fin])
    id_list = [int(w) for w in id_string.split()]
    return id_list

def make_batches(id_list, batch_size, num_step):
    num_batches = len(id_list) // (batch_size * num_step)  #获取batch的大小
    data = np.array(id_list[:num_batches * batch_size * num_step])
    data = np.reshape(data, [batch_size, num_batches * num_step])
    data_batches = np.split(data, num_batches, axis=1)

    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)
    return list(zip(data_batches, label_batches))

def main():
    train_batches = make_batches(read_data(output_path), TRAIN_BATCH_SIZE, TRAIN_NUM_STEP)
    # 在这里插入模型训练代码

if __name__== "__main__":
    main()

你可能感兴趣的:(NLP自然语言处理)