聊天机器人的历史可以追溯到1966年,当时韦森鲍姆发明了一种名为“伊丽莎”(ELIZA)的电脑程序。它仅仅从200行代码中模仿一个心理治疗师的言语。你现在仍然可以和它交谈:伊丽莎。
TF = (Number of times term t appears in a document)/(Number of terms in the document)
逆文档频率:是这个词在文档中罕见度的得分。
IDF = 1+log(N/n), where, N is the number of documents and n is the number of documents a term t has appeared in.
Tf-idf 权重是信息检索和文本挖掘中常用的一种权重。该权重是一种统计度量,用于评估单词对集合或语料库中的文档有多重要
例子: 考虑一个包含100个单词的文档,其中单词“phone”出现了5次。 “phone”的检索词频率就是(5 / 100) = 0.05。现在,假设我们有1000万份文档,其中1000份文档中出现了“电话”这个词。那么逆文档频率就是log(10,000,000 / 1,000) = 4。TF-IDF权重就是这两者的乘积:0.05 * 4 = 0.20。
余弦相似度 TF-IDF是一种在向量空间中得到两个实值向量的文本变换。然后我们可以通过取点积然后除以它们的范数乘积来得到任意一对向量的余弦相似度。接着以此得到向量夹角的余弦值。余弦相似度是两个非零向量之间相似度的度量。利用这个公式,我们可以求出任意两个文档d1和d2之间的相似性。
Cosine Similarity (d1, d2) = Dot product(d1, d2) / ||d1|| * ||d2||
其中d1,d2是非零向量。 TF-IDF和余弦相似度的详细说明和实际例子参见下面的文档。 (见文末) 现在我们对NLP过程有了一个基本概念。是我们开始真正工作的时候了。我们在这里将聊天机器人命名为“ROBO?”
导入必备库
import nltk
import numpy as np
import random
import string # to process standard Python strings
语料库 在我们的示例中,我们将使用聊天机器人的Wikipedia页面作为我们的语料库。从页面复制内容并将其放入名为“chatbot.txt”的文本文件中。然而,你可以使用你选择的任何语料库。
读入数据 我们将阅读corpus.txt文件,并将整个语料库转换为句子列表和单词列表,以便进行进一步的预处理。
f=open('chatbot.txt','r',errors = 'ignore')
raw=f.read()
raw=raw.lower()# converts to lowercase
nltk.download('punkt') # first-time use only
nltk.download('wordnet') # first-time use only
sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences
word_tokens = nltk.word_tokenize(raw)# converts to list of words
让我们看看sent_tokens 和 the word_tokens的例子
['a chatbot (also known as a talkbot, chatterbot, bot, im bot, interactive agent, or artificial conversational entity) is a computer program or an artificial intelligence which conducts a conversation via auditory or textual methods.',
'such programs are often designed to convincingly simulate how a human would behave as a conversational partner, thereby passing the turing test.']
['a', 'chatbot', '(', 'also', 'known']
预处理原始文本
现在我们将定义一个名为LemTokens 的函数,它将接受符号作为输入并返回规范化符号。
lemmer = nltk.stem.WordNetLemmatizer()
#
def LemTokens(tokens):
return [lemmer.lemmatize(token) for token in tokens]
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
def LemNormalize(text):
return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))
关键字匹配
接下来,我们将通过机器人定义一个问候函数,即如果用户的输入是问候语,机器人将返回相应的回复。ELIZA使用一个简单的关键字匹配问候。我们将在这里使用相同的概念。
GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey",)
GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]
def greeting(sentence):
for word in sentence.split():
if word.lower() in GREETING_INPUTS:
return random.choice(GREETING_RESPONSES)
生成回复 为了让我们的机器人为输入问题生成回复,这里将使用文档相似性的概念。因此,我们首先需要导入必要的模块。 从scikit learn库中,导入TFidf矢量化器,将一组原始文档转换为TF-IDF特征矩阵。
from sklearn.feature_extraction.text import TfidfVectorizer
同时, 从scikit learn库中导入 cosine similarity 模块
from sklearn.metrics.pairwise import cosine_similarity
这将用于查找用户输入的单词与语料库中的单词之间的相似性。这是聊天机器人最简单的实现。 我们定义了一个回复函数,该函数搜索用户的表达,搜索一个或多个已知的关键字,并返回几个可能的回复之一。如果没有找到与任何关键字匹配的输入,它将返回一个响应:“对不起!”我不明白你的意思"
def response(user_response):
robo_response=''
TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
tfidf = TfidfVec.fit_transform(sent_tokens)
vals = cosine_similarity(tfidf[-1], tfidf)
idx=vals.argsort()[0][-2]
flat = vals.flatten()
flat.sort()
req_tfidf = flat[-2]
if(req_tfidf==0):
robo_response=robo_response+"I am sorry! I don't understand you"
return robo_response
else:
robo_response = robo_response+sent_tokens[idx]
return robo_response
最后,我们将根据用户的输入来决定机器人在开始和结束对话时说的话。
flag=Trueprint("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!")
while(flag==True):
user_response = input()
user_response=user_response.lower()
if(user_response!='bye'):
if(user_response=='thanks' or user_response=='thank you' ):
flag=False
print("ROBO: You are welcome..")
else:
if(greeting(user_response)!=None):
print("ROBO: "+greeting(user_response))
else:
sent_tokens.append(user_response)
word_tokens=word_tokens+nltk.word_tokenize(user_response)
final_words=list(set(word_tokens))
print("ROBO: ",end="")
print(response(user_response))
sent_tokens.remove(user_response)
else:
flag=False
print("ROBO: Bye! take care..")
差不多就是这样。 现在,让我们看看它是如何与人类互动的:
AI研习社是AI学术青年和开发者社区,为大家提供一个顶会资讯、论文解读、数据竞赛、求职内推等的技术交流阵地,欢迎登陆www.yanxishe.com加入我们吧~
投稿、转载、媒介合作联系微信号 | bajiaojiao-sz商务合作联系微信号 | LJ18825253481