文本预处理、n-gram语言模型、循环神经网络基础

文本预处理

常见4个步骤:

  1. 读取文本
  2. 分词
  3. 建立字典,将每个词映射到一个唯一的索引
  4. 将文本从词的序列转换为索引的序列,方便输入模型

一、读取文本

import re
def read_data():
	with open('...') as f:
		lines = [re.sub('[^a-z]+',' ',line.strip().lower()) for line in f]
		#使用re包过滤字符,
		#表示与不包含小写字母的字符匹配,并替换为空格 ,去空格和转小写
	return lines

lines = read_data()
print('num of sentences %d'%len(lines))

二、分词

将一个句子分成若干个词token,转换为一个词的序列

def tokenize(sentences,token='word'):
	if token == 'word':
		return [sentence.split(' ') for sentence in sentences]
	elif token == 'char':
		return [list(sentence) for sentence in sentences]
	else:
		print('Unkown token type:'+token)

tokens  =  tokenize(lines)
tokens[0:2]

split函数会切割字符串,按照空格形式,并返回list

三、建立字典

模型是无法处理字符串的,我们需要把它转换为数字,所以先建立字典,在把单词映射到唯一的索引编号。

class Vocab(object):
    def __init__(self, tokens, min_freq=0, use_special_tokens=False):
        counter = count_corpus(tokens)  # : 
        self.token_freqs = list(counter.items())
        self.idx_to_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 += ['', '', '', '']
        else:
            self.unk = 0
            self.idx_to_token += ['']
        self.idx_to_token += [token for token, freq in self.token_freqs
                        if freq >= min_freq and token not in self.idx_to_token]
        self.token_to_idx = dict()
        for idx, token in enumerate(self.idx_to_token):
            self.token_to_idx[token] = idx
def count_corpus(sentences):
    tokens = [tk for st in sentences for tk in st]
    return collections.Counter(tokens)  # 返回一个字典,记录每个词的出现次数

vocab = Vocab(tokens)
print(list(vocab.token_to_idx.items())[0:10])

两个分词工具:

text = "Mr. Chen doesn't agree with my suggestion."
import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
print([token.text for token in doc])
text = "Mr. Chen doesn't agree with my suggestion."
from nltk.tokenize import word_tokenize
from nltk import data
data.path.append('/home/kesci/input/nltk_data3784/nltk_data')
print(word_tokenize(text))

语言模型

我们把一段文本,可以看成一个离散的时间序列,而语言模型的目标就是评估该序列是否合理.
语言模型的参数就是词的概率以及给定前几个词情况下条件概率
词的概率就是该词相对数据集的相对词频:
P ^ ( w 1 ) = n ( w 1 ) n \hat P(w_1) = \frac{n(w_1)}{n} P^(w1)=nn(w1)
同样的,给定w1,w2的条件概率:
P ^ ( w 2 ∣ w 1 ) = n ( w 1 , w 2 ) n ( w 1 ) \hat P(w_2 \mid w_1) = \frac{n(w_1, w_2)}{n(w_1)} P^(w2w1)=n(w1)n(w1,w2)

n元语法

遵循马尔科夫假设,即一个事件只取决于前一个事件相关,
P ( w 1 , w 2 , … , w T ) = ∏ t = 1 T P ( w t ∣ w t − ( n − 1 ) , … , w t − 1 ) . P(w_1, w_2, \ldots, w_T) = \prod_{t=1}^T P(w_t \mid w_{t-(n-1)}, \ldots, w_{t-1}) . P(w1,w2,,wT)=t=1TP(wtwt(n1),,wt1).
所以一元语法(unigram)只与自己有关、二元语法(bigram)与前一个词有关和三元语法(trigram)与前两个词有关.

n不能太小,会不准确,n较大,又会导致计算和要存储大量词频和多词相邻频率。引出n元语法可能有的两个缺陷,一个是参数空间过大,第二个是数据稀疏

读取模型并建立字符索引:

def load_data():   
    with open('...') as f:
        corpus_chars = f.read()
    corpus_chars = corpus_chars.replace('\n', ' ').replace('\r', ' ')
    corpus_chars = corpus_chars[0:10000]
    idx_to_char = list(set(corpus_chars))
    char_to_idx = dict([(char, i) for i, char in enumerate(idx_to_char)])
    vocab_size = len(char_to_idx)
    corpus_indices = [char_to_idx[char] for char in corpus_chars]
    return corpus_indices, char_to_idx, idx_to_char, vocab_size
时序数据采样

我们知道每次训练中,都会随机读取小批量样本和标签,而时序数据有点不同,一个样本通常包含连续字符,例如步长为3,就是X=”情人节“,而该样本标签序列为Y =“人节快”.

序列长度为T,时间步数为n,一共T-n个样本,因为样本的大量重复,所以采用高效的采样方式,随机采样和相邻采样.

随机采样

每次从数据里随机采样一个小批量。
batch_size为每个小批量的样本数目
num_steps为每个样本的时间步数
相邻的两个随机小批量在原始序列上的位置不一定相毗邻

import torch
import random
def data_iter_random(corpus_indices, batch_size, num_steps, device=None):
    # 减1是因为对于长度为n的序列,X最多只有包含其中的前n - 1个字符
    num_examples = (len(corpus_indices) - 1) // num_steps  # 下取整,得到不重叠情况下的样本个数
    example_indices = [i * num_steps for i in range(num_examples)]  # 每个样本的第一个字符在corpus_indices中的下标
    random.shuffle(example_indices)

    def _data(i):
        # 返回从i开始的长为num_steps的序列
        return corpus_indices[i: i + num_steps]
    if device is None:
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    
    for i in range(0, num_examples, batch_size):
        # 每次选出batch_size个随机样本
        batch_indices = example_indices[i: i + batch_size]  # 当前batch的各个样本的首字符的下标
        X = [_data(j) for j in batch_indices]
        Y = [_data(j + 1) for j in batch_indices]
        yield torch.tensor(X, device=device), torch.tensor(Y, device=device)

以下为测试代码:

my_seq = list(range(30))
for X, Y in data_iter_random(my_seq, batch_size=2, num_steps=6):
    print('X: ', X, '\nY:', Y, '\n')

X:  tensor([[ 6,  7,  8,  9, 10, 11],
        [12, 13, 14, 15, 16, 17]]) 
Y: tensor([[ 7,  8,  9, 10, 11, 12],
        [13, 14, 15, 16, 17, 18]]) 

X:  tensor([[ 0,  1,  2,  3,  4,  5],
        [18, 19, 20, 21, 22, 23]]) 
Y: tensor([[ 1,  2,  3,  4,  5,  6],
        [19, 20, 21, 22, 23, 24]]) 
相邻采样

相邻的两个随机小批量在原始序列上的位置相毗邻

def data_iter_consecutive(corpus_indices, batch_size, num_steps, device=None):
    if device is None:
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    corpus_len = len(corpus_indices) // batch_size * batch_size  # 保留下来的序列的长度
    corpus_indices = corpus_indices[: corpus_len]  # 仅保留前corpus_len个字符
    indices = torch.tensor(corpus_indices, device=device)
    indices = indices.view(batch_size, -1)  # resize成(batch_size, )
    batch_num = (indices.shape[1] - 1) // num_steps
    for i in range(batch_num):
        i = i * num_steps
        X = indices[:, i: i + num_steps]
        Y = indices[:, i + 1: i + num_steps + 1]
        yield X, Y

测试代码:

for X, Y in data_iter_consecutive(my_seq, batch_size=2, num_steps=6):
    print('X: ', X, '\nY:', Y, '\n')

X:  tensor([[ 0,  1,  2,  3,  4,  5],
        [15, 16, 17, 18, 19, 20]]) 
Y: tensor([[ 1,  2,  3,  4,  5,  6],
        [16, 17, 18, 19, 20, 21]]) 

X:  tensor([[ 6,  7,  8,  9, 10, 11],
        [21, 22, 23, 24, 25, 26]]) 
Y: tensor([[ 7,  8,  9, 10, 11, 12],
        [22, 23, 24, 25, 26, 27]]) 

在这里插入图片描述

循环神经网络基础

除了n-gram,我们也可以基于RNN实现语言模型,目标是基于当前输入和过去的输入序列,预测序列的下一个字符.
RNN引入一个隐藏变量H, H t H_t Ht为t时刻的状态, H t H_t Ht的计算是基于 X t X_t Xt H t − 1 H_{t-1} Ht1 H t H_t Ht记录了到当前字符为止的序列信息,然后利用它来预测下一个字符

RNN的结构

假设 X t ∈ R n × d \boldsymbol{X}_t \in \mathbb{R}^{n \times d} XtRn×d是时间步 t t t的小批量输入, H t ∈ R n × h \boldsymbol{H}_t \in \mathbb{R}^{n \times h} HtRn×h是该时间步的隐藏变量,则:

H t = ϕ ( X t W x h + H t − 1 W h h + b h ) . \boldsymbol{H}_t = \phi(\boldsymbol{X}_t \boldsymbol{W}_{xh} + \boldsymbol{H}_{t-1} \boldsymbol{W}_{hh} + \boldsymbol{b}_h). Ht=ϕ(XtWxh+Ht1Whh+bh).
其中, W x h ∈ R d × h \boldsymbol{W}_{xh} \in \mathbb{R}^{d \times h} WxhRd×h W h h ∈ R h × h \boldsymbol{W}_{hh} \in \mathbb{R}^{h \times h} WhhRh×h b h ∈ R 1 × h \boldsymbol{b}_{h} \in \mathbb{R}^{1 \times h} bhR1×h ϕ \phi ϕ函数是非线性激活函数。在时间步 t t t,输出层的输出为:

O t = H t W h q + b q . \boldsymbol{O}_t = \boldsymbol{H}_t \boldsymbol{W}_{hq} + \boldsymbol{b}_q. Ot=HtWhq+bq.

其中 W h q ∈ R h × q \boldsymbol{W}_{hq} \in \mathbb{R}^{h \times q} WhqRh×q b q ∈ R 1 × q \boldsymbol{b}_q \in \mathbb{R}^{1 \times q} bqR1×q

W_xh: 状态-输入权重
W_hh: 状态-状态权重
W_hq: 状态-输出权重
b_h: 隐藏层的偏置
b_q: 输出层的偏置

裁剪梯度

是一种应对梯度爆炸的方法,假设我们把所有模型参数的梯度拼接成一个向量 g \boldsymbol{g} g,并设裁剪的阈值是 θ \theta θ。裁剪后的梯度

min ⁡ ( θ ∥ g ∥ , 1 ) g \min\left(\frac{\theta}{\|\boldsymbol{g}\|}, 1\right)\boldsymbol{g} min(gθ,1)g

L 2 L_2 L2范数不超过 θ \theta θ

困惑度

困惑度是用来评价语言模型好坏的,困惑度是对交叉熵损失函数做指数运算后得到的值

  • 最佳情况下,模型总是把标签类别的概率预测为1,此时困惑度为1;
  • 最坏情况下,模型总是把标签类别的概率预测为0,此时困惑度为正无穷;
  • 基线情况下,模型总是预测所有类别的概率都相同,此时困惑度为类别个数。
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值