如何在TensorFlow中表示和操作Unicode字串?
Unicode 字串預設使用 UTF-8 編碼。可以使用 TensorFlow 模組中的“constant”方法將 Unicode 字串表示為 UTF-8 編碼的標量值。可以使用 TensorFlow 模組中的“encode”方法將 Unicode 字串表示為 UTF-16 編碼的標量。
閱讀更多:什麼是 TensorFlow?Keras 如何與 TensorFlow 一起建立神經網路?
處理自然語言的模型會處理不同語言,這些語言具有不同的字元集。Unicode 被認為是標準編碼系統,用於表示幾乎所有語言的字元。每個字元都使用介於 0 和 0x10FFFF 之間的唯一整數程式碼點進行編碼。Unicode 字串是由零個或多個程式碼值組成的序列。
讓我們瞭解如何使用 Python 表示 Unicode 字串,以及如何使用 Unicode 等效項來操作這些字串。首先,我們使用 Unicode 等效的標準字串操作,根據指令碼檢測將 Unicode 字串分成標記。
我們使用 Google Colaboratory 來執行以下程式碼。Google Colab 或 Colaboratory 幫助在瀏覽器上執行 Python 程式碼,無需任何配置,並可免費訪問 GPU(圖形處理單元)。Colaboratory 基於 Jupyter Notebook 構建。
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)程式碼來源:https://www.tensorflow.org/tutorials/load_data/unicode
輸出
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)
解釋
- TensorFlow `tf.string` 是一個基本資料型別。
- 它允許使用者構建位元組字串張量。
- Unicode 字串預設使用 UTF-8 編碼。
- 由於位元組字串被視為原子單元,因此 `tf.string` 張量能夠儲存不同長度的位元組字串。
- 字串長度不包含在張量維度中。
- 當使用 Python 構造字串時,Unicode 處理在 v2 和 v3 之間有所不同。在 v2 中,Unicode 字串用 "u" 字首表示。
- 在 v3 中,字串預設使用 Unicode 編碼。
- 在 TensorFlow 中表示 Unicode 字串的兩種標準方法:
- 字串標量:使用已知的字元編碼對程式碼點序列進行編碼。
- int32 向量:每一位包含單個程式碼點的方法。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP