十分鐘,如何制作一個(gè)聊天機(jī)器人?
本文轉(zhuǎn)載自公眾號(hào)“讀芯術(shù)”(ID:AI_Discovery)
了解聊天機(jī)器人的主要用途很重要,每個(gè)行業(yè)都不能使用同一個(gè)聊天機(jī)器人,他們有不同的目的和不同的語(yǔ)料庫(kù)。雖然消息傳遞組件可以很好地給予答復(fù),但是可能需要時(shí)間作出回應(yīng)。另一方面,考慮到時(shí)間問(wèn)題,可以應(yīng)用各種其他方法,甚至可以找到一些以規(guī)則為基礎(chǔ)的系統(tǒng),以獲得適合回答所提問(wèn)題的語(yǔ)句。
你曾多少次聯(lián)系旅行社要求退票,得到一個(gè)恰當(dāng)?shù)拇饛?fù)是遠(yuǎn)遠(yuǎn)不夠的。
現(xiàn)在讓我們制作一個(gè)簡(jiǎn)單的聊天機(jī)器人,安裝以下軟件包:
- pip install nltk
- pip install newspaper3k
Package newspaper3k有以下優(yōu)點(diǎn):
- 多線程文章下載框架
- 可識(shí)別新聞URL
- 可從HTML中提取文本
- 從HTML中提取頂層圖像
- 可從HTML提取所有圖像
- 可從文本中提取關(guān)鍵詞
- 可從文本中提取摘要
- 可從文本中提取作者
- 谷歌趨勢(shì)術(shù)語(yǔ)提取
- 使用10多種語(yǔ)言(英語(yǔ)、德語(yǔ)、阿拉伯語(yǔ)、中文等)
導(dǎo)入庫(kù),如下所示:
- #import libraries
- from newspaper import Article
- import random
- import nltk
- import string
- from sklearn.feature_extraction.text import CountVectorizer
- from sklearn.metrics.pairwise import cosine_similarity
余弦相似度或余弦核將相似度計(jì)算為X和Y的標(biāo)準(zhǔn)化點(diǎn)積:
- sklearn.metrics.pairwise.cosine_similarity(X, Y=None, dense_output=True)
參數(shù)
X{ndarray, sparse matrix} of shape (n_samples_X, n_features) 輸入數(shù)據(jù)。
Y{ndarray,sparse matrix} of shape (n_samples_Y, n_features), default=None 輸入數(shù)據(jù)。
如果沒(méi)有,輸出將是X. dense_outputbool中所有樣本之間的成對(duì)相似性,default =True是否返回密集輸出,即使輸入是稀疏的。如果為False,則如果兩個(gè)輸入數(shù)組都是稀疏的,則輸出是稀疏的。
返回
核矩陣:ndarray of shape(n_samples_X, n_samples_Y)
- import numpy as np
- import warnings
- warnings.filterwarnings('ignore')
這里從一個(gè)醫(yī)療保健網(wǎng)站獲取數(shù)據(jù):
- article=Article("https://www.mayoclinic.org/diseases-conditions/chronic-kidney-disease/symptoms-causes/syc-20354521")
- article.download()
- article.parse()
- article.nlp()
- corpus=article.text
- print(corpus)
- #tokenization
- text=corpus
- sentence_list=nltk.sent_tokenize(text) #A list of sentences
- #Print the list of sentences
- print(sentence_list)
準(zhǔn)備好了語(yǔ)料庫(kù)之后,你需要考慮用戶或客戶可能會(huì)問(wèn)或說(shuō)的問(wèn)題,這與我們的內(nèi)容無(wú)關(guān)。它可以是問(wèn)候語(yǔ)、感謝語(yǔ),也可以是拜拜之類(lèi)的信息。團(tuán)隊(duì)需要就這些信息和他們的反應(yīng)進(jìn)行考量。
問(wèn)候機(jī)器人響應(yīng):
- #Random response to greeting
- def greeting_response(text):
- text=text.lower()
- #Bots greeting
- bot_greetings=["howdy","hi","hola","hey","hello"]
- #User Greetings
- user_greetings=["wassup","howdy","hi","hola","hey","hello"]
- for word in text.split():
- if word in user_greetings:
- return random.choice(bot_greetings)
- #Random response to greeting
- def gratitude_response(text):
- text=text.lower()
感謝機(jī)器人響應(yīng):
- #Bots gratitude
- bot_gratitude=["Glad tohelp","You are most welcome", "Pleasure to be ofhelp"]
- #User Gratitude
- user_gratitude=["Thankyou somuch","grateful","Thankyou","thankyou","thankyou"]
- for word in text.split():
- if word in user_gratitude:
- return random.choice(bot_gratitude)
種類(lèi)列表:
- # Default title text
- def index_sort(list_var):
- length=len(list_var)
- list_index=list(range(0,length))
- x=list_var
- for i in range(length):
- for j in range(length):
- if x[list_index[i]]>x[list_index[j]]:
- #swap
- temp=list_index[i]
- list_index[i]=list_index[j]
- list_index[j]=temp
- return list_index
聊天機(jī)器人響應(yīng)功能來(lái)自于對(duì)預(yù)定義文本的余弦相似性的響應(yīng)。
- #Creat Bots Response
- def bot_response(user_input):
- user_input=user_input.lower()
- sentence_list.append(user_input)
- bot_response=""
- cm=CountVectorizer().fit_transform(sentence_list)
- similarity_scores=cosine_similarity(cm[-1],cm)
- similarity_scores_list=similarity_scores.flatten()
- index=index_sort(similarity_scores_list)
- index=index[1:]
- response_flag=0
- j=0
- for i in range(len(index)):
- ifsimilarity_scores_list[index[i]]>0.0:
- bot_response=bot_response+''+sentence_list[index[i]]
- response_flag=1
- j=j+1
- if j>2:
- break
- if response_flag==0:
- bot_response=bot_response+""+"I apologize, I dont understand"
- sentence_list.remove(user_input)
- return bot_response
對(duì)于退出聊天,退出列表中的單詞寫(xiě)為“退出”,“再見(jiàn)”,“再見(jiàn)”,“退出”。
響應(yīng)這些話,聊天機(jī)器人將退出聊天。
啟動(dòng)聊天機(jī)器人,盡情享受吧!
- #Start Chat
- print("Doc Bot: I am DOc bot and I will answer your queries about chronickidney disease, if you want to exit type, bye")
- exit_list=['exit','bye','see you later','quit']
- while(True):
- user_input=input()
- if user_input.lower() in exit_list:
- print("Doc Bot: Bye Bye See youlater")
- break
- elif greeting_response(user_input)!=None:
- print("Doc Bot: "+greeting_response(user_input))
- elif gratitude_response(user_input)!=None:
- print("Doc Bot: "+gratitude_response(user_input))
- else:
- print("Doc Bot: "+bot_response(user_input))
請(qǐng)參見(jiàn)下面聊天機(jī)器人的回復(fù):
“謝謝”并不在我們的機(jī)器人感謝程序中,因此我們要傳達(dá)這樣的信息。隨著時(shí)間的推移,你可以擴(kuò)大這樣的詞匯表,或者使用正則表達(dá)式對(duì)其進(jìn)行微調(diào)。
舉個(gè)小例子,與聊天機(jī)器人開(kāi)始聊天,應(yīng)該是快速和簡(jiǎn)單的。你需要針對(duì)不同行業(yè)對(duì)聊天機(jī)器人進(jìn)行微調(diào),這些行業(yè)的語(yǔ)料庫(kù)來(lái)自實(shí)時(shí)數(shù)據(jù)或云端的一些儲(chǔ)存。
此外,需要注意的是,實(shí)時(shí)數(shù)據(jù)要面對(duì)挑戰(zhàn),聊天必須基于最新的數(shù)據(jù)作出回應(yīng),例如在旅行社訂票。