如何使用Tensorflow和Python獲取句子中每個單詞的程式碼點?


要獲取句子中每個單詞的程式碼點,首先檢查句子是否是單詞的開頭。然後,檢查字元索引是否從扁平化字元列表(來自所有句子)中單詞的特定索引開始。驗證後,使用以下方法獲取每個單詞中每個字元的程式碼點。

指令碼識別符號有助於確定單詞邊界以及應新增位置。在句子的開頭以及每個指令碼與其前一個字元不同的字元處新增單詞邊界。可以使用起始偏移量構建RaggedTensor。這個RaggedTensor將包含所有批次中的單詞列表。

閱讀更多: 什麼是TensorFlow以及Keras如何與TensorFlow一起建立神經網路?

讓我們瞭解如何使用Python表示Unicode字串,以及如何使用Unicode等價物來操作它們。首先,我們藉助Unicode等價的標準字串操作,根據指令碼檢測將Unicode字串分成標記。

我們使用Google Colaboratory執行以下程式碼。Google Colab或Colaboratory有助於透過瀏覽器執行Python程式碼,無需任何配置,並可免費訪問GPU(圖形處理單元)。Colaboratory構建於Jupyter Notebook之上。

print("Check if sentence is the start of the word")
sentence_char_starts_word = tf.concat(
   [tf.fill([sentence_char_script.nrows(), 1], True),
    tf.not_equal(sentence_char_script[:, 1:], sentence_char_script[:, :-1])],
   axis=1)
print("Check if index of character starts from specific index of word in flattened list of characters from all sentences")
word_starts = tf.squeeze(tf.where(sentence_char_starts_word.values), axis=1)
print(word_starts)
print("Get the code point of every character in every word")
word_char_codepoint = tf.RaggedTensor.from_row_starts(
   values=sentence_char_codepoint.values,
   row_starts=word_starts)
print(word_char_codepoint)

程式碼來源:https://www.tensorflow.org/tutorials/load_data/unicode

輸出

Check if sentence is the start of the word
Check if index of character starts from specific index of word in flattened list of characters from all sentences
tf.Tensor([ 0   5   7 12 13 15], shape=(6,), dtype=int64)
Get the code point of every character in every word
<tf.RaggedTensor [[72, 101, 108, 108, 111], [44, 32], [116, 104, 101, 114, 101], [46], [19990, 30028], [12371, 12435, 12395, 12385, 12399]]>

解釋

  • 指令碼識別符號有助於確定應在何處新增單詞邊界。
  • 在每個句子的開頭以及每個指令碼與其前一個字元不同的字元處新增單詞邊界。
  • 接下來,可以使用這些起始偏移量來構建RaggedTensor。
  • 此RaggedTensor包含所有批次中的單詞列表。

更新於: 2021年2月20日

83 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.