Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีใช้ Text Vectorization บนชุดข้อมูล StackOverflow ด้วย TensorFlow ใน Python

บทนำ

TextVectorization layer ใน TensorFlow/Keras ใช้แปลงข้อความเป็นตัวเลข (Vectorize) เพื่อป้อนเข้า Neural Network

การติดตั้ง

pip install tensorflow

ตัวอย่างโค้ด

# ดูคำศัพท์ (vocabulary) ตัวอย่าง
print("1234 ---> ", int_vectorize_layer.get_vocabulary()[1289])
print("321 ---> ", int_vectorize_layer.get_vocabulary()[313])
print("Vocabulary size is : {}".format(len(int_vectorize_layer.get_vocabulary())))

# ใช้ vectorization layer กับ dataset
binary_train_ds = raw_train_ds.map(binary_vectorize_text)
binary_val_ds = raw_val_ds.map(binary_vectorize_text)
binary_test_ds = raw_test_ds.map(binary_vectorize_text)
int_train_ds = raw_train_ds.map(int_vectorize_text)
int_val_ds = raw_val_ds.map(int_vectorize_text)
int_test_ds = raw_test_ds.map(int_vectorize_text)

ผลลัพธ์

1234 ---> substring
321 ---> 20
Vocabulary size is : 10000
The text vectorization is applied to the training dataset
The text vectorization is applied to the validation dataset
The text vectorization is applied to the test dataset

คำอธิบาย

  • Binary mode: คืนค่า array บ่งบอกว่ามี token นั้นหรือไม่ (Multi-hot)

  • Int mode: แทน token ด้วย integer index (เก็บลำดับ)

  • ใช้ map บน tf.data.Dataset เพื่อแปลงข้อมูล