如何使用Python和TensorFlow從伊利亞特資料集的標記化單詞中構建詞彙表?


TensorFlow是由Google提供的機器學習框架。它是一個開源框架,與Python結合使用,可以實現演算法、深度學習應用程式等等。它用於研究和生產目的。它具有最佳化技術,有助於快速執行復雜的數學運算。這是因為它使用了NumPy和多維陣列。這些多維陣列也稱為“張量”。該框架支援使用深度神經網路。

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

我們將使用伊利亞特資料集,其中包含威廉·考珀、愛德華(德比伯爵)和塞繆爾·巴特勒三位譯者的三個譯文文字資料。該模型經過訓練,可以在給出單行文字時識別翻譯者。所使用的文字檔案已進行預處理。這包括刪除文件頁首和頁尾、行號和章節標題。

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

示例

以下是程式碼片段:

print("Build a vocabulary using the tokens")
tokenized_ds = configure_dataset(tokenized_ds)
vocab_dict = collections.defaultdict(lambda: 0)
for toks in tokenized_ds.as_numpy_iterator():
   for tok in toks:
   vocab_dict[tok] += 1
print("Sort the vocabulary")
vocab = sorted(vocab_dict.items(), key=lambda x: x[1], reverse=True)
vocab = [token for token, count in vocab]
vocab = vocab[:VOCAB_SIZE]
vocab_size = len(vocab)
print("The vocabulary size is : ", vocab_size)
print("First six vocabulary entries are :", vocab[:6])

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

輸出

Build a vocabulary using the tokens
Sort the vocabulary
The vocabulary size is : 10000
First six vocabulary entries are : [b',', b'the', b'and', b"'", b'of', b'.']

接下來,您將透過按頻率對標記排序並保留前VOCAB_SIZE個標記來構建詞彙表。

解釋

  • 根據標記的頻率排序後構建詞彙表。

  • 控制檯中顯示了一些詞彙表條目。

更新於:2021年1月19日

313 次瀏覽

啟動您的職業生涯

完成課程獲得認證

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