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

วิธีเข้ารหัสสตริงหลายสตริงที่มีความยาวเท่ากันด้วย TensorFlow และ Python

บทนำ

tf.strings.unicode_encode เข้ารหัส code points → string รองรับ input 3 รูปแบบ:

  1. tf.Tensor (dense): เมื่อทุกสตริงมีจำนวน code points เท่ากัน (shape: [batch, seq_len])
  2. tf.RaggedTensor: เมื่อความยาวต่างกัน (ragged dimension)
  3. Sparse/Padded Tensor: แปลงเป็น RaggedTensor ก่อนด้วย from_sparse หรือ from_tensor(padding=...)

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

print("When encoding multiple strings of same lengths, tf.Tensor is used as input")
tf.strings.unicode_encode([[99, 97, 116], [100, 111, 103], [99, 111, 119]], output_encoding='UTF-8')

print("When encoding multiple strings with varying length, a tf.RaggedTensor should be used as input:")
tf.strings.unicode_encode(batch_chars_ragged, output_encoding='UTF-8')

print("If there is a tensor with multiple strings in padded/sparse format, convert it to a tf.RaggedTensor before calling unicode_encode")
tf.strings.unicode_encode(
    tf.RaggedTensor.from_sparse(batch_chars_sparse),
    output_encoding='UTF-8')
tf.strings.unicode_encode(
    tf.RaggedTensor.from_tensor(batch_chars_padded, padding=-1),
    output_encoding='UTF-8')

ผลลัพธ์

When encoding multiple strings of same lengths, tf.Tensor is used as input
When encoding multiple strings with varying length, a tf.RaggedTensor should be used as input:
If there is a tensor with multiple strings in padded/sparse format, convert it to a tf.RaggedTensor before calling unicode_encode

คำอธิบาย

  • Dense tensor: ใช้ได้ก็ต่อเมื่อทุกแถวยาวเท่ากัน (fixed-length)
  • RaggedTensor: ยืดหยุ่น ไม่ต้อง padding ความจำน้อยกว่า
  • SparseTensor: ใช้ RaggedTensor.from_sparse
  • Padded tensor: ใช้ RaggedTensor.from_tensor(padding=PAD_VALUE) โดยระบุค่า padding (เช่น -1)

Best Practice

ใน NLP pipelines ปกติ decode → process → encode ควรคง RaggedTensor ตลอดจนขั้นสุดท้าย เพื่อหลีกเลี่ยง overhead ของ padding