您的位置:首页 > 理论基础 > 计算机网络

深度学习d2:文本预处理、语言模型、循环神经网络基础

2020-03-05 19:11 1211 查看

文本预处理

  • 步骤

  1. 读入文本
    代码:

    import collections
    import re
    def read_time_machine():
    #打开文本文件,创建文本对象f
    with open('/Users/wuruolan/Downloads/35-0.txt', 'r') as f:
    #每次处理文件的一行,strip函数去掉前缀、后缀的空格字符,lower函数把所有大写字母变成小写
    #re.sub为正则表达式的替换函数,由a-z构成的至少为1的字符串,+代表是闭包
    lines = [re.sub('[^a-z]+', ' ', line.strip().lower()) for line in f]
    return lines
  2. 分词

    #setences是个列表,列表元素是字符串
    #token是标志,标志要做哪个级别的分词
    def tokenize(sentences, token='word'):
    """Split sentences into word or char tokens"""
    if token == 'word': #用空格做分隔符
    return [sentence.split(' ') for sentence in sentences]
    elif token == 'char': #直接把字符串转换为列表即可
    return [list(sentence) for sentence in sentences]
    else:
    print('ERROR: unkown token type '+token)
  3. 建立字典,将每个词映射到一个唯一的索引(index)

    class Vocab(object): #把词映射到索引编号
    def __init__(self, tokens, min_freq=0, use_special_tokens=False):
    #先去重,再筛掉一些词,接着还有可能增加一些特殊的标记
    counter = count_corpus(tokens)  #counter是个字典,<key,value> <词,词频>
    self.token_freqs = list(counter.items()) #将counter变成列表。
    self.idx_to_token = [] #记录最终需要维护的token
    if use_special_tokens:
    # padding, begin of sentence, end of sentence, unknown
    self.pad, self.bos, self.eos, self.unk = (0, 1, 2, 3)
    self.idx_to_token += ['<pad>', '<bos>', '<eos>', '<unk>']
    #上述token分别表示padding,begin of sentence,end of sentence,unkown
    #pad的用处:同一个batch的句子,长度不一定是一样的,这些句子中短的就要补充到长的那么长
    #bos、eos的用处:标记一个句子的开始和结束
    #unk:有些词是不在语料库中的
    else:
    self.unk = 0
    self.idx_to_token += ['unk']
    self.idx_to_token += [token for token, freq in self.token_freqs
    if freq >= min_freq and token not in self.idx_to_token]
    #词频大于设置的最小值,且不再语料库中(pad、bos、eos、unk)
    #idx_to_token就天然是从下标->词语的映射
    #下面建立词语->下标的映射
    self.token_to_idx = dict()
    for idx, token in enumerate(self.idx_to_token):
    self.token_to_idx[token] = idx
    #返回长度
    def __len__(self):
    return len(self.idx_to_token)
    #返回词语对应的序号
    def __getitem__(self, tokens):
    if not isinstance(tokens, (list, tuple)):
    return self.token_to_idx.get(tokens, self.unk)
    return [self.__getitem__(token) for token in tokens]
    #返回序号对应的词语
    def to_tokens(self, indices):
    if not isinstance(indices, (list, tuple)):
    return self.idx_to_token[indices]
    return [self.idx_to_token[index] for index in indices]
    #把二维列表sentence变成一维的token
    def count_corpus(sentences):
    tokens = [tk for st in sentences for tk in st]
    return collections.Counter(tokens)  # 返回一个字典,记录每个词的出现次数
  4. 将文本从词的序列转换为索引的序列,方便输入模型

    for i in range(8, 10): #输出第八行~第九行的单词及其对应的序列
    print('words:', tokens[i])
    print('indices:', vocab[tokens[i]])
  • 存在缺点及改进

  1. 标点符号通常可以提供语义信息,但是我们的方法直接将其丢弃了
  2. 类似“shouldn’t", "doesn’t"这样的词会被错误地处理
  3. 类似"Mr.", "Dr."这样的词会被错误地处理
  • spaCy
    import spacy
    nlp = spacy.load('en_core_web_sm')
    doc = nlp(text)
    print([token.text for token in doc])
  • NLTK:
    from nltk.tokenize import word_tokenize
    from nltk import data
    data.path.append('/home/kesci/input/nltk_data3784/nltk_data')
    print(word_tokenize(text))

语言模型

语言模型简单来说,就是给定一段序列,判断这段序列是否合理(概率是多少)。
即给定一个长度为𝑇 的词的序列 𝑤1,𝑤2,…,𝑤𝑇 ,语言模型将计算该序列的概率:
𝑃(𝑤1,𝑤2,…,𝑤𝑇),其中𝑤𝑡为时间步t的输出或标签。
在语音识别中,可通过前面的语义预测后面的单词是什么。
  • 计算

    𝑃 (𝑤1,𝑤2,…,𝑤𝑇)=∏ 𝑃 (𝑤𝑡∣𝑤1,…,𝑤𝑡−1) (𝑡∈[1,𝑇 ])
    𝑃 (𝑤1∣𝑤2)=𝑃 (𝑤1,𝑤2) / 𝑃(𝑤2)

  • n元语法

    n元语法通过n阶马尔可夫假设简化了语言模型的计算。即一个词的出现只与前面 𝑛 个词相关。如果基于 𝑛−1 阶马尔可夫链,则可将n元语法语言模型改写成:
    𝑃(𝑤1,𝑤2,…,𝑤𝑇)≈∏𝑃(𝑤𝑡∣𝑤𝑡−(𝑛−1),…,𝑤𝑡−1) (𝑡∈[1,𝑇 ])
    3元语法为:
    𝑃(𝑤1,𝑤2,𝑤3,𝑤4)=𝑃(𝑤1)𝑃(𝑤2∣𝑤1)𝑃(𝑤3∣𝑤1,𝑤2)𝑃(𝑤4∣𝑤2,𝑤3)
    缺点

    参数空间过大(所需空间与n是指数关系)
  • 数据稀疏(齐夫定律,算出来大部分词的词频都是0)
  • 实例

    预处理语言模型数据集,并将其转换成字符级循环神经网络所需的输入格式。

    1. 读取字符集
    2. 建立字符索引
    3. 时序数据的采样

      样本中需包含连续的字符,标签就是这些连续字符下一个连续字符可能是什么。(n个 --> n个,如1234->2345),故序列长度为T,时间步数为n,则共用T-n个样本,但样本太多了,要用下面两种方法进行采样。
    • 连续采样
      在随机采样中,每个样本是原始序列上任意截取的一段序列。相邻的两个随机小批量在原始序列上的位置不一定相毗邻。因此,我们无法用一个小批量最终时间步的隐藏状态来初始化下一个小批量的隐藏状态。在训练模型时,每次随机采样前都需要重新初始化隐藏状态
      代码
    # 本函数已保存在d2lzh包中方便以后使用
    #batch_size为批量大小,即行数;num_steps为时间步长,即列数
    def data_iter_random(corpus_indices, batch_size, num_steps, ctx=None):
    # 减1是因为输出的索引是相应输入的索引加1
    num_examples = (len(corpus_indices) - 1) // num_steps #可以有多少个样本个数
    epoch_size = num_examples // batch_size #总共要有多少个周期,总的样本数÷一批要的样本数
    example_indices = list(range(num_examples)) #每个样本的第一个字符在整体 序列中的下标
    random.shuffle(example_indices)  #随机采样
    
    # 返回从pos开始的长为num_steps的序列
    def _data(pos):
    return corpus_indices[pos: pos + num_steps]
    
    for i in range(epoch_size):
    # 每次读取batch_size个随机样本
    i = i * batch_size
    batch_indices = example_indices[i: i + batch_size] #当前batch,各个样本首字符的下标
    X = [_data(j * num_steps) for j in batch_indices]  #样本
    Y = [_data(j * num_steps + 1) for j in batch_indices] #样本对应的标签
    yield nd.array(X, ctx), nd.array(Y, ctx)
  • 相邻采样
    令相邻的两个随机小批量在原始序列上的位置相毗邻。故只需在每一个迭代周期开始时初始化隐藏状态。但模型参数的梯度计算将依赖所有串联起来的小批量序列,从而在同一迭代周期中,随着迭代次数的增加,梯度的计算开销会越来越大
    代码:

    # 本函数已保存在d2lzh包中方便以后使用
    def data_iter_consecutive(corpus_indices, batch_size, num_steps, ctx=None):
    corpus_indices = nd.array(corpus_indices, ctx=ctx)
    data_len = len(corpus_indices)
    batch_len = data_len // batch_size #每个批量的长度
    #把序号reshape成一个二维矩阵,第一个维度(行)是批量大小,第二个维度(列)是批量长度
    #该矩阵的每一列,就是一个batch
    indices = corpus_indices[0: batch_size*batch_len].reshape((
    batch_size, batch_len))
    #循环周期 = 批量长度 / 步长 ,即每个批量中有多少个样本
    # batch_len -1 的原因是,他不能包含最后一个字符
    epoch_size = (batch_len - 1) // num_steps
    for i in range  (epoch_size):
    i = i * num_steps #当前批量首个字符对应的下标
    X = indices[:, i: i + num_steps] #样本(取的都是列)
    Y = indices[:, i + 1: i + num_steps + 1] #标签 (取的都是列)
    yield X, Y
  • 循环神经网络基础

    并非刚性记忆所有固定长度的序列,而是通过隐藏状态来存储之前时间步的信息。利用多层感知机添加隐藏状态来将它变成循环神经网络。

    • 不含隐藏状态的神经网络

      即之前含但隐藏层的多层感知机。
      𝐻=𝜙(𝑋𝑊𝑥ℎ+𝑏ℎ),𝑂=𝐻𝑊ℎ𝑞+𝑏𝑞

    • 含隐藏状态的循环神经网络

      考虑输入数据存在时间相关性。则有:
      𝐻𝑡=𝜙(𝑋𝑡𝑊𝑥ℎ+𝐻𝑡−1𝑊ℎℎ+𝑏ℎ)
      𝑋𝑡∈ℝ𝑛×𝑑 是序列中时间步𝑡的小批量输入
      𝐻𝑡∈ℝ𝑛×ℎ是该时间步的隐藏变量,故𝐻𝑡-1是上一时间步的隐藏变量,隐藏变量也称隐藏状态
      𝑊ℎℎ∈ℝℎ×ℎ用来描述在当前时间步如何使用上一时间步的隐藏变量
      𝑊𝑥ℎ∈ℝ𝑑×ℎ是隐藏层的权重
      循环神经网络模型参数的数量不随时间步的增加而增长
      上述计算是循环的,即计算出前一项才能得到后一项,故叫循环神经网络。
    • 输出层的输出为:(即预测的结果)
      𝑂𝑡=𝐻𝑡𝑊ℎ𝑞+𝑏𝑞
    • 如下图,Ht+1依赖于Ht ,Ht依赖于Ht-1,故t+1相当于依赖于前面所有字符。

      隐藏状态中 𝑋𝑡𝑊𝑥ℎ+𝐻𝑡−1𝑊ℎℎ 计算等价于 𝑋𝑡 与 𝐻𝑡−1 连结后的矩阵乘以 𝑊𝑥ℎ 与 𝑊ℎℎ 连结后的矩阵
  • 应用:基于字符级循环神经网络的语言模型

  • 从零开始实现

    1. one-hot向量
      词 -> 向量,为了获得神经网络的输入。
      若共有N个字符,那么索引为 i 的字符对应的向量就是:
      [ 0, 0, … , 1 , … , 0 ] (即除了第 i 个为1之外,其他都是0

    2. 初始化模型参数

      num_inputs, num_hiddens, num_outputs = vocab_size, 256, vocab_size
      ctx = d2l.try_gpu()
      print('will use', ctx)
      
      def get_params():
      def _one(shape): #给定一个shape,会返回一个随机初始化好的形状为shape的参数
      return nd.random.normal(scale=0.01, shape=shape, ctx=ctx)
      
      # 隐藏层参数
      W_xh = _one((num_inputs, num_hiddens))
      W_hh = _one((num_hiddens, num_hiddens))
      b_h = nd.zeros(num_hiddens, ctx=ctx) #初始化为0
      # 输出层参数
      W_hq = _one((num_hiddens, num_outputs))
      b_q = nd.zeros(num_outputs, ctx=ctx) #初始化为0
      # 附上梯度
      params = [W_xh, W_hh, b_h, W_hq, b_q]
      for param in params:
      param.attach_grad()
      return params
    3. 定义模型

      def rnn(inputs, state, params):
      # inputs和outputs皆为num_steps个形状为(batch_size, vocab_size)的矩阵
      W_xh, W_hh, b_h, W_hq, b_q = params #模型的参数
      H, = state # 状态的初始值 ,包含了隐藏状态等。
      outputs = []  #维护输出
      for X in inputs:
      #各个时间步的隐藏状态
      H = nd.tanh(nd.dot(X, W_xh) + nd.dot(H, W_hh) + b_h)
      #输出
      Y = nd.dot(H, W_hq) + b_q
      outputs.append(Y)
      return outputs, (H,) #返回状态,方便后面训练
    4. 定义预测函数

      #给定前缀prefix,去预测下num_chars个字符
      def predict_rnn(prefix, num_chars, rnn, params, init_rnn_state,
      num_hiddens, vocab_size, ctx, idx_to_char, char_to_idx):
      #构造并初始化状态
      state = init_rnn_state(1, num_hiddens, ctx)
      #output记录prefix和预测的num_chars个字符
      output = [char_to_idx[prefix[0]]]
      for t in range(num_chars + len(prefix) - 1):
      # 将上一时间步的输出作为当前时间步的输入
      X = to_onehot(nd.array([output[-1]], ctx=ctx), vocab_size)
      # 计算输出和更新隐藏状态
      (Y, state) = rnn(X, state, params)
      # 下一个时间步的输入是prefix里的字符或者当前的最佳预测字符
      if t < len(prefix) - 1:
      output.append(char_to_idx[prefix[t + 1]])
      else:
      output.append(int(Y[0].argmax(axis=1).asscalar()))
      return ''.join([idx_to_char[i] for i in output]) #把字符索引都转换成字符
    5. 裁剪梯度
      梯度是一个的形式,指数就是时间步数。
      假设我们把所有模型参数梯度的元素拼接成一个向量 𝑔 ,并设裁剪的阈值是 𝜃 。裁剪后的梯度 min(𝜃 / ‖𝑔‖,1)𝑔,其𝐿2范数不超过 𝜃。

      # 本函数已保存在d2lzh包中方便以后使用
      def grad_clipping(params, theta, ctx): #theta是预设的阈值
      norm = nd.array([0], ctx) #g的L2范数,即所有梯度的平方和
      for param in params:
      norm += (param.grad ** 2).sum()
      norm = norm.sqrt().asscalar() #梯度开根号
      if norm > theta: #即 theta / norm < 1
      for param in params:
      param.grad[:] *= theta / norm #
    6. 困惑度
      用以评价语言模型的好坏
      指对交叉熵损失函数做指数运算后得到的值。特别的情况(如概率为1、0、相等),相当于取倒数了。
      最坏情况下,模型总是把标签类别的概率预测为0,此时困惑度为正无穷;

    7. 定义模型训练函数

      # 本函数已保存在d2lzh包中方便以后使用
      def train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,
      vocab_size, ctx, corpus_indices, idx_to_char,
      char_to_idx, is_random_iter, num_epochs, num_steps,
      lr, clipping_theta, batch_size, pred_period,
      pred_len, prefixes):
      #判断数据采样方法
      if is_random_iter:
      data_iter_fn = d2l.data_iter_random
      else:
      data_iter_fn = d2l.data_iter_consecutive
      
      params = get_params()
      loss = gloss.SoftmaxCrossEntropyLoss() #交叉熵损失函数
      
      for epoch in range(num_epochs):
      if not is_random_iter:  # 如使用相邻采样,在epoch开始时初始化隐藏状态
      state = init_rnn_state(batch_size, num_hiddens, ctx)
      l_sum, n, start = 0.0, 0, time.time() #用于输出训练过程中信息的变量
      #data_iter是个生成器
      data_iter = data_iter_fn(corpus_indices, batch_size, num_steps, ctx)
      for X, Y in data_iter:
      if is_random_iter:  # 如使用随机采样,在每个小批量更新前初始化隐藏状态
      state = init_rnn_state(batch_size, num_hiddens, ctx)
      else:  # 否则需要使用detach函数从计算图分离隐藏状态
      for s in state:
      s.detach() #分离
      with autograd.record(): #梯度记录
      #input是num_steps个形状为(Batch_size,vocab_size)的矩阵
      inputs = to_onehot(X, vocab_size)
      # outputs有num_steps个形状为(batch_size, vocab_size)的矩阵
      (outputs, state) = rnn(inputs, state, params)
      # 拼接之后形状为(num_steps * batch_size, vocab_size)
      outputs = nd.concat(*outputs, dim=0)
      # Y的形状是(batch_size, num_steps),转置后再变成长度为
      # batch * num_steps 的向量,这样跟输出的行一一对应
      y = Y.T.reshape((-1,))
      # 使用交叉熵损失计算平均分类误差, y是标签
      l = loss(outputs, y).mean()
      l.backward() #梯度计算
      grad_clipping(params, clipping_theta, ctx)  # 裁剪梯度
      d2l.sgd(params, lr, 1)  # 因为误差已经取过均值,梯度不用再做平均
      l_sum += l.asscalar() * y.size
      n += y.size
      
      if (epoch + 1) % pred_period == 0:
      print('epoch %d, perplexity %f, time %.2f sec' % (
      epoch + 1, math.exp(l_sum / n), time.time() - start))
      for prefix in prefixes:
      print(' -', predict_rnn(
      prefix, pred_len, rnn, params, init_rnn_state,
      num_hiddens, vocab_size, ctx, idx_to_char, char_to_idx))
    8. 实际运用
      其实就是定义参数,然后传到train_and_predict_rnn这个函数里就可。

      num_epochs, num_steps, batch_size, lr, clipping_theta = 250, 35, 32, 1e2, 1e-2
      pred_period, pred_len, prefixes = 50, 50, ['分开', '不分开']
      train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,
      vocab_size, ctx, corpus_indices, idx_to_char,
      char_to_idx, True, num_epochs, num_steps, lr,
      clipping_theta, batch_size, pred_period, pred_len,
      prefixes)
    • 简洁实现

      运用Gluon
      1.读取数据集
    1. 定义模型
      下面构造一个含单隐藏层、隐藏单元个数为256的循环神经网络层rnn_layer,并对权重做初始化。

      num_hiddens = 256
      rnn_layer = rnn.RNN(num_hiddens)
      rnn_layer.initialize()
      batch_size = 2
      #begin_state返回初始化的隐藏状态列表,有一个形状为(隐藏层个数, 批量大小, 隐藏单元个数)的元素。
      state = rnn_layer.begin_state(batch_size=batch_size)
      state[0].shape
      #大小为(1,批量大小,隐藏单元个数)
      #1的大小是固定的,以后复杂的神经网络就不是1了
      num_steps = 35
      # rnn_layer的输入形状为3个了!
      X = nd.random.uniform(shape=(num_steps, batch_size, vocab_size))
      Y, state_new = rnn_layer(X, state)
      Y.shape, len(state_new), state_new[0].shape
    2. 用Block类来定义一个完整的循环神经网络

      class RNNModel(nn.Block):
      def __init__(self, rnn_layer, vocab_size, **kwargs):
      super(RNNModel, self).__init__(**kwargs)
      self.rnn = rnn_layer
      self.vocab_size = vocab_size
      self.dense = nn.Dense(vocab_size) #定义线性层
      
      def forward(self, inputs, state):
      # 将输入转置成(num_steps, batch_size)后获取one-hot向量表示
      X = nd.one_hot(inputs.T, self.vocab_size)
      Y, state = self.rnn(X, state)
      # 全连接层会首先将Y的形状变成(num_steps * batch_size, num_hiddens),它的输出
      # 形状为(num_steps * batch_size, vocab_size)
      output = self.dense(Y.reshape((-1, Y.shape[-1])))
      return output, state
      
      def begin_state(self, *args, **kwargs):
      return self.rnn.begin_state(*args, **kwargs)
    3. 预测函数

      def predict_rnn_gluon(prefix, num_chars, model, vocab_size, ctx, idx_to_char,
      char_to_idx):
      # 使用model的成员函数来初始化隐藏状态
      state = model.begin_state(batch_size=1, ctx=ctx)
      output = [char_to_idx[prefix[0]]]
      for t in range(num_chars + len(prefix) - 1):
      X = nd.array([output[-1]], ctx=ctx).reshape((1, 1))
      (Y, state) = model(X, state)  # 前向计算不需要传入模型参数
      if t < len(prefix) - 1:
      output.append(char_to_idx[prefix[t + 1]])
      else:
      output.append(int(Y.argmax(axis=1).asscalar()))
      return ''.join([idx_to_char[i] for i in output])
    4. 实际预测

      ctx = d2l.try_gpu()
      model = RNNModel(rnn_layer, vocab_size)
      model.initialize(force_reinit=True, ctx=ctx)
      predict_rnn_gluon('分开', 10, model, vocab_size, ctx, idx_to_char, char_to_idx)
    5. 训练函数

      # 本函数已保存在d2lzh包中方便以后使用
      def train_and_predict_rnn_gluon(model, num_hiddens, vocab_size, ctx,
      corpus_indices, idx_to_char, char_to_idx,
      num_epochs, num_steps, lr, clipping_theta,
      batch_size, pred_period, pred_len, prefixes):
      loss = gloss.SoftmaxCrossEntropyLoss()
      model.initialize(ctx=ctx, force_reinit=True, init=init.Normal(0.01))
      trainer = gluon.Trainer(model.collect_params(), 'sgd',
      {'learning_rate': lr, 'momentum': 0, 'wd': 0})
      
      for epoch in range(num_epochs):
      l_sum, n, start = 0.0, 0, time.time()
      data_iter = d2l.data_iter_consecutive(
      corpus_indices, batch_size, num_steps, ctx)
      state = model.begin_state(batch_size=batch_size, ctx=ctx)
      for X, Y in data_iter:
      for s in state:
      s.detach() #用detach从计算图分离隐藏状态
      with autograd.record():
      (output, state) = model(X, state)
      y = Y.T.reshape((-1,))
      l = loss(output, y).mean() #损失
      l.backward()
      # 梯度裁剪
      params = [p.data() for p in model.collect_params().values()]
      d2l.grad_clipping(params, clipping_theta, ctx)
      trainer.step(1)  # 因为已经误差取过均值,梯度不用再做平均
      l_sum += l.asscalar() * y.size
      n += y.size
      
      if (epoch + 1) % pred_period == 0:
      print('epoch %d, perplexity %f, time %.2f sec' % (
      epoch + 1, math.exp(l_sum / n), time.time() - start))
      for prefix in prefixes:
      print(' -', predict_rnn_gluon(
      prefix, pred_len, model, vocab_size, ctx, idx_to_char,
      char_to_idx))

    调用方法

    ```python
    num_epochs, batch_size, lr, clipping_theta = 250, 32, 1e2, 1e-2
    pred_period, pred_len, prefixes = 50, 50, ['分开', '不分开']
    train_and_predict_rnn_gluon(model, num_hiddens, vocab_size, ctx,
    corpus_indices, idx_to_char, char_to_idx,
    num_epochs, num_steps, lr, clipping_theta,
    batch_size, pred_period, pred_len, prefixes)
    ```
    • 点赞
    • 收藏
    • 分享
    • 文章举报
    RUOLAN_TJ 发布了8 篇原创文章 · 获赞 0 · 访问量 445 私信 关注
    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: 
    相关文章推荐