原文链接:http://www.one2know.cn/nlp24/

  • 准备

    数据集:AIML数据集

    下载数据集并用Notepad++打开,复制到txt文件中方便打开
  • 代码实现

    数据很少,训练轮次不多,结果不好,仅当示例
import numpy as np
import pandas as pd with open('bot.txt','r') as content_file:
botdata = content_file.read()
Questions = []
Answers = [] for line in botdata.split('</pattern>'):
if '<pattern>' in line:
Quesn = line[line.find('<pattern>')+len('<pattern>'):]
Questions.append(Quesn.lower())
for line in botdata.split('</template>'):
if '<template>' in line:
Ans = line[line.find('<template>')+len('<template>'):]
Answers.append(Ans.lower())
QnAdata = pd.DataFrame(np.column_stack([Questions,Answers]),columns=['Questions','Answers'])
QnAdata['QnAcomb'] = QnAdata['Questions'] + ' ' + QnAdata['Answers']
print(QnAdata[:5]) import nltk
import collections ## 向量化
counter = collections.Counter()
for i in range(len(QnAdata)):
for word in nltk.word_tokenize(QnAdata.iloc[i][2]):
counter[word] += 1
word2idx = {w:(i+1) for i,(w,_) in enumerate(counter.most_common())}
idx2word = {v:k for k,v in word2idx.items()}
idx2word[0] = 'PAD'
vocab_size = len(word2idx) + 1
print('\nVocabulary size:',vocab_size) def encode(sentence, maxlen,vocab_size):
indices = np.zeros((maxlen, vocab_size))
for i, w in enumerate(nltk.word_tokenize(sentence)):
if i == maxlen: break
indices[i, word2idx[w]] = 1
return indices def decode(indices, calc_argmax=True):
if calc_argmax:
indices = np.argmax(indices, axis=-1)
return ' '.join(idx2word[x] for x in indices) question_maxlen = 10
answer_maxlen = 20 def create_questions(question_maxlen,vocab_size):
question_idx = np.zeros(shape=(len(Questions),question_maxlen,vocab_size))
for q in range(len(Questions)):
question = encode(Questions[q],question_maxlen,vocab_size)
question_idx[i] = question
return question_idx quesns_train = create_questions(question_maxlen=question_maxlen,vocab_size=vocab_size) def create_answers(answer_maxlen,vocab_size):
answer_idx = np.zeros(shape=(len(Answers),answer_maxlen,vocab_size))
for q in range(len(Answers)):
answer = encode(Answers[q],answer_maxlen,vocab_size)
answer_idx[i] = answer
return answer_idx answs_train = create_answers(answer_maxlen=answer_maxlen,vocab_size=vocab_size) from keras.layers import Input,Dense,Dropout,Activation
from keras.models import Model
from keras.layers.recurrent import LSTM
from keras.layers.wrappers import Bidirectional
from keras.layers import RepeatVector,TimeDistributed,ActivityRegularization n_hidden = 128 question_layer = Input(shape=(question_maxlen,vocab_size)) encoder_rnn = LSTM(n_hidden,dropout=0.2,recurrent_dropout=0.2)(question_layer)
# encoder_rnn = Bidirectional(LSTM(n_hidden,dropout=0.2,recurrent_dropout=0.2),merge_mode='concat')(question_layer)
# RNN的双向包装 向前和向后RNN的输出将合并
# merge_mode(合并模型)参数:{'sum', 'mul', 'concat', 'ave', None} repeat_encode = RepeatVector(answer_maxlen)(encoder_rnn)
# 重复输入n次 shape加了一维 比如(a,b,c)=>(n,a,b,c) dense_layer = TimeDistributed(Dense(vocab_size))(repeat_encode)
# TimeDistributed和Dense一起使用,
# 在静态形状中查找非特定维度,并用张量的相应动态形状代替它们 regularized_layer = ActivityRegularization(l2=1)(dense_layer)
# 对基于代价函数的输入活动应用更新的层 softmax_layer = Activation('softmax')(regularized_layer) model = Model([question_layer],[softmax_layer]) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) print(model.summary()) # 模型训练
quesns_train_2 = quesns_train.astype('float32')
answs_train_2 = answs_train.astype('float32') model.fit(quesns_train_2, answs_train_2,batch_size=32,epochs=30,validation_split=0.05) # 模型预测
ans_pred = model.predict(quesns_train_2[0:3])
print(decode(ans_pred[0]))
print(decode(ans_pred[1]))

NLP(二十四)使用LSTM构建生成式聊天机器人的更多相关文章

  1. (C/C++学习笔记) 二十四. 知识补充

    二十四. 知识补充 ● 子类调用父类构造函数 ※ 为什么子类要调用父类的构造函数? 因为子类继承父类,会继承到父类中的数据,所以子类在进行对象初始化时,先调用父类的构造函数,这就是子类的实例化过程. ...

  2. Bootstrap<基础二十四> 缩略图

    Bootstrap 缩略图.大多数站点都需要在网格中布局图像.视频.文本等.Bootstrap 通过缩略图为此提供了一种简便的方式.使用 Bootstrap 创建缩略图的步骤如下: 在图像周围添加带有 ...

  3. 二十四、Struts2中的UI标签

    二十四.Struts2中的UI标签 Struts2中UI标签的优势: 数据回显 页面布局和排版(Freemark),struts2提供了一些常用的排版(主题:xhtml默认 simple ajax) ...

  4. WCF技术剖析之二十四: ServiceDebugBehavior服务行为是如何实现异常的传播的?

    原文:WCF技术剖析之二十四: ServiceDebugBehavior服务行为是如何实现异常的传播的? 服务端只有抛出FaultException异常才能被正常地序列化成Fault消息,并实现向客户 ...

  5. VMware vSphere 服务器虚拟化之二十四 桌面虚拟化之手动池管理物理机

    VMware vSphere 服务器虚拟化之二十四 桌面虚拟化之手动池管理物理机 VMwareView手动池可以管理物理计算机 说明: 环境基于实验二十三 1.准备一台Windows 7的物理计算机名 ...

  6. Bootstrap入门(二十四)data属性

    Bootstrap入门(二十四)data属性 你可以仅仅通过 data 属性 API 就能使用所有的 Bootstrap 插件,无需写一行 JavaScript 代码.这是 Bootstrap 中的一 ...

  7. 3360: [Usaco2004 Jan]算二十四

    3360: [Usaco2004 Jan]算二十四 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 6  Solved: 6[Submit][Statu ...

  8. JAVA之旅(二十四)——I/O流,字符流,FileWriter,IOException,文件续写,FileReader,小练习

    JAVA之旅(二十四)--I/O流,字符流,FileWriter,IOException,文件续写,FileReader,小练习 JAVA之旅林林总总也是写了二十多篇了,我们今天终于是接触到了I/O了 ...

  9. 二十四. Python基础(24)--封装

    二十四. Python基础(24)--封装 ● 知识结构   ● 类属性和__slots__属性 class Student(object):     grade = 3 # 也可以写在__slots ...

随机推荐

  1. BFS vs DFS

    1 Clone Graph   1  copy ervery nodes by bfs  2  add neighbors public UndirectedGraphNode cloneGraph( ...

  2. RobotFramework_3.SeleniumLibrary操作(一)

    RobotFramework_3.SeleniumLibrary操作(一) *:first-child { margin-top: 0 !important; } body>*:last-chi ...

  3. Spring WebClient vs. RestTemplate

    1. 简介 本教程中,我们将对比 Spring 的两种 Web 客户端实现 -- RestTemplate 和 Spring 5 中全新的 Reactive 替代方案 WebClient. 2. 阻塞 ...

  4. HTTP文件上传原理

    前言 对于这块知识点,我一直都是模糊的,不是非常清楚的.在平时的工作中,遇到上传的问题,也没有深入的去研究过,也都是直接用别人封装好的类来完成自己的工作.某一天,看了本书,说到这个知识点,一脸茫然,觉 ...

  5. maven-build-downloading

    1. 场景描述 maven库用的是公司私服和阿里云结合的方式(maven多仓库配置),本项目maven依赖的有其他项目组的jar包(单点登录),但是天有不测风云,依赖单点登录的好几个jar包,在编译( ...

  6. TCP拥塞算法瓶颈及TCP加速器解决方案

    TCP拥塞算法详解    ps:详解TCP拥塞算法就是为了说明瓶颈所在.   先解释一下概念: 拥塞:对网络中某一资源的需求超出了该资源所能提供的可用部分 拥塞窗口:以字节为单位,表示能通过的数据报的 ...

  7. 动态开内存(malloc与calloc)

    malloc与calloc 1.函数原型 #include<stdlib.h> void *malloc(unsigned int size);     //申请size字节的内存 voi ...

  8. 【Python-django后端开发】logging日制配置详解!!!

    官方文档请查看:https://docs.djangoproject.com/en/1.11/topics/logging/ 1. 配置工程日志,在setting.py里,如下 LOGGING = { ...

  9. 【Python-Django定义用户模型类】Python-Django定义用户模型类详解!!!

    定义用户模型类 1. Django默认用户认证系统 Django自带用户认证系统 它处理用户账号.组.权限以及基于cookie的用户会话. Django认证系统位置 django.contrib.au ...

  10. drf之序列化

    在django视图中使用serializer 只是使用serializer类编写API视图,没有用到REST框架 app01下的models.py from django.db import mode ...