TensorFlow TextVectorization layer chuyển câu hỏi StackOverflow thành tensor số cho mô hình deep learning.
Quy trình
- Định nghĩa
binary_vectorize_layer(mode='binary', vocab=10000). - Định nghĩa
int_vectorize_layer(mode='int', vocab=10000, sequence_length=250). - Hàm
vectorize_textmở rộng chiều và áp dụng layer. - Lấy batch mẫu, in ra dạng binary và int.
Ví dụ code
def int_vectorize_text(text, label):
text = tf.expand_dims(text, -1)
return int_vectorize_layer(text), label
text_batch, label_batch = next(iter(raw_train_ds))
first_q, first_l = text_batch[0], label_batch[0]
print("Question:", first_q)
print("Label:", first_l)
print("Binary vectorized:", binary_vectorize_text(first_q, first_l)[0])
print("Int vectorized:", int_vectorize_text(first_q, first_l)[0])
Kết quả mẫu
Question: b'"function expected error in blank for dynamically created check box..."'
Label: tf.Tensor(2, shape=(), dtype=int32)
Binary vectorized: tf.Tensor([[1. 1. 1. ... 0. 0. 0.]], shape=(1, 10000), dtype=float32)
Int vectorized: tf.Tensor([[37 464 65 7 16 12 879 ... 0 0 0]], shape=(1, 250), dtype=int64)
Giải thích
- Binary mode: vector thưa (sparse) chỉ dấu hiện diện từ.
- Int mode: chuỗi index từ vựng, giữ thứ tự, độ dài cố định 250.
get_vocabulary()tra từ theo index.
Nguồn: TensorFlow Text Tutorial