Torchtext构建Vocab词表
torchtext.vocab 1 from torchtext.vocab import vocab 1. 定义词汇表 基于词元的频率统计表,OrderedDict 对象 1 2 3 4 vocab(ordered_dict = , #一个 OrderedDict 对象,包含词汇和它们的频率。 min_freq = 1, #指定词汇表中词出现的最小频率。 specials = None, #一个列表,包含特殊标记(如 <unk>, <pad>, <bos>, <eos> 等)。 special_first = True) #一个布尔值,决定特殊标记是否在词汇表的开头。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 from collections import Counter, OrderedDict counter = Counter(["a", "a", "b", "b", "b"]) counter # Counter({'b': 3, 'a': 2}) sorted_by_freq_tuples = sorted(counter.items(), key=lambda x: x[1], reverse=True) sorted_by_freq_tuples # [('b', 3), ('a', 2)] ordered_dict = OrderedDict(sorted_by_freq_tuples) # OrderedDict([('b', 3), ('a', 2)]) v1 = vocab(ordered_dict) # Vocab() 直接基于可迭代对象 1 2 3 4 5 6 7 build_vocab_from_iterator( iterator = , # Iterator used to build Vocab. Must yield list or iterator of tokens. min_freq = , specials = , special_first = , max_tokens =None #最多引入多少个词元 ) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 from torchtext.vocab import build_vocab_from_iterator # 定义一个简单的迭代器 # yield关键字,用于定义生成器函数。惰性取值:按需生成值,而不是一次性生成所有值,适合处理大数据集。 def yield_tokens(data_iter): for text in data_iter: yield text.split() # 示例数据 data = ["this is a sentence", "this is another sentence"] # 构建词汇表 v2 = build_vocab_from_iterator(yield_tokens(data), min_freq=1, specials=['<unk>', '<pad>'], special_first=True) ### 直接使用token list作为输入 token_lists = [ ["this", "is", "a", "sentence"], ["this", "is", "another", "sentence"] ] # 构建词汇表 v3 = build_vocab_from_iterator(token_lists) 2. 查询词汇表 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 # 1. 查看词元的索引 v1['a'], v1['b'] # 2. 设置当查询不在词汇表的新词元时,返回的索引 v2.set_default_index(v2[unk_token]) v2['sss'] # 3. 查询索引对应的词元 v2.get_itos()[:3] # v2['out of vocab'] is v2[unk_token] v2.get_stoi() # {'a': 5, # 'this': 4, # 'another': 6, # 'sentence': 3, # 'is': 2, # '<pad>': 1, # '<unk>': 0}