一、卷积网络在NLP上的运用简析
1、输入:句子或文档
类似于图片处理需要将图片转化成矩阵形式,矩阵中的向量代表的是像素点,同样应用到文本上是每行为单词向量[5],通常得到这种向量的处理方式是WordEmbeding(低维表示,不懂参考解释),常用的方法有:word2vec或者GloVe也可以是Onehot形式形成单词索引。
2、算法模型:卷积网络
区别于图像处理,卷积网络通过窗口在局部区域滑动获取卷积运算后的值,对于文本中窗口大小的选择,其宽度通常与输入矩阵宽度相同,高度或区域大小可能不同,但一次滑动窗口通常设置超过2-5个单词。还需要注意的是,对于图像来说通道设置为RGB,文本来说具体的通道需要根据实际方法而定
二、论文实例(Convolutional Neural Networks for Sentence Classification)
代码链接
文章链接
特点:词向量和深度学习结合实现文本分类
这里这要借鉴实现原理及代码
1.输入:为词向量从上到下排序的矩阵(width-最长句子词向量长,height-embeding设置值)。
矩阵的类型有静态(static)和非静态(non-static)方式。static方式采用比如word2vec预训练的词向量,训练过程不更新词向量,实质上属于迁移学习了,特别是数据量比较小的情况下,采用静态的词向量往往效果不错。non-static则是在训练过程中更新词向量。推荐的方式是 non-static 中的 fine-tunning方式,它是以预训练(pre-train)的word2vec向量初始化词向量,训练过程中调整词向量,能加速收敛,当然如果有充足的训练数据和资源,直接随机初始化词向量效果也是可以的。
处理方式:CNN处理图片的方式是左右滑动窗口,处理文本是上下,类似于N-Gream的方式,这里的N即embeding值,比如:每两行卷积一次就是2-gream。
2.卷积网络参数:从n-gream的角度看,n的取值范围通常取2,3,4,这里卷积核的大小取的是(2,3,4)数量分别为100,100,100,总共为300个卷积核
3.输出:情绪分类结果,这里作者用的数据集中有两种情绪(积极、消极,即二分类)
三、code分析
1、数据处理
输入数据为rt-polarity.neg和rt-polarity.pos,包含摘自影评得到英文评论。
主要模块如下:
def load_data_and_labels(positive_data_file, negative_data_file):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
加载数据文件,生成对应标签,清洗数据,合并分别生成数据文件和标签文件
"""
# Load data from files
positive_examples = list(open(positive_data_file, "r", encoding='utf-8').readlines())
# delete blank mark('\n','\r','\t',''),s.strip(something)
positive_examples = [s.strip() for s in positive_examples]
negative_examples = list(open(negative_data_file, "r", encoding='utf-8').readlines())
negative_examples = [s.strip() for s in negative_examples]
# Split by words
x_text = positive_examples + negative_examples
# merge to one text
x_text = [clean_str(sent) for sent in x_text]
# Generate labels,second classification
positive_labels = [[0, 1] for _ in positive_examples]
negative_labels = [[1, 0] for _ in negative_examples]
# merge to one label text
y = np.concatenate([positive_labels, negative_labels], 0)
return [x_text, y]
清洗数据过程如下:
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
"""
#sub正则替换函数,除A-Za-z0-9(),!?'`外的字符,去除
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
#\'s替换成 \'s(加空格)
string = re.sub(r"\'s", " \'s", string)
string = re.sub(r"\'ve", " \'ve", string)
string = re.sub(r"n\'t", " n\'t", string)
string = re.sub(r"\'re", " \'re", string)
string = re.sub(r"\'d", " \'d", string)
string = re.sub(r"\'ll", " \'ll", string)
string = re.sub(r",", " , ", string)
string = re.sub(r"!", " ! ", string)
string = re.sub(r"\(", " \( ", string)
string = re.sub(r"\)", " \) ", string)
string = re.sub(r"\?", " \? ", string)
#两个以上连续的空白符,删除
string = re.sub(r"\s{2,}", " ", string)
return string.strip().lower()
python的re模块(正则表达式)详解
2、网络模型
嵌入层、卷积层、池化层、Dropout层、预测层
1.初始化参数:
sequence_length, num_classes, vocab_size,embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0
2.封装的embedding层:
它将词汇词索引映射到低维向量表示中。 它本质上是一个从数据中学习的查找表。
#封装embedding层
with tf.device('/cpu:0'), tf.name_scope("embedding"):
self.W = tf.Variable(
#self.W可以理解为词向量词典,vocab_size为max_document_length,随机初始化为(-1,1)
tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),
name="W")
#params中查找与ids对应的表示。W中查找self.input_x对应的表示
self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)
#self.embedded_chars_expanded:将词向量表示扩充一个维度(embedded_chars * 1)
#维度变为[句子数量, sequence_length, embedding_size, 1]
self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)
3.卷积层和池化层:
for i, filter_size in enumerate(filter_sizes):
with tf.name_scope("conv-maxpool-%s" % filter_size):
# Convolution Layer
filter_shape = [filter_size, embedding_size, 1, num_filters]
W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")
conv = tf.nn.conv2d(
self.embedded_chars_expanded,
W,
strides=[1, 1, 1, 1],
padding="VALID",
name="conv")
# Apply nonlinearity
h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
pooled = tf.nn.max_pool(
h,
ksize=[1, sequence_length - filter_size + 1, 1, 1],
strides=[1, 1, 1, 1],
padding='VALID',
name="pool")
pooled_outputs.append(pooled)
# Combine all the pooled features,get from three filters
num_filters_total = num_filters * len(filter_sizes)
self.h_pool = tf.concat(pooled_outputs, 3)
self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])
这里需要注意多个filter的迭代写法,同样看出TensorFlow的灵活性。其中h是将非线性应用于卷积输出的结果。 每个过滤器在整个嵌入中滑过,但是它涵盖的字数有所不同。 “VALID”填充意味着我们将过滤器滑过我们的句子而不填充边缘,执行一个窄的卷积,给出一个形状[1,sequence_length - filter_size + 1,1,1]的输出。 在特定过滤器大小的输出上执行最大化池将留下一张张量[batch_size,1,num_filters]。 这本质上是一个特征向量,其中最后一个维度对应于我们的特征。 一旦我们从每个过滤器大小得到所有的汇集输出张量,我们将它们组合成一个长形特征向量[batch_size,num_filters_total]。 在tf.reshape中使用-1可以告诉TensorFlow在可能的情况下平坦化维度。
4.Dropout层及预测:
# Add dropout
with tf.name_scope("dropout"):
self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)
# Final (unnormalized) scores and predictions
with tf.name_scope("output"):
W = tf.get_variable(
"W",
shape=[num_filters_total, num_classes],
initializer=tf.contrib.layers.xavier_initializer())
b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b")
l2_loss += tf.nn.l2_loss(W)
l2_loss += tf.nn.l2_loss(b)
self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores")
self.predictions = tf.argmax(self.scores, 1, name="predictions")
使用max-pooling(with dropout )的特征向量,我们可以通过执行矩阵乘法并选择具有最高分数的类来生成预测。 也可以应用softmax函数将原始分数转换为归一化概率。这里,tf.nn.xw_plus_b是执行Wx + b矩阵乘法。
2、训练文件
1.固定参数设置
# Parameters
====================================
# Data loading params
#10% of database is used to do verification
tf.flags.DEFINE_float("dev_sample_percentage", .1, "Percentage of the training data to use for validation")
tf.flags.DEFINE_string("positive_data_file", "./data/rt-polaritydata/rt-polarity.pos", "Data source for the positive data.")
tf.flags.DEFINE_string("negative_data_file", "./data/rt-polaritydata/rt-polarity.neg", "Data source for the negative data.")
# Model Hyperparameters
tf.flags.DEFINE_integer("embedding_dim", 128, "Dimensionality of character embedding (default: 128)")
tf.flags.DEFINE_string("filter_sizes", "3,4,5", "Comma-separated filter sizes (default: '3,4,5')")
tf.flags.DEFINE_integer("num_filters", 128, "Number of filters per filter size (default: 128)")
tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)")
tf.flags.DEFINE_float("l2_reg_lambda", 0.0, "L2 regularization lambda (default: 0.0)")
# Training parameters
tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)")
tf.flags.DEFINE_integer("num_epochs", 200, "Number of training epochs (default: 200)")
tf.flags.DEFINE_integer("evaluate_every", 100, "Evaluate model on dev set after this many steps (default: 100)")
tf.flags.DEFINE_integer("checkpoint_every", 100, "Save model after this many steps (default: 100)")
tf.flags.DEFINE_integer("num_checkpoints", 5, "Number of checkpoints to store (default: 5)")
# Misc Parameters
tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement")
tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices")
FLAGS = tf.flags.FLAGS
flag函数定义传参的方式值得借鉴
2.训练数据测试数据处理过程
def preprocess():
# Data Preparation
# ==================================================
# Load data
print("Loading data...")
x_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)
# Build vocabulary
max_document_length = max([len(x.split(" ")) for x in x_text])
vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)
x = np.array(list(vocab_processor.fit_transform(x_text)))
# Randomly shuffle data
np.random.seed(10)
shuffle_indices = np.random.permutation(np.arange(len(y)))
x_shuffled = x[shuffle_indices]
y_shuffled = y[shuffle_indices]
# Split train/test set
# TODO: This is very crude, should use cross-validation
dev_sample_index = -1 * int(FLAGS.dev_sample_percentage * float(len(y)))
x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]
y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]
del x, y, x_shuffled, y_shuffled
print("Vocabulary Size: {:d}".format(len(vocab_processor.vocabulary_)))
print("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev)))
return x_train, y_train, vocab_processor, x_dev, y_dev
这里训练集和数据集的比例是9:1,此外对于数据集小的可以采用K折交叉验证(参看sklearn函数)
tensorflow的训练结构是常见形式,作者还加了summary模块,用于tensorboard进行可视化显示
grad_summaries = []
for g, v in grads_and_vars:
if g is not None:
grad_hist_summary = tf.summary.histogram("{}/grad/hist".format(v.name), g)
sparsity_summary = tf.summary.scalar("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g))
grad_summaries.append(grad_hist_summary)
grad_summaries.append(sparsity_summary)
grad_summaries_merged = tf.summary.merge(grad_summaries)
# Output directory for models and summaries
timestamp = str(int(time.time()))
out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp))
print("Writing to {}\n".format(out_dir))
# Summaries for loss and accuracy
loss_summary = tf.summary.scalar("loss", cnn.loss)
acc_summary = tf.summary.scalar("accuracy", cnn.accuracy)
# Train Summaries
train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged])
train_summary_dir = os.path.join(out_dir, "summaries", "train")
train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph)
# Dev summaries
dev_summary_op = tf.summary.merge([loss_summary, acc_summary])
dev_summary_dir = os.path.join(out_dir, "summaries", "dev")
dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)
将最终训练好的模型存成.ckpt文件
3、测试文件
word2vec 词袋化,这块不是很懂,以后遇见再补。
# Map data into vocabulary
# 词向量存放路径并取出,词向量就是打开模型这台车的钥匙
vocab_path = os.path.join(FLAGS.checkpoint_dir, "..", "vocab")
vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)
# 测试语料,写入一个array,依次串行写入
x_test = np.array(list(vocab_processor.transform(x_raw)))
参考链接:
[1] 作者解读
[2] 其他解读
[3] 卷积神经网络CNN在自然语言处理中的应用
[4] N-Gram模型详解
[5] 词向量及Word2vec的理解
[6] code分析参考