博客内容将首发在微信公众号"跟我一起读论文啦啦",上面会定期分享机器学习、深度学习、数据挖掘、自然语言处理等高质量论文,欢迎关注!

本次总结的是一篇16年的关于NLP中分词操作的论文,论文链接Subword,参考的实现代码subword-nmt,许多论文方法(例如BERT等)都将该方法应用到分词处理上,相对于word-level和character-level,该方法取得了不错的效果。
动机和创新点
- 机器翻译中,通常使用固定大小的词表,而在实际翻译场景中,应当是open-vocabulary。这就使得翻译数据集中的稀有词变得困难,不能生成词表中没出现的词。这就是OOV问题。
- 对于word-level 翻译模型,通常使用back-off dictionary(比如将source和target两两对应起来,使用OOV来表示,这样在翻译结果中出现OOV时,就用source所对应的target来代替)来处理OOV词汇。但是这样做是建立在source target中的词总是能一一对应的前提下,因为语言之间的形态合成程度不同,这种假设常常不成立;其次word-level 翻译模型不能生成模型没见过的词(不在词表中),对于这种情况,有论文提出直接从copy unknown 词到target words中,但是这种处理策略也仅仅限于一些实体名称类的词汇;同时为了节省计算时间和资源,词表大小通常被限制在30k-50k之间,所以词表空间是比较昂贵的,如果一些词义类似的词放到词表中,例如like,liked,liking等形态上类似的词均放到词表中,直观上感觉有些浪费。
- 在实际翻译时,并不一定都是以word为基本单位进行翻译,可通过比单词更小的单位(subword)进行翻译,例如名称类的词(通过subword复制或音译)、复合词(形态上类似的词,前缀后缀相同,如run、runer、running等,可通过合成(run与er合成等)翻译)、同源词和外来词(通过subword语音和形态转换),以上称为透明翻译。直观上来看,有时相对于以一个word作为基本单位整体去翻译,这种通过subword来翻译则显得更有效率和意义。论文中提到,从德语数据集中分析,在100个稀有词(不在出现最频繁的5000个词中)中,大多数的词可以通过更小的subword units进行翻译。
- 那么,如何将word切分成合适的subword呢?论文中提出了采用Byte pair encoding(BPE)压缩算法,首先以字符划分,然后再合并。也就是不断的以出现频次最高的2-gram进行合并操做,直到打到词表大小为止。这种以频次合并是比较符合常识的,例如像’er’,'ing,'ed’这样比较有意义的后缀,'e’和’r’同时出现的频次应该比较多。“ing”和“ed”类似道理。
- 将稀有词划分成subword,能比较好的处理oov问题。例如训练集中大量出现“runner”和“thinking”,那按word-level词频来说,word-level词表中应该包含这两个词,此时词“running”只出现一次,则该词很有可能是oov,但是如果以subword切词,则subword词表中应该含有“run”,”er”,”think”,”ing”,那么对于”running”,其subword切词后为“run”,”ing”均在词表中。
- 通过对稀有词进行适当的切分,得到subword units,机器翻译模型能更好的处理透明翻译,并且能生成一些unseen words。
- 机器翻译模型通常都会用到注意力机制,在word-level模型中,模型每次只能计算在word级别上的注意力,我们希望模型可以在每一步学习中将注意力放在不同的subword上,显然这样更有意义和效率。
BPE
一个很简单的压缩算法。具体来说,分为以下几步:
- 将原始数据集划分成单词集合,再将每个单词划分成字符集,对于每个单词最后一个字符后面加上’-’(标记单词边界,以后用于字符恢复成单词),这样就得到了一个大的字符集合。
- 统计上面的得到的字符集合,统计每个单词内 2-gram字符出现频次,得到频次最高的2-gram字符,例如(‘A’,‘B’)连续出现的频率最高,则以“AB”替换所有单词内出现的(‘A‘,‘B’),然后将该新词添加到词表中。这里注意:该新词以后可以作为一个整体与单词内其他字符合并;替换或合并不跨单词边界。
- 对步骤2循环进行多次,直到达到就得到我们预设的词表大小。最终的vocab_size = init_size(这里为0)+ merge_operation_count, merge_operation_count是模型唯一的超参数。
上图中,实际上将er这样常见且很有意义的后缀作为一个subword放入到词表中,对模型理解语言和节省词表空间、以及OOV问题很有帮助。
实现代码
这篇论文所提方法很简单,但是代码具体实现可以了解下,挺有趣的。这里参考的代码nmt-subword。代码中主要有以下两个重要文件代码。依次来看看。
learn_bpe.py
- 在原始数据集上,统计每个word出现的频率,然后得到每个单词的字符序列(末尾加’</w>'标记单词边界),和其出现频率,组成字典,然后按照频率进行倒排序,得到sorted_vocab。
vocab = get_vocabulary(infile, is_dict)
vocab = dict([(tuple(x[:-1])+(x[-1]+'</w>',) ,y) for (x,y) in vocab.items()])
sorted_vocab = sorted(vocab.items(), key=lambda x: x[1], reverse=True)
- 统计每个单词内2-gram出现的频率
def get_pair_statistics(vocab):
"""Count frequency of all symbol pairs, and create index"""
# data structure of pair frequencies
stats = defaultdict(int)
#index from pairs to words
indices = defaultdict(lambda: defaultdict(int))
for i, (word, freq) in enumerate(vocab):
prev_char = word[0]
for char in word[1:]:
stats[prev_char, char] += freq
indices[prev_char, char][i] += 1
prev_char = char
return stats, indices
- 在预设的合并次数内,不断的合并出现频次最高的2-gram词,同时将得到的新词加入到词表中,同时更新与新词左右两边相连的2-gram频次。直到出现的最高频次低于我们预设min_frequency。
for i in range(num_symbols):
if stats:
most_frequent = max(stats, key=lambda x: (stats[x], x)) ## 统计出现的最高频次的2-gram
# we probably missed the best pair because of pruning; go back to full statistics
if not stats or (i and stats[most_frequent] < threshold):
prune_stats(stats, big_stats, threshold)
stats = copy.deepcopy(big_stats)
most_frequent = max(stats, key=lambda x: (stats[x], x))
# threshold is inspired by Zipfian assumption, but should only affect speed
threshold = stats[most_frequent] * i/(i+10000.0)
prune_stats(stats, big_stats, threshold)
if stats[most_frequent] < min_frequency:
sys.stderr.write('no pair has frequency >= {0}. Stopping\n'.format(min_frequency))
break
if verbose:
sys.stderr.write('pair {0}: {1} {2} -> {1}{2} (frequency {3})\n'.format(i, most_frequent[0], most_frequent[1], stats[most_frequent]))
outfile.write('{0} {1}\n'.format(*most_frequent)) ## 将出现频次最高的2-gram存入到词表中
changes = replace_pair(most_frequent, sorted_vocab, indices) ## 合并和替换出现频次最高的2-gram
update_pair_statistics(most_frequent, changes, stats, indices) ## 更新与合并后新词左右两边相连的2-gram频次
stats[most_frequent] = 0
这样就得到了2-gram词频表 BPE_codes。
apply_bpe.py
在learn_bpe.py中,按照bpe算法得到了数据集的BPE_codes,那么将数据喂给模型之前,我们需要将输入数据按照bpe_codes进行编码,通俗来说就是按照BPE_codes里面的分词规则对输入数据进行分词罢了。
def segment_tokens(self, tokens):
"""segment a sequence of tokens with BPE encoding"""
output = []
for word in tokens:
# eliminate double spaces
if not word:
continue
new_word = [out for segment in self._isolate_glossaries(word)
for out in encode( ## 下面会有encode方法介绍
segment, ## 需要进行编码的序列
self.bpe_codes, ## learn_bpe得到的编码,进行了字典处理,第一个为pair 元祖,第一个为对应的索引
self.bpe_codes_reverse, ## (pair[0] + pair[1], pair)
self.vocab,
self.separator,
self.version,
self.cache,
self.glossaries)] ## 已有的一些词汇表,如城市名称,国家名称等,这些词不能再切分,并且要和其他词split开
for item in new_word[:-1]:
output.append(item + self.separator)
output.append(new_word[-1])
return output
再来看看encode方法,就是将序列内的2-ngram按照bpe_codes不断的合并替换。如果最终pair长度为1即没有合并的可能或者最大的pair也不再bpe_codes中,则停止循环。
def encode(orig, bpe_codes, bpe_codes_reverse, vocab, separator, version, cache, glossaries=None):
"""Encode word based on list of BPE merge operations, which are applied consecutively
"""
if orig in cache:
return cache[orig]
if re.match('^({})$'.format('|'.join(glossaries)), orig):
cache[orig] = (orig,)
return (orig,)
if version == (0, 1):
word = tuple(orig) + ('</w>',)
elif version == (0, 2): # more consistent handling of word-final segments
word = tuple(orig[:-1]) + ( orig[-1] + '</w>',)
else:
raise NotImplementedError
pairs = get_pairs(word)
if not pairs:
return orig
while True:
bigram = min(pairs, key = lambda pair: bpe_codes.get(pair, float('inf')))
if bigram not in bpe_codes:
break
first, second = bigram
new_word = []
i = 0
while i < len(word):
try:
j = word.index(first, i)
new_word.extend(word[i:j])
i = j
except:
new_word.extend(word[i:])
break
if word[i] == first and i < len(word)-1 and word[i+1] == second:
new_word.append(first+second)
i += 2
else:
new_word.append(word[i])
i += 1
new_word = tuple(new_word)
word = new_word
if len(word) == 1:
break
else:
pairs = get_pairs(word)
# don't print end-of-word symbols
if word[-1] == '</w>':
word = word[:-1]
elif word[-1].endswith('</w>'):
word = word[:-1] + (word[-1].replace('</w>',''),)
if vocab: ## 这里的vocab是以一定阈值,统计得到的词表,过滤掉了低频词,以减少低词频影响。
## 论文中讲到低频词可能是噪声
## 这里结合过滤低频词后的词汇表。
##因为过滤掉低词频,可能会出现oov问题,如出现oov问题,则将原词切分为更小的词。
## 更小的词,就有可能在subword词表中。
word = check_vocab_and_split(word, bpe_codes_reverse, vocab, separator)
cache[orig] = word
return word
这样就完成了对输入数据的subword分词。
个人总结
- 论文方法比较简单,在流程上输入数据预处理阶段
- 相对于word-level,subword更有意义和效率
- 这种subword方法可能对中文不太奏效,因为中文没有那种后缀之类的形式。