当前位置:   article > 正文

如何用python加NLP打造自己的智能问答机器人_智能问答机器人代码

智能问答机器人代码

一、基本流程

我们可以参照以下流程进行智能机器人的程序设计工作,

(1)利用已有的数据对 TfidfVectorizer 模型进行训练

(2)利用训练好的TF-IDF模型进行训练数据data0和真实数据data1的TFIDF值求解

(3)通过余弦相似度进行两者的比较找到data1和data0中的所有值的相似值

(4)取出相似值结果中最相似值的索引,并将该索引对应的答复输出即可

参考代码:

  1. import numpy as np
  2. import jieba
  3. from sklearn.feature_extraction.text import TfidfVectorizer
  4. # 车机的命令与回复数组
  5. from sklearn.metrics.pairwise import cosine_similarity
  6. command=[['请打开车窗','好的,车窗已打开'],
  7. ['我要听陈奕迅的歌','为你播放富士山下'],
  8. ['我好热','已为你把温度调到25度'],
  9. ['帮我打电话给小猪猪','已帮你拨小猪猪的电话'],
  10. ['现在几点钟','现在是早上10点'],
  11. ['我要导航到中华广场','高德地图已打开'],
  12. ['明天天气怎么样','明天天晴']
  13. ]
  14. # 利用 jieba 转换命令格式
  15. def getWords():
  16. comm=np.array(command)
  17. list=[jieba.lcut(sentence) for sentence in comm[:,0]]
  18. words=[' '.join(word) for word in list]
  19. return words
  20. #获取输入命令的分词
  21. def getInputWords():
  22. # 把输入命令转化为数组格式
  23. sentence = jieba.lcut(inputCommand)
  24. words = ' '.join(sentence)
  25. list = []
  26. list.insert(0, words)
  27. return list
  28. # 训练 TfidfVectorizer 模型
  29. def getModel():
  30. words=getWords()
  31. vectorizer=TfidfVectorizer()
  32. model=vectorizer.fit(words)
  33. return model
  34. # 计算 consine 余弦相似度
  35. def consine(): # 获取训练好的 TfidfVectorizer 模型
  36. model=getModel()
  37. # 获取车机命令的 TF-IDF 向量
  38. data0=model.transform(getWords()).toarray().reshape(len(command),-1)
  39. # 获取输入命令的 TF-IDF 向量
  40. data1=model.transform(getInputWords()).toarray().reshape(1,-1)
  41. # 余弦相似度对比
  42. result=cosine_similarity(data0,data1)
  43. print('相似度对比:\n{0}'.format(result))
  44. return result
  45. if __name__=='__main__':
  46. inputCommand=input('您请说:')
  47. # 获取余弦相似度
  48. result=np.array(consine())
  49. # 获取相似度最高的命令 index
  50. argmax=result.argmax()
  51. # 读取命令回复
  52. data=command[argmax][1]
  53. print('命令:{0}\n回复:{1}'.format(inputCommand,data))

问答机器人代码:

train.py

  1. import jieba
  2. import numpy as np
  3. from sklearn.feature_extraction.text import TfidfVectorizer
  4. from joblib import dump
  5. import xlrd
  6. # 车机的命令与回复数组
  7. # command=[['请打开车窗','好的,车窗已打开'],
  8. # ['我要听陈奕迅的歌','为你播放富士山下'],
  9. # ['我好热','已为你把温度调到25度'],
  10. # ['帮我打电话给小猪猪','已帮你拨小猪猪的电话'],
  11. # ['现在几点钟','现在是早上10点'],
  12. # ['我要导航到中华广场','高德地图已打开'],
  13. # ['明天天气怎么样','明天天晴']
  14. # ]
  15. filepath = r'222.xls'
  16. wb = xlrd.open_workbook(filepath)
  17. sheet = wb.sheet_by_index(0)
  18. command = []
  19. for i in range(1,sheet.nrows):
  20. command.append(sheet.row_values(i))
  21. # 利用 jieba 转换命令格式
  22. def getWords():
  23. comm=np.array(command)
  24. list=[jieba.lcut(sentence) for sentence in comm[:,0]]
  25. words=[' '.join(word) for word in list]
  26. return words
  27. # 训练 TfidfVectorizer 模型
  28. def getModel():
  29. words=getWords()
  30. vectorizer=TfidfVectorizer()
  31. model=vectorizer.fit(words)
  32. return model
  33. def maintrain():
  34. model = getModel()
  35. dump(model, 'model.pkl')
  36. # 获取车机命令的 TF-IDF 向量
  37. data0 = model.transform(getWords()).toarray().reshape(len(command), -1)
  38. return data0,command
  39. if __name__ == '__main__':
  40. maintrain()

textsame.py

  1. import numpy as np
  2. import jieba
  3. import streamlit as st
  4. from joblib import load
  5. from train import maintrain
  6. from sklearn.metrics.pairwise import cosine_similarity
  7. # 车机的命令与回复数组
  8. # command=[['请打开车窗','好的,车窗已打开'],
  9. # ['我要听陈奕迅的歌','为你播放富士山下'],
  10. # ['我好热','已为你把温度调到25度'],
  11. # ['帮我打电话给小猪猪','已帮你拨小猪猪的电话'],
  12. # ['现在几点钟','现在是早上10点'],
  13. # ['我要导航到中华广场','高德地图已打开'],
  14. # ['明天天气怎么样','明天天晴']
  15. # ]
  16. # # 利用 jieba 转换命令格式
  17. # def getWords():
  18. # comm=np.array(command)
  19. # list=[jieba.lcut(sentence) for sentence in comm[:,0]]
  20. # words=[' '.join(word) for word in list]
  21. # return words
  22. # 计算 consine 余弦相似度
  23. def consine(inputCommand):
  24. # 把输入命令转化为数组格式
  25. sentence=jieba.lcut(inputCommand)
  26. words=str.join(' ',sentence)
  27. list=[]
  28. list.insert(0,words)
  29. # 获取训练好的 TfidfVectorizer 模型
  30. model=load('model.pkl')
  31. # 获取输入命令的 TF-IDF 向量
  32. data1=model.transform(list).toarray().reshape(1,-1)
  33. # 余弦相似度对比
  34. result=cosine_similarity(data0,data1)
  35. #print('相似度对比:\n{0}'.format(result))
  36. return result
  37. if __name__=='__main__':
  38. #相似度
  39. treshold = 0.8
  40. #拒识话术
  41. jstext = '抱歉,这个问题我不会!!!'
  42. data0,command = maintrain()
  43. comm = st.text_input(label='您请说:', value='')
  44. #comm='我要听陈奕迅的歌'
  45. if comm:
  46. # 获取余弦相似度
  47. result=np.array(consine(comm))
  48. # 获取相似度最高的命令 index
  49. argmax=result.argmax()
  50. # 读取命令回复
  51. data=command[argmax][1]
  52. #print('命令:{0}\n回复:{1}'.format(comm,data))
  53. if result[argmax][0] >= treshold :
  54. data = data
  55. else:
  56. data = jstext
  57. else:
  58. data = ''
  59. st.text_area(label='回复:', value=data)

sbert:

  1. from sentence_transformers import SentenceTransformer, util
  2. import xlrd
  3. import torch
  4. import streamlit as st
  5. #获取知识库中的问题和答案
  6. filepath = r'222.xls'
  7. wb = xlrd.open_workbook(filepath)
  8. sheet = wb.sheet_by_index(0)
  9. normal_questions = sheet.col_values(0)[1:]
  10. normal_answer = sheet.col_values(1)[1:]
  11. #加载模型
  12. model = SentenceTransformer('paraphrase-distilroberta-base-v1')
  13. #获得所有问题的向量
  14. embeddings = torch.load('myTensor.pth')
  15. # 相似度
  16. treshold = 0.7
  17. # 拒识话术
  18. jstext = '抱歉,这个问题我不会!!!'
  19. def sim(query):
  20. #查询条件向量化
  21. q_emd = model.encode(query)
  22. #语料库中的标准问题向量化
  23. #计算相似度
  24. cosine_scores = util.cos_sim(q_emd,embeddings)[0]
  25. top_res = torch.topk(cosine_scores,k=1)
  26. return float(top_res[0]),normal_answer[int(top_res[1])]
  27. if __name__ == '__main__':
  28. st.header("知识问答平台")
  29. comm = st.text_input(label='您请说:', value='')
  30. if comm:
  31. scorebest,answer = sim(query=comm)
  32. if scorebest >= treshold:
  33. data = answer
  34. else:
  35. data = jstext
  36. else:
  37. data = ''
  38. st.text_area(label='回复:', value=data, height=200)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/363440
推荐阅读
相关标签
  

闽ICP备14008679号