บทนำ
TensorFlow ใช้ tf.string dtype สำหรับ byte strings (UTF-8 default) มี 2 วิธีหลักแทนค่า Unicode strings:
- String scalar: ลำดับ code points เข้ารหัสด้วย encoding ที่รู้จัก (UTF-8, UTF-16, etc.)
- Int32 vector: แต่ละตำแหน่งเก็บ code point เดียว
โค้ดตัวอย่าง
import tensorflow as tf
print("A constant is defined")
tf.constant(u"Thanks 😊")
print("The shape of the tensor is")
tf.constant([u"You are", u"welcome!"]).shape
print("Unicode string represented as UTF-8 encoded scalar")
text_utf8 = tf.constant(u"语言处理")
print(text_utf8)
print("Unicode string represented as UTF-16 encoded scalar")
text_utf16be = tf.constant(u"语言处理".encode("UTF-16-BE"))
print(text_utf16be)
print("Unicode string represented as a vector of Unicode code points")
text_chars = tf.constant([ord(char) for char in u"语言处理"])
print(text_chars)ผลลัพธ์
A constant is defined The shape of the tensor is Unicode string represented as UTF-8 encoded scalar tf.Tensor(b'\xe8\xaf\xad\xe8\xa8\x80\xe5\xa4\x84\xe7\x90\x86', shape=(), shape=(), dtype=string) Unicode string represented as UTF-16 encoded scalar tf.Tensor(b'\x8b\xed\x8a\x00Y\x04t\x06', shape=(), dtype=string) Unicode string represented as a vector of Unicode code points tf.Tensor([35821 35328 22788 29702], shape=(4,), dtype=int32)
คำอธิบาย
tf.stringtensor เก็บ byte strings ความยาวไม่เท่ากันได้ → shape ไม่รวมความยาว string- Python 3: strings เป็น Unicode default (ไม่ต้อง prefix u) แต่ TF ops คาดหวัง UTF-8 bytes
- Batch strings → decode → RaggedTensor ของ code points (เพราะความยาวต่างกัน)
- RaggedTensor → dense tensor (
.to_tensor(default_value=-1)) หรือ sparse tensor (.to_sparse())
Batch Processing
batch_utf8 = [s.encode('UTF-8') for s in [u'hÃllo', u'What is the weather tomorrow', u'Göödnight', u'😊']]
batch_chars_ragged = tf.strings.unicode_decode(batch_utf8, input_encoding='UTF-8')
# RaggedTensor: [[104,195,108,108,111], [87,104,97,116,...], [71,246,246,100,110,105,103,104,116], [128522]]
batch_chars_padded = batch_chars_ragged.to_tensor(default_value=-1)
batch_chars_sparse = batch_chars_ragged.to_sparse()