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

วิธีรวม Word Code Points ของ Ragged Tensor กลับเป็นประโยคด้วย TensorFlow

บทนำ

ในการประมวลผลภาษาธรรมชาติ (NLP) การ Segmentation (การแบ่งคำ) เป็นขั้นตอนสำคัญ โดยเฉพาะภาษาที่ไม่มี space คั่นคำ เช่น ไทย จีน ญี่ปุ่น หรือภาษาที่มีคำประสมยาว เช่น เยอรมัน

TensorFlow มีเครื่องมือ Unicode และ RaggedTensor สำหรับจัดการข้อความระดับ code point ได้อย่างมีประสิทธิภาพ

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

print("Segment the word code points back to sentences")
print("Check if code point for a character in a word is present in the sentence")
sentence_word_char_codepoint = tf.RaggedTensor.from_row_lengths(
    values=word_char_codepoint,
    row_lengths=sentence_num_words)
print(sentence_word_char_codepoint)

print("Encoding it back to UTF-8")
tf.strings.unicode_encode(sentence_word_char_codepoint, 'UTF-8').to_list()

ผลลัพธ์

Segment the word code points back to sentences
Check if code point for a character in a word is present in the sentence

Encoding it back to UTF-8
[[b'Hello', b', ', b'there', b'.'], [b'\xe4\xb8\x96\xe7\x95\x8c', b'\xe3\x81\x93\xe3\x82\x93\xe3\x81\xab\xe3\x81\xa1\xe3\x81\xaf']]

คำอธิบาย

  • tf.RaggedTensor.from_row_lengths ใช้รวม code points ของคำ (word_char_codepoint) กลับเป็นประโยค โดยระบุจำนวนคำต่อประโยค (sentence_num_words)
  • โครงสร้างเป็น 3 ระดับ: [batch, sentence, word, char_codepoint]
  • tf.strings.unicode_encode(..., 'UTF-8') แปลง code points กลับเป็น byte string UTF-8
  • ตัวอย่าง: "Hello, there." (อังกฤษ) และ "世界こんにちは" (จีน+ญี่ปุ่น)

ประโยชน์

เทคนิคนี้ใช้ใน pipeline NLP ที่ต้อง tokenize แล้วประมวลผลต่อระดับคำ (word-level) แล้วค่อยรวมกลับเป็นประโยคสำหรับ output หรือ evaluation