当前位置:   article > 正文

【Tensorflow+自然语言处理+RNN】实现中文译英文的智能聊天机器人实战(附源码和数据集 超详细)_基于自然语言处理的闲聊机器人

基于自然语言处理的闲聊机器人

需要源码和数据集请点赞关注收藏后评论区留言私信~~~

一、序列-序列机制概述

Seq2Seq 是一个 Encoder-Decoder 结构的神经网络,它的输入是一个序列(Sequence),输出也是一个序列(Sequence)。在 Encoder 中,将可变长度的序列转变为固定长度的向量表达,Decoder 将这个固定长度的向量转换为可变长度的目标的信号序列。

序列-序列的基本模型包括三个部分,即编码器、解码器以及连接两者的中间状态向量语义编码,编码器通过学习输入,将其编码成固定大小的状态向量,继而将语义编码传给解码器,解码器再通过对状态向量语义编码的学习输出对应的序列 下图是基本工作流程

 

二、注意力机制 

注意力机制与编码器-解码器模型的区别在于不再要求编码器将所有输入信息都编码成固定长度的向量,而是编码成向量的序列。

三、集束搜索概述 

Beam Search(集束搜索)是基于Seq2Seq的一种搜索算法,通常用在解空间比较大的情况下,为了减少搜索所占用的空间和时间,在每一步深度扩展的时候,剪掉一些质量比较差的结点,保留下一些质量较高的结点,这样就减少了空间消耗,并提高了时间效率,其缺点是潜在的最佳方案可能被丢弃

四、张量流智能机器人实战

智能客服系统的主要功能根据应用场景不同而变化,通常包括会话管理、任务管理、模型管理和权限管理等功能。

(1)会话管理:包含会话分类、问题查询以及问题更新等功能。

(2)任务管理:包括任务配置、任务更新、模型配置等。

(3)模型管理:包括模型更新、数据更新以及访问接口等。

(4)权限管理:包括权限控制、角色匹配以及业务对接等。

1:语料预处理

中英文本语料,首先按照行将文本信息切分,如果是英文,则将文本变为小写,然后去掉开始和结尾的空白符并各自加上起始标识符和结束标识符,如果是中文文本,则去掉开始和结尾的空白符直接添加起始和结束标识符

通过将文本映射为索引张量信息,输出部分样本,对比中英文词嵌入处理结果如下

2:训练模型

基于参数配置 训练模型 设置训练轮数为10轮,随着训练轮数增加,损失值逐渐降低

 

 3:测试结果

模型训练结束后 输入中文获得英文翻译结果 部分结果如下图 翻译结果可能会随着训练轮数和训练样本数量发生一定变化

 

 

 

 

 五、代码

部分代码如下 全部代码和数据集请点赞关注收藏后评论区留言私信~~~

  1. import tensorflow as tf
  2. import matplotlib.pyplot as plt
  3. import matplotlib.ticker as ticker
  4. from sklearn.model_selection import train_test_split
  5. import unicodedata
  6. import re
  7. import numpy as np
  8. import os
  9. import io
  10. import time
  11. import pathlib
  12. from matplotlib import rcParams
  13. rcParams['font.family'] = ['Microsoft YaHei']
  14. # 下载文件
  15. path_to_zip = tf.keras.utils.get_file(
  16. 'cmn-eng.txt', origin='https://firebasestorage.googleapis.com/v0/b/marine-order-311008.appspot.com/o/cmn-eng.txt?alt=media&token=4d856d2f-ea8b-4ba4-9ba2-9e9dfb8d4080',
  17. cache_subdir='datasets',extract=False)
  18. path_to_file = pathlib.Path(path_to_zip).parent/'cmn-eng.txt'
  19. #path_to_file = "cmn-eng/cmn.txt"
  20. get_ipython().system('ls /root/.keras/datasets/')
  21. print(pathlib.Path(path_to_zip).parent)
  22. # In[ ]:
  23. # 将 unicode 文件转换为 ascii
  24. def unicode_to_ascii(s):
  25. return ''.join(c for c in unicodedata.normalize('NFD', s)
  26. if unicodedata.category(c) != 'Mn')
  27. def preprocess(text):
  28. reg = re.compile(r'[a-zA-Z,.?]')
  29. if reg.match(text):
  30. text = unicode_to_ascii(text.lower().strip())
  31. text = re.sub(r"([.!:;,])", r" \1 ", text)
  32. text = re.sub(r'[" "]+', " ", text)
  33. text = re.sub(r"[^a-zA-Z?.!,:;]+", " ", text)
  34. text = text.rstrip().strip()
  35. text = '<start> ' + text +' <end>'
  36. return text
  37. # In[ ]:
  38. en_sentence = u"Information Technology has achieved great advancement"
  39. sp_sentence = u"信息技术获得巨大进步"
  40. print(preprocess(en_sentence))
  41. print(preprocess(sp_sentence))
  42. # In[ ]:
  43. # 1. 去除重音符号
  44. # 2. 清理句子
  45. # 3. 返回这样格式的单词对:[ENGLISH, SPANISH]
  46. get_ipython().system('pip install jieba')
  47. import jieba
  48. def corpus(path, no):
  49. lines = io.open(path, encoding='UTF-8').read().strip().split('\n')
  50. english=[]
  51. chinese=[]
  52. out
  53. print(sp[100:120])
  54. # In[ ]:
  55. def max_length(tensor):
  56. return max(len(t) for t in tensor)
  57. # In[ ]:
  58. def tokenize(lang):
  59. lang_tokenizer = tf.keras.preprocessing.text.Tokenizer(
  60. filters='')
  61. lang_tokenizer.fit_on_texts(lang)
  62. tensor = lang_tokenizer.texts_to_sequences(lang)
  63. tensor = tf.keras.preprocessing.sequence.pad_sequences(tensor,
  64. padding='post')
  65. return tensor, lang_tokenizer
  66. # In[ ]:
  67. def load_dataset(path, num_examples=None):
  68. # 创建清理过的输入输出对
  69. targ_lang, inp_lang = corpus(path, num_examples)
  70. input_tensor, inp_lang_tokenizer = tokenize(inp_lang)
  71. target_tensor, targ_lang_tokenizer = tokenize(targ_lang)
  72. return input_tensor, target_tensor, inp_lang_tokenizer, targ_lang_tokenizer
  73. # ### 限制数据集的大小以加快实验速度(可选)
  74. #
  75. #
  76. # 计算目标张量的最大长度 (max_length
  77. max_length_targ, max_length_inp = max_length(target_tensor), max_length(input_tensor)
  78. # In[ ]:
  79. # 采用 80 - 20 的比例切分训练集和验证集
  80. input_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2)
  81. # 显示长度
  82. print(len(input_tensor_train), len(target_tensor_train), len(input_tensor_val), len(target_tensor_val))
  83. # In[ ]:
  84. def convert(lang, tensor):
  85. for t in tensor:
  86. if t!=0:
  87. print ("%d =====> %s" % (t, lang.index_word[t]))
  88. # In[ ]:
  89. print ("待翻译语言:索引值和文本映射")
  90. convert(inp_lang, input_tensor_train[0])
  91. print ()
  92. pri
  93. BUFFER_SIZE = len(input_tensor_train)
  94. BATCH_SIZE = 64
  95. steps_per_epoch = len(input_tensor_train)//BATCH_SIZE
  96. embedding_dim = 256
  97. units = 1024
  98. vocab_inp_size = len(inp_lang.word_index)+1
  99. vocab_tar_size = len(targ_lang.word_index)+1
  100. dataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(BUFFER_SIZE)
  101. dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)
  102. # In[ ]:
  103. example_input_batch, example_target_batch = next(iter(dataset))
  104. example_input_batch.shape, example_target_batch.shape
  105. # In[ ]:
  106. class Encoder(tf.keras.Model):
  107. def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):
  108. super(Encoder, self).__init__()
  109. self.batch_sz = batch_sz
  110. self.enc_raint=None, mask_zero=False, input_length=None,)
  111. #self.gru = tf.keras.layers.GRU(self.enc_units,
  112. # return_sequences=True,
  113. # return_state=True,
  114. # recurrent_initializer='glorot_uniform')
  115. self.gru = tf.keras.layers.GRU(self.enc_units,
  116. return_state=True,
  117. activation='tanh', recurrent_activation='sigmoid',
  118. use_bias=True, kernel_initializer='glorot_uniform',
  119. recurrent_initializer='orthogonal',
  120. bias_initializer='zeros', kernel_regularizer=None,
  121. recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None,
  122. kernel_constraint=None, recurrent_constraint=None, bias_constraint=None,
  123. dropout=0.1, recurrent_dropout=0.1, return_sequences=True,
  124. go_backwards=False, stateful=False, unroll=False, time_major=False,
  125. reset_after=True,)
  126. def call(self, x, hidden):
  127. x = self.embedding(x)
  128. output, state = self.gru(x, initial_state = hidden)
  129. return output, state
  130. def initialize_hidden_state(self):
  131. return tf.zeros((self.batch_sz, self.enc_units))
  132. # In[ ]:
  133. encoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)
  134. # 样本输入
  135. sample_hidden = encoder.initialize_hidden_state()
  136. sample_output, sample_hidden = encoder(example_input_batch, sample_hidden)
  137. print ('Encoder output shape: (batch size, sequence length, units) {}'.format(sample_output.shape))
  138. print ('Encoder Hidden state shape: (batch size, units) {}'.format(sample_hidden.shape))
  139. # In[ ]:
  140. class BahdanauAttention(tf.keras.layers.Layer):
  141. def __init__(self, units):
  142. super(BahdanauAttention, self).__init__()
  143. self.W1 = tf.keras.layers.Dense(units)
  144. self.W2 = tf.keras.layers.Dense(units)
  145. self.V = tf.keras.layers.Dense(1)
  146. def call(self, query, values):
  147. # 隐藏层的形状 == (批大小,隐藏层大小)
  148. # hidden_with_time_axis 的形状 == (批大小,1,隐藏层大小)
  149. # 这样做是为了执行加法以计算分数
  150. hidden_with_time_axis = tf.expand_dims(query, 1)
  151. # 分数的形状 == (批大小,最大长度,1
  152. # 我们在最后一个轴上得到 1, 因为我们把分数应用于 self.V
  153. # 在应用 self.V 之前,张量的形状是(批大小,最大长度,单位)
  154. score = self.V(tf.nn.tanh(
  155. self.W1(values) + self.W2(hidden_with_time_axis)))
  156. # 注意力权重 (attention_weights) 的形状 == (批大小,最大长度,1
  157. attention_weights = tf.nn.softmax(score, axis=1)
  158. # 上下文向量 (context_vector) 求和之后的形状 == (批大小,隐藏层大小)
  159. context_vector = attention_weights * values
  160. context_vector = tf.reduce_sum(context_vector, axis=1)
  161. return context_vector, attention_weights
  162. # In[ ]:
  163. attention_layer = BahdanauAttention(10)
  164. attention_result, attention_weights = attention_layer(sample_hidden, sample_output)
  165. print("Attention result shape: (batch size, units) {}".format(attention_result.shape))
  166. print("Attention weights shape: (batch_size, sequence_length, 1) {}".format(attention_weights.shape))
  167. # In[ ]:
  168. class Decoder(tf.keras.Model):
  169. def __init__(self, vocab_size, embedding_dim, dec_units, batch_sz):
  170. super(Decoder, self).__init__()
  171. self.batch_sz = batch_sz
  172. self.dec_units = dec_units
  173. self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
  174. #self.gru = tf.keras.layers.GRU(self.dec_units,
  175. # return_sequences=True,
  176. # return_state=True,
  177. # recurrent_initializer='glorot_uniform')
  178. self.gru = tf.keras.layers.GRU(self.dec_units,
  179. return_state=True,
  180. activation='tanh', recurrent_activation='sigmoid',
  181. use_bias=True, kernel_initializer='glorot_uniform',
  182. recurrent_initializer='orthogonal',
  183. bias_initializer='zeros', kernel_regularizer=None,
  184. recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None,
  185. kernel_constraint=None, recurrent_constraint=None, bias_constraint=None,
  186. dropout=0.1, recurrent_dropout=0.1, return_sequences=True,
  187. go_backwards=False, stateful=False, unroll=False, time_major=False,
  188. reset_after=True,)
  189. self.fc = tf.keras.layers.Dense(units=vocab_size, activation=None, use_bias=True,
  190. kernel_initializer='glorot_uniform',
  191. bias_initializer='zeros', kernel_regularizer=None,
  192. bias_regularizer=None, activity_regularizer=None, kernel_constraint=None,
  193. bias_constraint=None,)
  194. # 用于注意力
  195. self.attention = BahdanauAttention(self.dec_units)
  196. def call(self, x, hidden, enc_output):
  197. # 编码器输出 (enc_output) 的形状 == (批大小,最大长度,隐藏层大小)
  198. context_vector, attention_weights = self.attention(hidden, enc_output)
  199. # x 在通过嵌入层后的形状 == (批大小,1,嵌入维度)
  200. x = self.embedding(x)
  201. # x 在拼接 (concatenation) 后的形状 == (批大小,1,嵌入维度 + 隐藏层大小)
  202. x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)
  203. # 将合并后的向量传送到 GRU
  204. output, state = self.gru(x)
  205. # 输出的形状 == (批大小 * 1,隐藏层大小)
  206. output = tf.reshape(output, (-1, output.shape[2]))
  207. # 输出的形状 == (批大小,vocab)
  208. x = self.fc(output)
  209. return x, state, attention_weights
  210. # In[ ]:
  211. decoder = Decoder(vocab_tar_size, embedding_dim, units, BATCH_SIZE)
  212. sample_decoder_output, _, _ = decoder(tf.random.uniform((64, 1)),
  213. sample_hidden, sample_output)
  214. print ('Decoder output shape: (batch_size, vocab size) {}'.format(sample_decoder_output.shape))
  215. # ## 定义优化器和损失函数
  216. # In[ ]:
  217. optimizer = tf.keras.optimizers.Adam()
  218. loss_object = tf.keras.losses.SparseCategoricalCrossentropy(
  219. from_logits=True, reduction='none')
  220. def loss_function(real, pred):
  221. mask = tf.math.logical_not(tf.math.equal(real, 0))
  222. loss_ = loss_object(real, pred)
  223. mask = tf.cast(mask, dtype=loss_.dtype)
  224. loss_ *= mask
  225. return tf.reduce_mean(loss_)
  226. # ## 检查点(基于对象保存)
  227. # In[ ]:
  228. checkpoint_dir = './training_checkpoints'
  229. checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
  230. checkpoint = tf.train.Checkpoint(optimizer=optimizer,
  231. encoder=encoder,
  232. decoder=decoder)
  233. # ## 训练
  234. #
  235. # 1. 将 *输入* 传送至 *编码器*,编码器返回 *编码器输出**编码器隐藏层状态*
  236. # 2. 将编码器输出、编码器隐藏层状态和解码器输入(即 *开始标记*)传送至解码器。
  237. # 3. 解码器返回 *预测**解码器隐藏层状态*
  238. # 4. 解码器隐藏层状态被传送回模型,预测被用于计算损失。
  239. # 5. 使用 *教师强制 (teacher forcing)* 决定解码器的下一个输入。
  240. # 6. *教师强制* 是将 *目标词* 作为 *下一个输入* 传送至解码器的技术。
  241. # 7. 最后一步是计算梯度,并将其应用于优化器和反向传播。
  242. # In[ ]:
  243. @tf.function
  244. def train_step(inp, targ, enc_hidden):
  245. loss = 0
  246. with tf.GradientTape() as tape:
  247. enc_output, enc_hidden = encoder(inp, enc_hidden)
  248. dec_hidden = enc_hidden
  249. dec_input = tf.expand_dims([targ_lang.word_index['<start>']] * BATCH_SIZE, 1)
  250. # 教师强制 - 将目标词作为下一个输入
  251. for t in range(1, targ.shape[1]):
  252. # 将编码器输出 (enc_output) 传送至解码器
  253. predictions, dec_hidden, _ = decoder(dec_input, dec_hidden, enc_output)
  254. loss += loss_function(targ[:, t], predictions)
  255. # 使用教师强制
  256. dec_input = tf.expand_dims(targ[:, t], 1)
  257. batch_loss = (loss / int(targ.shape[1]))
  258. variables = encoder.trainable_variables + decoder.trainable_variables
  259. gradients = tape.gradient(loss, variables)
  260. optimizer.apply_gradients(zip(gradients, variables))
  261. return batch_loss
  262. # In[ ]:
  263. EPOCHS = 10
  264. for epoch in range(EPOCHS):
  265. start = time.time()
  266. enc_hidden = encoder.initialize_hidden_state()
  267. total_loss = 0
  268. for (batch, (inp, targ)) in enumerate(dataset.take(steps_per_epoch)):
  269. batch_loss = train_step(inp, targ, enc_hidden)
  270. total_loss += batch_loss
  271. if batch % 100 == 0:
  272. print('第 {}轮 第 {} 批 损失值 {:.3}'.format(epoch + 1,
  273. batch,
  274. batch_loss.numpy()))
  275. # 每 2 个周期(epoch),保存(检查点)一次模型
  276. if (epoch + 1) % 2 == 0:
  277. checkpoint.save(file_prefix = checkpoint_prefix)
  278. print('第 {} 轮 损失值 {:.3f}'.format(epoch + 1,
  279. total_loss / steps_per_epoch))
  280. print('本轮训练时间为 {} 秒 \n'.format(time.time() - start))
  281. # ## 翻译
  282. #
  283. # * 评估函数类似于训练循环,不同之处在于在这里我们不使用 *教师强制*。每个时间步的解码器输入是其先前的预测、隐藏层状态和编码器输出。
  284. # * 当模型预测 *结束标记* 时停止预测。
  285. # * 存储 *每个时间步的注意力权重*
  286. #
  287. # 请注意:对于一个输入,编码器输出仅计算一次。
  288. # In[ ]:
  289. def evaluate(sentence):
  290. attention_plot = np.zeros((max_length_targ, max_length_inp))
  291. sentence = preprocess(sentence)
  292. inputs = [inp_lang.word_index[i] for i in sentence.split(' ')]
  293. inputs = tf.keras.preprocessing.sequence.pad_sequences([inputs],
  294. maxlen=max_length_inp,
  295. padding='post')
  296. inputs = tf.convert_to_tensor(inputs)
  297. result = ''
  298. hidden = [tf.zeros((1, units))]
  299. enc_out, enc_hidden = encoder(inputs, hidden)
  300. dec_hidden = enc_hidden
  301. dec_input = tf.expand_dims([targ_lang.word_index['<start>']], 0)
  302. for t in range(max_length_targ):
  303. predictions, dec_hidden, attention_weights = decoder(dec_input,
  304. dec_hidden,
  305. enc_out)
  306. # 存储注意力权重以便后面制图
  307. attention_weights = tf.reshape(attention_weights, (-1, ))
  308. attention_plot[t] = attention_weights.numpy()
  309. predicted_id = tf.argmax(predictions[0]).numpy()
  310. result += targ_lang.index_word[predicted_id] + ' '
  311. if targ_lang.index_word[predicted_id] == '<end>':
  312. return result, sentence, attention_plot
  313. # 预测的 ID 被输送回模型
  314. dec_input = tf.expand_dims([predicted_id], 0)
  315. return result, sentence, attention_plot
  316. # In[ ]:
  317. # 注意力权重制图函数
  318. from matplotlib.font_manager import FontProperties
  319. get_ipython().system('wget -O taipei_sans_tc_beta.ttf https://drive.google.com/uc?id=1eGAsTN1HBpJAkeVM57_C7ccp7hbgSz3_&export=download')
  320. get_ipython().system('mv taipei_sans_tc_beta.ttf /usr/local/lib/python3.7/dist-packages/matplotlib//mpl-data/fonts/ttf')
  321. # 自定義字體變數
  322. font = FontProperties(fname=r'/usr/local/lib/python3.7/dist-packages/matplotlib/mpl-data/fonts/ttf/taipei_sans_tc_beta.ttf')
  323. def plot_attention(attention, sentence, predicted_sentence):
  324. fig = plt.figure(figsize=(6,6))
  325. ax = fig.add_subplot(1, 1, 1)
  326. ax.matshow(attention, cmap=plt.get_cmap('Purples'))
  327. fontdict = {'fontsize': 14}
  328. ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90, fontproperties=font)
  329. ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict)
  330. ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
  331. ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
  332. plt.show()
  333. # In[ ]:
  334. def translate(sentence):
  335. result, sentence, attention_plot = evaluate(sentence)
  336. print('输入文本: %s' % (sentence))
  337. print('翻译结果: {}'.format(result))
  338. attention_plot = attention_plot[:len(result.split(' ')), :len(sentence.split(' '))]
  339. plot_attention(attention_plot, sentence.split(' '), result.split(' '))
  340. # ## 恢复最新的检查点并验证
  341. # In[ ]:
  342. # 恢复检查点目录 (checkpoint_dir) 中最新的检查点
  343. checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
  344. # In[ ]:
  345. translate('嗨')
  346. # In[ ]:
  347. translate(u'他 不幸 找 不到 工作')
  348. # In[ ]:
  349. translate(u'我 想 打 电话')
  350. # In[ ]:
  351. # In[ ]:
  352. translate(u'运动 有利 健康')
  353. # In[ ]:
  354. translate(u'我 相信 你 的 判断')
  355. # In[ ]:
  356. translate(u'应该 了解 相应 的 规则')
  357. # In[ ]:
  358. translate(u'我们 终于 达到 了 目标')
  359. # In[ ]:

创作不易 觉得有帮助请点赞关注收藏~~~

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

闽ICP备14008679号