下午琢磨subword,研究手边的论文,看到一个BPE(Byte Pair
Encoding,双字节编码)觉得不错,2016年应用于机器翻译,解决 集外词(OOV)和罕见词(Rare
word)问题。
论文题目《Neural Machine Translation of Rare Words with Subword
Units》
---发表于ACL2016
论文介绍可以参考机器之心的推送【http://www.sohu.com/a/115373230_465975】
论文中有python代码小例子:如下
====================================================
import re, collections
def get_stats(vocab):
pairs = collections.defaultdict(int)
for word, freq in vocab.items():
symbols = word.split()
print(symbols)
print("len(symbols)
--- ",len(symbols))
for i in range(len(symbols)-1):
pairs[symbols[i],symbols[i+1]] += freq
return pairs
def merge_vocab(pair, v_in):
v_out = {}
bigram = re.escape(' '.join(pair))
print("bigram
",bigram)
p =
re.compile(r'(?
for word in v_in:
w_out = p.sub(''.join(pair), word)
print("w_out
",w_out)
v_out[w_out] = v_in[word]
return v_out
vocab = {'l o w ' : 5, 'l o w e r ' : 2,
'n e w e s t ':6, 'w i d e s t ':3}
num_merges = 10
for i in range(num_merges):
print("=#####################################=== ")
pairs = get_stats(vocab)
print("===========11111=======
")
print(pairs)
#print("===========11111======= ")
best = max(pairs,
key=pairs.get)
print("===========2222=======
")
print("pairs.get
",pairs.get)
print("best ",best)
#raise SystemExit
vocab = merge_vocab(best,
vocab)
print("vocab ",vocab)
====================================================
截个自己调试的图,好看一点
http://s4/mw690/004cTbxUzy7hQ3mBo8bb3&690Pair Encoding,双字节编码)---2018年02月01日" TITLE="BPE(Byte Pair Encoding,双字节编码)---2018年02月01日" />
然后 最后,将词汇表由之前的
vocab = {'l o w ' : 5, 'l o w e r ' : 2,
'n e w e s t ':6, 'w i d e s
t ':3}
更新为如下:
{'newest': 6, 'low': 5,
'w i d est': 3, 'low e r ':
2})
准备后续拿过来做实验。。。哎。。。不开心~~~
加载中,请稍候......