如何使用Tensorflow和Python將伊利亞特資料集中的分詞轉換為整數?


Tensorflow 是 Google 提供的一個機器學習框架。它是一個開源框架,與 Python 結合使用,用於實現演算法、深度學習應用程式等等。它被用於研究和生產目的。

可以使用以下程式碼行在 Windows 上安裝“tensorflow”包:

pip install tensorflow

張量是 TensorFlow 中使用的資料結構。它有助於連線流圖中的邊。此流圖稱為“資料流圖”。張量只不過是多維陣列或列表。

它們可以使用三個主要屬性進行識別:

  • - 它說明張量的維度。可以理解為張量的階數或已定義張量的維度數。

  • 型別 - 它說明與張量元素相關聯的資料型別。它可以是一維、二維或 n 維張量。

  • 形狀 - 它是由行數和列數共同組成的。

我們將使用伊利亞特資料集,其中包含 William Cowper、Edward(Derby 伯爵)和 Samuel Butler 三個譯本的文字資料。該模型經過訓練,可以在給出一行文字時識別翻譯者。所使用的文字檔案已進行預處理。這包括刪除文件標題和頁尾、行號和章節標題。

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

示例

以下是程式碼片段:

keys = vocab
values = range(2, len(vocab) + 2) # reserve 0 for padding, 1 for OOV
print("Map the tokens to integers")
init = tf.lookup.KeyValueTensorInitializer(
   keys, values, key_dtype=tf.string, value_dtype=tf.int64)
num_oov_buckets = 1
vocab_table = tf.lookup.StaticVocabularyTable(init, num_oov_buckets)
print("A function has been defined to standardize, tokenize and vectorize the dataset using
tokenizer and lookup table")
def preprocess_text(text, label):
   standardized = tf_text.case_fold_utf8(text)
   tokenized = tokenizer.tokenize(standardized)
   vectorized = vocab_table.lookup(tokenized)
   return vectorized, label

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

輸出

Map the tokens to integers
A function has been defined to standardize, tokenize and vectorize the dataset using tokenizer
and lookup table

解釋

  • 詞彙表集用於建立 StaticVocabularyTable。

  • 標記被對映到 [2, vocab_size + 2] 範圍內的整數。

  • 數字 0 用於表示填充,數字 1 用於表示詞彙表外 (OOV) 標記。

更新於:2021年1月19日

98 次瀏覽

開啟您的職業生涯

完成課程,獲得認證

開始學習
廣告