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

วิธีสร้าง Ragged Tensor จากรายการคำด้วย TensorFlow และ Python

บทนำ

tf.RaggedTensor เหมาะสำหรับข้อมูลขนาดไม่เท่ากัน เช่น จำนวนคำต่อประโยค, จำนวนตัวอักษรต่อคำ ซึ่งแตกต่างจาก dense tensor ที่ต้อง padding

บทความนี้สาธิตการสร้าง RaggedTensor จาก row_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)

print("Get the number of words in the specific sentence")
sentence_num_words = tf.reduce_sum(tf.cast(sentence_char_starts_word, tf.int64), axis=1)

ผลลัพธ์

Get the code point of every character in every word

Get the number of words in the specific sentence

คำอธิบาย

  • from_row_starts(values, row_starts) สร้าง RaggedTensor โดย row_starts คือ index ใน values ที่แต่ละแถว (คำ) เริ่มต้น
  • sentence_char_codepoint.values คือ tensor แบน (flattened) ของ code points ทุกตัวในทุกประโยค
  • word_starts คำนวณจาก script boundaries (ดูบทความก่อนหน้า)
  • sentence_num_words นับจำนวนคำต่อประโยคจาก boolean mask sentence_char_starts_word

ไฟล์งาน

ขั้นตอนนี้มักอยู่ใน pipeline: decode UTF-8 → detect script boundaries → หา word_starts → สร้าง word-level RaggedTensor → ประมวลผลต่อ (เช่น embedding, segmentation)