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

วิธีแทนค่า Unicode Strings เป็น UTF-8 Encoded Strings ด้วย TensorFlow และ Python

บทนำ

TensorFlow ใช้ tf.string dtype เก็บ byte strings (UTF-8 default) การแทนค่า Unicode strings หลายรูปแบบ:

  1. UTF-8 encoded scalar: tf.constant(u"text".encode('UTF-8')) หรือ tf.constant(u"text") (Python 3 auto UTF-8)
  2. UTF-16 encoded scalar: tf.constant(u"text".encode('UTF-16-BE'))
  3. Vector of code points (int32): tf.constant([ord(c) for c in u"text"])

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

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=(), 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.string tensor เก็บ byte strings ความยาวต่างกันได้ (atomic units) → shape ไม่รวม string length
  • Python 3: string เป็น Unicode default (ไม่ต้อง prefix u) แต่ TensorFlow ops คาดหวัง UTF-8 bytes
  • สองรูปแบบมาตรฐาน: (1) string scalar (encoded) (2) int32 vector (code points)
  • Batch ของ strings → RaggedTensor ของ code points (เพราะความยาวต่างกัน)
  • RaggedTensor → dense tensor ด้วย .to_tensor(default_value=-1) หรือ sparse tensor ด้วย .to_sparse()

Batch Processing Example

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')
# batch_chars_ragged: 
batch_chars_padded = batch_chars_ragged.to_tensor(default_value=-1)
batch_chars_sparse = batch_chars_ragged.to_sparse()