Bước quan trọng trong pipeline NLP là ánh xạ từ token (chuỗi ký tự) sang chỉ số số nguyên. TensorFlow cung cấp tf.lookup.StaticVocabularyTable để thực hiện việc này hiệu quả.
Xây dựng bảng tra cứu từ vựng
keys = vocab
values = range(2, len(vocab) + 2) # 0: padding, 1: OOV
print("Ánh xạ token sang số nguyên")
init = tf.lookup.KeyValueTensorInitializer(
keys, values, key_dtype=tf.string, value_dtype=tf.int64)
num_oov_buckets = 1
vocab_table = tf.lookup.StaticVocabularyTable(init, num_oov_buckets)
print("Định nghĩa hàm chuẩn hóa, tách token và vector hóa")
def preprocess_text(text, label):
standardized = tf_text.case_fold_utf8(text)
tokenized = tokenizer.tokenize(standardized)
vectorized = vocab_table.lookup(tokenized)
return vectorized, label
Kết quả
Ánh xạ token sang số nguyên Định nghĩa hàm chuẩn hóa, tách token và vector hóa dataset sử dụng tokenizer và lookup table
Giải thích
- Tập từ vựng (
vocab) được dùng tạoStaticVocabularyTable. - Token được ánh xạ vào khoảng
[2, vocab_size + 2]. - Số
0dành cho padding, số1dành cho token ngoài từ vựng (OOV - Out Of Vocabulary). - Hàm
preprocess_textkết hợp: lowercase → tokenize → lookup vector hóa.