初学tensorflow, 发现网上坑太多了,各种版本的滞后,一下代码这样写,一下代码那样写~~很多都是老的书写方式! 走了许许多多的弯路,所以想整理一下最新的版本来梳理一下,也可以自己未来回顾的时候有个参考!
注: 现在最新版本是 tensorflow1.9 的版本, 我自己安装的是 1.8的! 所以本文代码肯定适用1.8版本! 1.9应该也适用~~并没有多少改动这方面的代码
tensorflow是什么么,基础的概念我就不重复了,一点都不懂的请去看基础教程自己学习! 本文主要以seq2seq 做NLP方面的讲解, 如果你也跟我一样是从 普通神经网络--卷积神经网络--循环神经网络的步骤走过来的话, 一些基本概念应该也都能明白
做初级的 NLP 主要分为以下几个步骤:
1. sample 文本数据的处理
2. seq2seq encoder
3. seq2seq decoder
4. train model
5. prediciting
本文跳过文本处理的代码阶段,主要讲 encoder decoder的构建方面, 文本方面的处理会稍微带过一下
一、文本处理
首先你需要有一些sample的数据,可能是英文、中文等等各种文本,里面也可能有各种符号等等
比如聊天机器人的文本, 第一行是问,第二行是答, 第三行是问,第四行是答 这样依此类推下去, 你要做的就是讲这个文本进行处理,无论使用 python的基本语法还是用一些python工具模块 nltk 等来处理文本,最终要讲文本处理成 input_source , output_target这样两个大类, input_source 就是所有问的语句 一行代表一句问. output_target就是所有答的语句 也是一行一句答. 类似于基本的神经网络里 X, Y 这样的数据! 当然分好后,你还要对input_source output_target做一些处理 比如取掉一些没用的特殊字符等,就是要保留纯英文(中午)等,还有记得去除每个行尾巴的 '\n'符号
这时候 你经过处理的到了纯净的 input_source, output_target 然后你就要用这两个内容去做 word_to_int int_to_word这两个方面的转换了 source 和target都要做这方面的转换 然后你的到 input_source_int output_target_int 类似这样的 纯数字的东西~~ 也是一样的 一行就代表一个sample 一个target 这样的数据就可以 用到 encoder decoder里面了!
文本处理方面不是本文重点,只是讲了大概要做的处理 最终就是讲文本变成 [1,32,4123,4121,53,56,78......] 类似这样的东西 因为每句话的长度大小都不一定,以及一些其他问题 所以这时候就会有 <PAD>, <UNK>,<EOS>,<GO>这些特殊的符号也要加入进来 当然这些特殊的符号也是转换成特定的数字加入到 input_source_int output_target_int里面来! 详细的操作代码方面,我下回有空了整理一下 专门开一篇文章来介绍如何处理.
二、seq2seq encoder
seq2seq 的原理本文就不介绍了,相信有太多的文章会很详细的介绍,然后画一大堆图以及数学公式来告诉你如何实现, 那些数学公式基本上数学差的人是看不懂的,看懂了也记得不~~~ 所以本文主要从代码方面介绍, 详细的理论方面请google~~~
seq2seq 分为两大部分, 一个是encoder部分 另一个是decoder部分,我们先讲encoder部分:
def get_encoder_layer(input_data, source_vocab_size,encoding_embedding_size,rnn_size,source_sequence_length, num_layers):
encoder_embed_input = tf.contrib.layers.embed_sequence(input_data, source_vocab_size, encoding_embedding_size)
def get_signle_cell(rnn_size):
cell = tf.contrib.rnn.LSTMCell(rnn_size)
return cell
rnn_cell = tf.contrib.rnn.MultiRNNCell([get_signle_cell(rnn_size) for _ in range(num_layers)])
encoder_output,encoder_state = tf.nn.dynamic_rnn(rnn_cell,encoder_embed_input,source_sequence_length, dtype=tf.float32)
return encoder_output, encoder_state
上面这部分代码就是encoder层的全部代码了~~ 各个参数当然是之前定义好的 我这里讲解一下
input_data 就是通过batch的 input_source_int