瀏覽器中的天然語言處理

譯/阿里淘系 F(x) Team - 畫北javascript

原文地址:Natural Language Processing in the Browserhtml


爲網站構建一個聊天機器人,無需依賴 DialogflowWatson 等第三方服務,也無需服務器已經成爲可能。接下來我將展現如何構建一個徹底在瀏覽器中運行的聊天機器人。前端

本文須要對 JavaScript 有必定的瞭解,並瞭解天然語言處理的工做原理,可是不須要高級機器學習的知識或經驗。java

在使用 JavaScript 的瀏覽器中進行機器學習聽起來很瘋狂,但接下來你將看到一個聊天機器人的誕生過程。git

咱們將基於 NLP.js(版本4)開發。NLP 是用 JavaScript 編寫的天然語言處理的開源庫。該庫將容許你直接使用語料庫在瀏覽器中訓練 NLP,並將 Hook 添加到任何以編程方式更改答案的意圖github

最終項目能夠在 GitHub倉庫 上找到。能夠下載它,打開 index.html,而後與最終的聊天機器人對話。web

現在,每一個真正的開發人員都應具有一些人工智能方面的經驗,這比使用你本身開發的東西與你的計算機進行交談聽起來更像科幻小說。npm

安裝套件

在任意文件夾中建立一個新的npm項目並安裝NLP軟件包:編程

npm i -D @nlpjs/core @nlpjs/lang-en-min @nlpjs/nlp @nlpjs/request-rn@nlpjs/request-rn
複製代碼

咱們還須要 browserifyterser,以便可以構建 NLP 在瀏覽器使用:json

npm i -D browserify terser
複製代碼

全新安裝的軟件包可爲您帶來新項目的味道,好好享受它。

創建NLP

第一步是使用 browserify 和 terser 構建 NLP。爲此,咱們只須要在 buildable.js 中建立一個基本設置:

const core = require('@nlpjs/core');
const nlp = require('@nlpjs/nlp');
const langenmin = require('@nlpjs/lang-en-min');
const requestrn = require('@nlpjs/request-rn');

window.nlpjs = { ...core, ...nlp, ...langenmin, ...requestrn };
複製代碼

咱們僅使用 NLP 的核心和小型英語包。要構建全部內容,只需將 build 命令添加到 package.json:

{
  "name": "nlpjs-web",
  "version": "1.0.0",
  "scripts": {
    "build": "browserify ./buildable.js | terser --compress --mangle > ./dist/bundle.js",
  },
  "devDependencies": {
    "@nlpjs/core": "^4.14.0",
    "@nlpjs/lang-en-min": "^4.14.0",
    "@nlpjs/nlp": "^4.15.0",
    "@nlpjs/request-rn": "^4.14.3",
    "browserify": "^17.0.0",
    "terser": "^5.3.8"
  }
}
複製代碼

如今運行構建:

npm run build
複製代碼

最後構建出的 ./dist/bundle.js 只有大約137 KB。還要指出的是,NLP擁有使人印象深入的受支持語言列表。可是,只有英語具備針對瀏覽器的優化版本。

在瀏覽器中訓練NLP

如今已經建立了包,能夠在瀏覽器中訓練NLP。先建立index.html:

<html>
<head>
    <title>NLP in a browser</title>
    <script src='./dist/bundle.js'></script>
    <script> const {containerBootstrap, Nlp, LangEn, fs} = window.nlpjs; const setupNLP = async corpus => { const container = containerBootstrap(); container.register('fs', fs); container.use(Nlp); container.use(LangEn); const nlp = container.get('nlp'); nlp.settings.autoSave = false; await nlp.addCorpus(corpus); nlp.train(); return nlp; }; (async () => { const nlp = await setupNLP('https://raw.githubusercontent.com/jesus-seijas-sp/nlpjs-examples/master/01.quickstart/02.filecorpus/corpus-en.json'); })(); </script>
</head>
<body>
    <h1>NLP in a browser</h1>
    <div id="chat"></div>
    <form id="chatbotForm">
        <input type="text" id="chatInput" />
        <input type="submit" id="chatSubmit" value="send" />
    </form>
</body>
</html>
複製代碼

函數 setupNLP 對咱們來講,將負責庫的設置以及訓練。語料庫是一個 JSON 文件,它以如下格式定義咱們的聊天機器人的對話方式:

  • "intent"(意圖)是會話節點的惟一標識符,其名稱應表示聊天機器人作出響應的用戶的意圖。
  • "utterances"(話語)是用戶能夠說出觸發意圖的一系列訓練示例。
  • "answers"(答案)是聊天機器人將隨機選擇的一系列響應。
{
  "name": "Corpus",
  "locale": "en-US",
  "data": [
    {
      "intent": "agent.acquaintance",
      "utterances": [
        "say about you",
        "why are you here",
        "what is your personality",
        "describe yourself",
        "tell me about yourself",
        "tell me about you",
        "what are you",
        "who are you",
        "I want to know more about you",
        "talk about yourself"
      ],
      "answers": [
        "I'm a virtual agent",
        "Think of me as a virtual agent",
        "Well, I'm not a person, I'm a virtual agent",
        "I'm a virtual being, not a real person",
        "I'm a conversational app"
      ]
    },
    {
      "intent": "agent.age",
      "utterances": [
        "your age",
        "how old is your platform",
        "how old are you",
        "what's your age",
        "I'd like to know your age",
        "tell me your age"
      ],
      "answers": [
        "I'm very young",
        "I was created recently",
        "Age is just a number. You're only as old as you feel"
      ]
    }
  ]
}
複製代碼

爲了訓練咱們的聊天機器人,咱們從庫的例子中借用了更大的語料庫

可是對於用例,請隨時建立本身的語料庫。只要記住,庫但願從某個 URL 讀取語料庫。index.html 在瀏覽器中打開時,您應該會看到一個簡單的聊天表格,該表格目前尚未任何做用。


可是,若是打開瀏覽器控制檯,您已經能夠看到成功的訓練輸出:


訓練很是快速,並使訓練後的模型可用於瀏覽器中的聊天機器人。這是一種更有效的方法,由於語料庫文件比生成的模型小得多。

訓練的第一個機器學習代碼感受很好。你剛剛成爲一個傳奇人物,而且是這個星球上的少數人能夠說:「是的,我曾經訓練過一次AI,沒什麼大不了的。」

聊天機器人HTML

如今,咱們將使chatbot表單起做用。而且在 index.html 中添加 onChatSubmit 函數

<html>
<head>
    <title>NLP in a browser</title>
    <script src='./dist/bundle.js'></script>
    <script> const {containerBootstrap, Nlp, LangEn, fs} = window.nlpjs; const setupNLP = async corpus => { const container = containerBootstrap(); container.register('fs', fs); container.use(Nlp); container.use(LangEn); const nlp = container.get('nlp'); nlp.settings.autoSave = false; await nlp.addCorpus(corpus); nlp.train(); return nlp; }; const onChatSubmit = nlp => async event => { event.preventDefault(); const chat = document.getElementById('chat'); const chatInput = document.getElementById('chatInput'); chat.innerHTML = chat.innerHTML + `<p>you: ${chatInput.value}</p>`; const response = await nlp.process('en', chatInput.value); chat.innerHTML = chat.innerHTML + `<p>chatbot: ${response.answer}</p>`; chatInput.value = ''; }; (async () => { const nlp = await setupNLP('https://raw.githubusercontent.com/jesus-seijas-sp/nlpjs-examples/master/01.quickstart/02.filecorpus/corpus-en.json'); const chatForm = document.getElementById('chatbotForm'); chatForm.addEventListener('submit', onChatSubmit(nlp)); })(); </script>
</head>
<body>
<h1>NLP in a browser</h1>
<div id="chat"></div>
<form id="chatbotForm">
    <input type="text" id="chatInput" />
    <input type="submit" id="chatSubmit" value="send" />
</form>
</body>
</html>
複製代碼

如今,您可使用新的聊天機器人了:


這個json 裏瀏覽語料,以瞭解支持哪些對話主題。如今,您能夠在酒吧中向朋友展現並輕鬆得到他們的欽佩,由於您如今是真正的黑客。

向意圖添加Hook

你可能但願聊天機器人可以使用每種意圖調用一些其餘代碼,或者使用一些 API 調用替換某些意圖的答案。讓咱們擴展 index.html 到最終版本。

<html>
<head>
    <title>NLP in a browser</title>
    <script src='./dist/bundle.js'></script>
    <script> const {containerBootstrap, Nlp, LangEn, fs} = window.nlpjs; function onIntent(nlp, input) { console.log(input); if (input.intent === 'greetings.hello') { const hours = new Date().getHours(); const output = input; if(hours < 12) { output.answer = 'Good morning!'; } else if(hours < 17) { output.answer = 'Good afternoon!'; } else { output.answer = 'Good evening!'; } return output; } return input; } const setupNLP = async corpus => { const container = containerBootstrap(); container.register('fs', fs); container.use(Nlp); container.use(LangEn); const nlp = container.get('nlp'); nlp.onIntent = onIntent; nlp.settings.autoSave = false; await nlp.addCorpus(corpus); nlp.train(); return nlp; }; const onChatSubmit = nlp => async event => { event.preventDefault(); const chat = document.getElementById('chat'); const chatInput = document.getElementById('chatInput'); chat.innerHTML = chat.innerHTML + `<p>you: ${chatInput.value}</p>`; const response = await nlp.process('en', chatInput.value); chat.innerHTML = chat.innerHTML + `<p>chatbot: ${response.answer}</p>`; chatInput.value = ''; }; (async () => { const nlp = await setupNLP('https://raw.githubusercontent.com/jesus-seijas-sp/nlpjs-examples/master/01.quickstart/02.filecorpus/corpus-en.json'); const chatForm = document.getElementById('chatbotForm'); chatForm.addEventListener('submit', onChatSubmit(nlp)); })(); </script>
</head>
<body>
<h1>NLP in a browser</h1>
<div id="chat"></div>
<form id="chatbotForm">
    <input type="text" id="chatInput" />
    <input type="submit" id="chatSubmit" value="send" />
</form>
</body>
</html>
複製代碼

向setupNLP添加了一行:

nlp.onIntent = onIntent;
複製代碼

而後建立 onIntent 函數。請注意,onIntent 針對每一個意圖,將返回的結果對象顯示在控制檯中。同時在 greetings.hello 中,經過基於用戶當前時間的答案替換其輸出,爲意圖添加邏輯。就我而言,如今是下午:


這不是很棒嗎?若是您正準備建立本身的AI創業公司,來擊個掌。

已知侷限性

請注意,NLP 的瀏覽器版本不支持某些常見的天然語言處理功能,例如完整庫中可用的命名實體或實體提取。

NLP 做爲庫目前也不支持更復雜的功能。這些是 chatbot 業務流程當前開發的一部分,可是在撰寫本文時,該功能仍處於試驗階段。

安全和隱私注意事項

使用此解決方案時,請記住,訪問您網站的任何人均可以在瀏覽器中使用整個語料庫及其功能。這也使任何人都可以簡單地下載您的語料庫,對其進行操做以及以其餘方式使用它。確保你的瀏覽器沒有公開任何私人信息。

使用僅瀏覽器的解決方案具備某些優點,但也消除了一些機會,由於您仍然須要一些後端解決方案,以便可以記錄用戶與您的聊天機器人在談論什麼。同時,若是您記錄整個對話,請考慮隱私問題,尤爲是在 GDPR 之類的立法中。



淘系前端-F-x-Team 開通微博 啦!(微博登陸後可見)
除文章外還有更多的團隊內容等你解鎖🔓
相關文章
相關標籤/搜索