開始使用免費開始

為訓練準備資料

在這個練習中,你會繼續準備資料以訓練模型。建立好句子陣列與下一個字元的陣列之後,你需要把它們轉換成模型可用的數值。

這一步是必要的,因為 RNN 模型只接受數字,不接受字串。你將建立數值陣列,於句子中出現的字元所代表的位置填入 0 或 1。1(或 True)代表該位置存在對應字元,0(或 False)代表該位置不存在該字元。

變數 sentencesnext_charn_vocabchars_windownum_seqs(訓練資料中的句子數量)以及 numpy(作為 np)都已載入環境。

本練習屬於課程

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

檢視課程

練習說明

  • 建立一個以 0 初始化的 np.array(),shape 為 (number of sentences, characters window, vocabulary size)
  • 使用字典 char_to_index,把目前字元的位置設為 1
  • 將目前的下一個字元設為 1
  • 印出每個陣列的第一個位置。

動手互動練習

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

# Instantiate the variables with zeros
numerical_sentences = np.zeros((____, ____, ____), dtype=np.bool)
numerical_next_chars = np.zeros((num_seqs, n_vocab), dtype=np.bool)

# Loop for every sentence
for i, sentence in enumerate(sentences):
  # Loop for every character in sentence
  for t, char in enumerate(sentence):
    # Set position of the character to 1
    numerical_sentences[i, t, ____] = ____
    # Set next character to 1
    ____[i, char_to_index[next_chars[i]]] = 1

# Print the first position of each
print(____, ____, sep="\n")
編輯並執行程式碼