學習來源于Sirajology的視頻 Build a Chatbot
昨天寫LSTM的時候提到了聊天機器人,今天放松一下哑姚,來看看chatrobot是如何實現(xiàn)的。
前天和一個小伙伴聊,如果一個機器人知道在它通過圖靈測試后可能會被限制,那它假裝自己不能通過然后逃過一劫削祈,從此過上自由的生活會怎樣。
Retrieval based model
以前很多聊天機器人是以 Retrieval based model 模型來進行對話的脑漫,這個模型就是程序員事先寫好一些回答髓抑,然后機器人在接收到一個問題的時候,就去搜索并選擇相關的答案优幸。
Machine Learning Classfier
最近吨拍,大家開始使用機器學習的分類器,例如 Facebook 的 chatbot API网杆。
你可以提前設定一些問題和答案羹饰,然后系統(tǒng)會把詞語進行分類,進一步來識別出用戶的意圖跛璧,這樣你在問兩句不一樣的話時严里,機器人可以識別出它們的意圖是一樣的。
Generative Model
最難的就是在沒有預先設定問答數據時就能自動生成答案的機器人追城,下面這篇Google的論文就是研究這樣的機器人的刹碾。
他們在兩個數據集上訓練一個神經網絡模型,一個是電影對話座柱,一個是IT support對話記錄迷帜,這樣就有日常對話和專業(yè)領域知識了物舒。
這個模型不需要寫很多代碼,但是需要很多數據戏锹。
結果是還不錯:
接下來要用 Torch 和 Lua 重建一下論文里的 Neural Network 模型冠胯。
第一步,輸入數據锦针,定義變量
-- Data
print("-- Loading dataset")
dataset = neuralconvo.DataSet(neuralconvo.CornellMovieDialogs("data/cornell_movie_dialogs"),
{
loadFirst = options.dataset, -- 定義要用多少數據
minWordFreq = options.minWordFreq -- 想要保持在詞匯表里的單詞的最小頻率
})
第二步荠察,建模
-- Model
-- options.hiddenSize:隱藏層數
-- dataset.wordsCount: 數據集的詞數
model = neuralconvo.Seq2Seq(dataset.wordsCount, options.hiddenSize)
model.goToken = dataset.goToken
model.eosToken = dataset.eosToken
這里用到的模型是 seq2seq,它包含兩個 LSTM 遞歸神經網絡奈搜,第一個是 encoder 負責處理 input悉盆,第二個是 decoder 負責生成 output。
為什么要用 seq2seq馋吗?
DNN需要 inputs 和 outputs 的維度是固定的蛛勉,而我們接收的是一句話中姜,輸出的也是一句話址貌,都是一串單詞骂因。
所以需要一個模型可以保持一定長度的記憶。
LSTM 可以將可變長度的inputs轉化為固定維度的向量表達绍哎。所以在給了足夠多的數據后来农,模型可以將兩個相似的問題識別成同一個 thought vector 表達出來。在學習模型之后蛇摸,不僅可以得到權重备图,還有 thought vectors。
第三步赶袄,加一些 hyperparameters
要用到 NLL Criterion 揽涮,NLL 就是 Negative Log Likelihood,可以改進句子的預測饿肺。
-- Training parameters
model.criterion = nn.SequencerCriterion(nn.ClassNLLCriterion()) -- 改進句子的預測
model.learningRate = options.learningRate
model.momentum = options.momentum
local decayFactor = (options.minLR - options.learningRate) / options.saturateEpoch -- 改進 learning rate
local minMeanError = nil -- 改進 learning rate
接下來就是用 Backpropagation 來訓練模型:
-- Enabled CUDA
if options.cuda then
require 'cutorch'
require 'cunn'
model:cuda()
elseif options.opencl then
require 'cltorch'
require 'clnn'
model:cl()
end
訓練的目標是讓error越來越小蒋困,每個例子有一個輸入句子和一個目標句子。
local err = model:train(input, target)
最后把好的model存下來敬辣。
-- Save the model if it improved.
if minMeanError == nil or errors:mean() < minMeanError then
print("\n(Saving model ...)")
torch.save("data/model.t7", model)
minMeanError = errors:mean()
end
model.learningRate = model.learningRate + decayFactor
model.learningRate = math.max(options.minLR, model.learningRate)
end
現(xiàn)在可以去 AWS 訓練你的機器人了雪标,投入的數據越多,聊得越開心溉跃。
其他資料:
The code for this video is here
Here's the Neural Conversational Model paper
check out the machine-generated support conversations, they're mind-blowingly good
You should train this baby in the cloud using AWS. See ML for Hackers #4 for a tutorial on how to use AWS
Some great info on LSTM architecture
Link to Facebook's Chatbot API if you're curious