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

วิธีดำเนินการ Unicode Operations ใน TensorFlow ด้วย Python

บทนำ

TensorFlow มี operations สำหรับวัดความยาวและแปลง encoding ของ Unicode strings:

  • tf.strings.length: วัดความยาว (รองรับ unit: BYTE, UTF8_CHAR, UTF16_CHAR)
  • tf.strings.unicode_encode: code points → encoded string
  • tf.strings.unicode_decode: encoded string → code points
  • tf.strings.unicode_transcode: แปลง encoding (เช่น UTF-8 → UTF-16-BE)

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

print("The final character takes about 4 bytes in UTF-8 encoding")
thanks = u'Hello 😊'.encode('UTF-8')
num_bytes = tf.strings.length(thanks).numpy()
num_chars = tf.strings.length(thanks, unit='UTF8_CHAR').numpy()
print('{} bytes; {} UTF-8 characters'.format(num_bytes, num_chars))

ผลลัพธ์

The final character takes about 4 bytes in UTF-8 encoding
10 bytes; 7 UTF-8 characters

คำอธิบาย

  • "Hello 😊" = 6 ASCII chars (6 bytes) + 😊 (4 bytes) = 10 bytes
  • แต่เป็น 7 Unicode characters (H,e,l,l,o, space, 😊)
  • unit='UTF8_CHAR' ให้นับ code points แทน bytes
  • สิ่งนี้สำคัญสำหรับ: padding, truncation, positional encoding ใน NLP models

สรุป Operations หลัก

Operationหน้าที่
lengthวัดความยาว (byte หรือ char)
unicode_decodestring → code points (int32 vector)
unicode_encodecode points → string (encoding 指定)
unicode_transcodestring (encoding A) → string (encoding B)
unicode_splitstring → substrings ตัวอักษรเดี่ยว
substrตัด substring (รองรับ char unit)