文字生成函式

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

David Cecchini

Data Scientist

生成句子

  • 句子由標點決定,例如 .(句點)、!(驚嘆號)、?(問號)。

    • 這些標點需納入詞彙表。
  • 使用句子標記,如 <SENT></SENT>,來標示句首與句尾。

    • 需先前處理資料以插入這些標記。
使用 Keras 建立語言模型的循環神經網路(RNN)

生成句子

sentence = ''

# 迴圈直到句子結束 while next_char != '.':
# 預測下一個字元:取得第 0 個位置的機率陣列 pred = model.predict(X)[0]
char_index = np.argmax(pred)
next_char = index_to_char(char_index)
# 串接到句子 sentence = sentence + next_char
使用 Keras 建立語言模型的循環神經網路(RNN)

機率縮放

調整機率分佈。

  • Temperature:源自物理學
    • _小值_:讓預測更有把握
    • 等於 1:不做縮放
    • 較大值:讓預測更有創意
    • 超參數:嘗試不同數值以符合你的需求
使用 Keras 建立語言模型的循環神經網路(RNN)

機率縮放

def scale_softmax(softmax_pred, temperature=1.0):
    # 取對數
    scaled_pred = np.log(softmax_pred) / temperature

# 再次套用指數 scaled_pred = np.exp(scaled_pred)
# 建立機率分佈 scaled_pred = scaled_pred / np.sum(scaled_pred)
# 模擬多項分佈 scaled_pred = np.random.multinomial(1, scaled_pred, 1)
# 回傳模擬類別 return np.argmax(scaled_pred)
使用 Keras 建立語言模型的循環神經網路(RNN)

一起來練習吧!

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

Preparing Video For Download...