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

วิธีหา Code Point ของทุกคำในประโยคด้วย TensorFlow และ Python

บทนำ

การหา word boundaries (ขอบเขตคำ) ในข้อความ Unicode ที่ผสมภาษา สามารถทำได้โดยใช้ script identifiers (รหัสสคริปต์) ของแต่ละตัวอักษร

หลักการ: เริ่มคำใหม่ที่ (1) ตัวแรกของประโยค (2) ตัวอักษรที่มี script ต่างจากตัวก่อนหน้า

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

print("Check if sentence is the start of the word")
sentence_char_starts_word = tf.concat(
    [tf.fill([sentence_char_script.nrows(), 1], True),
     tf.not_equal(sentence_char_script[:, 1:], sentence_char_script[:, :-1])],
    axis=1)

print("Check if index of character starts from specific index of word in flattened list of characters from all sentences")
word_starts = tf.squeeze(tf.where(sentence_char_starts_word.values), axis=1)
print(word_starts)

print("Get the code point of every character in every word")
word_char_codepoint = tf.RaggedTensor.from_row_starts(
    values=sentence_char_codepoint.values,
    row_starts=word_starts)
print(word_char_codepoint)

ผลลัพธ์

Check if sentence is the start of the word
Check if index of character starts from specific index of word in flattened list of characters from all sentences
tf.Tensor([ 0  5  7 12 13 15], shape=(6,), dtype=int64)
Get the code point of every character in every word

คำอธิบาย

  1. sentence_char_script: รหัส script ของแต่ละตัวอักษร (จาก tf.strings.unicode_script)
  2. สร้าง boolean mask sentence_char_starts_word: True ที่ตัวแรกของประโยค และที่ script เปลี่ยน
  3. tf.where(...).values หา index ของ True ทั้งหมด → word_starts
  4. ใช้ from_row_starts ตัด code points ตาม word_starts ได้ word-level RaggedTensor

ข้อจำกัด

วิธี "script change" นี้เป็น heuristic แบบ rough segmentation ใช้ได้ดีกับภาษาที่ไม่มี space คั่น แต่ไม่ครอบคลุมทุกกรณี (เช่น คำประสมในไทย) สำหรับ production ควรใช้ tokenizer เฉพาะภาษา ( مثل PyThaiNLP, MeCab, jieba)