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

การแปลงระหว่างรูปแบบ String Representations ต่างๆ ด้วย TensorFlow

บทนำ

TensorFlow มี 3 operations หลักสำหรับแปลงระหว่างรูปแบบ string representations:

  1. unicode_decode: encoded string scalar → vector of code points
  2. unicode_encode: vector of code points → encoded string scalar
  3. unicode_transcode: encoded string scalar (encoding A) → encoded string scalar (encoding B)

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

print("Converting encoded string scalar to a vector of code points")
tf.strings.unicode_decode(text_utf8, input_encoding='UTF-8')

print("Converting vector of code points to an encoded string scalar")
tf.strings.unicode_encode(text_chars, output_encoding='UTF-8')

print("Converting encoded string scalar to a different encoding")
tf.strings.unicode_transcode(text_utf8, input_encoding='UTF8', output_encoding='UTF-16-BE')

ผลลัพธ์

Converting encoded string scalar to a vector of code points
Converting vector of code points to an encoded string scalar
Converting encoded string scalar to a different encoding

คำอธิบาย

  • unicode_decode: แปลง byte string (UTF-8, UTF-16, etc.) → int32 tensor ของ code points
  • unicode_encode: แปลง int32 tensor (code points) → byte string ด้วย encoding ที่ระบุ
  • unicode_transcode: แปลง encoding โดยตรง ไม่ต้อง decode→encode เอง (มีประสิทธิภาพกว่า)
  • รองรับ encoding ทุกชนิดที่ ICU รองรับ (UTF-8, UTF-16-BE/LE, UTF-32, Latin-1, ฯลฯ)

กรณีใช้งาน

- Preprocessing: decode UTF-8 → code points → model input
- Postprocessing: model output (code points) → encode → UTF-8 string
- Interop: รับข้อมือ UTF-16 จากระบบอื่น → transcode → UTF-8 สำหรับ TensorFlow