transformer中 數據預處理代碼理解


今天師兄將transformer中的數據預處理部分講了一下。

數據准備: train.en train.cn  一個英文的語料,一個中文的語料 語料中是一些一行行的語句

目標:將語料中的詞抽取出來,放在一個詞表里。詞表里是序號+詞 其次,將train中的語句形成數字序列  比如:today在詞表中的id是1 is 在詞表中的id是4 good的id是5

                                                  today is good --->145  

details:

#step1:創建10個文件(train) /dev (1個文件)
1.
tf.logging.info('create 10 train file name')
suffix = '-train'
train_paths = self.filepaths(data_dir, self.num_shards, suffix)
suffix = '-dev'
dev_paths = self.filepaths(data_dir, self.num_dev_shards, suffix)
10個文件的作用在於:避免產生的語句序列過多放於一個文件夾中運行時時間慢長,比如產生12萬句子,平分到10個文件夾中
#step2: 對訓練文件中單詞統計詞頻信息,抽取前size大小的詞作為詞表(3特殊符號)
with tf.gfile.GFile(filepaths, mode='r') as source_file:
for line in source_file:
yield line #讀取訓練文件,返回每一行


tf.logging.info('step1: count word number dict')
token_counts = defaultdict(int) #將詞表存於詞典中,以K,V的形式存放
for item in generate(): #item為返回的每一行
words = native_to_unicode(item).strip().split()#此作用就是將每一行的詞以空格來split,獲取每個詞
for tok in words: #記錄詞出現的次數-詞頻
token_counts[tok] += 1
 
#抽取target_size的大小,形成詞表
self._alphabet = chain(six.iterkeys(token_counts), [native_to_unicode(t) for t in RESERVED_TOKENS])
new_subtoken_strings = []
#這一步是計算RESERVED_TOKENS = [PAD, EOS, UNK] 三個特殊字符在token_counts出現的次數,一般都是0
#PAD--補位 EOS--結束符 UNK---不在所選取的30000個單詞里面
new_subtoken_strings.extend((token_counts.get(a, 0), a) for a in self._alphabet)
new_subtoken_strings.sort(reverse=True)
new_subtoken_strings = [subtoken for _, subtoken in new_subtoken_strings]
new_subtoken_strings = new_subtoken_strings[:target_size]#抽取size的詞
new_subtoken_strings = RESERVED_TOKENS + new_subtoken_strings
self._subtoken_string_to_id = {s: i for i, s in enumerate(new_subtoken_strings) if s}#添加id
 
#step3: 根據形成的詞表,對訓練文件中每句話轉為ID序列
#轉成ID序列
tokens = native_to_unicode(raw_text).strip().split()
ret=[]
for tok in tokens:
if tok in self._subtoken_string_to_id:
ret.extend([self._subtoken_string_to_id[tok]])
else:
ret.extend([UNK_ID])
#調用上面的encode,轉成序列函數,來表示語句序列
source_ints = source_vocab.encode(source.strip()) + eos_list
target_ints = target_vocab.encode(target.strip()) + eos_list
yield {"inputs": source_ints, "targets": target_ints}
source, target = source_file.readline(), target_file.readline()
#step4:將ID序列保存到10個不同文件中,並shuffle文件
for case in generator:generator是第三步的函數
if counter > 0 and counter % 100000 == 0: counter是第幾句話
tf.logging.info("Generating case %d." % counter)
counter += 1
features = {}
for (k, v) in six.iteritems(case):
if isinstance(v[0], six.integer_types):
features[k] = tf.train.Feature(int64_list = tf.train.Int64List(value=v))
sequence_example = tf.train.Example(features=tf.train.Features(feature=features))
writers[shard].write(sequence_example.SerializeToString())
shard = (shard + 1) % num_shards
-------今天才發現博客可以插入代碼------------好吧----------好丑的排版--------------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM