開始使用免費開始

Word2Vec

在這個練習中,你將使用 Keras 建立一個 Word2Vec 模型。

用來預先訓練模型的語料庫是影集 The Big Bang Theory 的所有集數腳本,並以句子為單位切分。此語料已存放在變數 bigbang 中。

語料中的文字已轉為小寫,且所有單字都完成分詞。結果存於變數 tokenized_corpus

一個 Word2Vec 模型已預先訓練完成,使用的視窗大小為 10 個單字的脈絡(中心字前 5 個與後 5 個),出現次數少於 3 次的單字已移除,採用 skip-gram 方法,向量維度為 50。模型已儲存為檔案 bigbang_word2vec.model

Word2Vec 類別已從 gensim.models.word2vec 載入到環境中。

本練習屬於課程

使用 Keras 建立語言模型的循環神經網路(RNN)

檢視課程

練習說明

  • 載入預先訓練的 Word2Vec 模型。
  • "bazinga", "penny", "universe", "spock", "brain" 這些單字,依照此順序,存成 list 並指派給變數 words_of_interest
  • 針對每個關注單字進行迭代,使用屬性 wv 上的 .most_similar() 方法,將前 5 個相似單字以字典形式加入 top5_similar_words
  • 列印每個關注單字所找到的前 5 個相似單字。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Word2Vec model
w2v_model = Word2Vec.load(____)

# Selected words to check similarities
words_of_interest = ____

# Compute top 5 similar words for each of the words of interest
top5_similar_words = []
for word in words_of_interest:
    top5_similar_words.append(
      {word: [item[0] for item in w2v_model.wv.____([word], topn=5)]}
    )

# Print the similar words
____
編輯並執行程式碼