Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách biểu diễn và thao tác chuỗi Unicode trong TensorFlow

Chuỗi Unicode mặc định được mã hóa UTF-8. TensorFlow hỗ trợ hai cách biểu diễn chuẩn:

  1. String scalar: chuỗi mã điểm được mã hóa với encoding biết trước (UTF-8, UTF-16, v.v.).
  2. Vector int32: mỗi vị trí chứa một mã điểm đơn lẻ.

Mã ví dụ

import tensorflow as tf
print("Định nghĩa hằng số")
tf.constant(u"Thanks 😊")
print("Shape của tensor")
tf.constant([u"You are", u"welcome!"]).shape

print("Unicode string as UTF-8 scalar")
text_utf8 = tf.constant(u"语言处理")
print(text_utf8)

print("Unicode string as UTF-16-BE scalar")
text_utf16be = tf.constant(u"语言处理".encode("UTF-16-BE"))
print(text_utf16be)

print("Unicode string as vector of code points")
text_chars = tf.constant([ord(char) for char in u"语言处理"])
print(text_chars)

Nguồn mã: TensorFlow Unicode Tutorial

Đầu ra

Định nghĩa hằng số
Shape của tensor
Unicode string as UTF-8 scalar
tf.Tensor(b'\xe8\xaf\xad\xe8\xa8\x80\xe5\xa4\x84\xe7\x90\x86', shape=(), dtype=string)
Unicode string as UTF-16-BE scalar
tf.Tensor(b'\x8b\xed\x8a\x00Y\x04t\x06', shape=(), dtype=string)
Unicode string as vector of code points
tf.Tensor([35821 35328 22788 29702], shape=(4,), dtype=int32)

Giải thích

  • tf.string là kiểu dữ liệu cơ bản, chứa chuỗi byte.
  • Unicode strings mặc định UTF-8.
  • Tensor string chứa byte strings độ dài khác nhau (được coi như đơn vị nguyên tử).
  • Độ dài chuỗi KHÔNG nằm trong shape tensor.
  • Python 2: tiền tố u cho unicode; Python 3: chuỗi mặc định unicode.
  • Hai cách biểu diễn chuẩn: string scalar (encoded) và int32 vector (code points).