最近在做TextCNN的代码复现,遇到了许多问题,虽然到目前为止还没有清楚的明白每一条语句的功能,但是我想边写边看,这样总比一直钻牛角尖要快的多。
我这次的代码上传至Github:https://github.com/lee-mq/sentiment_analysis_textcnn-master
我将从每个文档的功能进行描述,对每句话的功以及设计到的函数进行总结概况。以下的学习笔记均是个人的理解,如果有错误欢迎大佬指正。
data_input_helper.py
这部分的功能是数据抽取、分割。
首先就是import 部分:
import numpy as np
import re
import word2vec
这里导入了三个包,numpy、re、word2vec:
numpy就是一种大型的计算软件基础包。如果要进行线性运算、傅里叶变化、排序等操作,numpy就可以实现。
re:全程regular expression,即正则表达式。它是一种搜索指定字符串的包。
word2vec:这个就不用多介绍了,经典的词向量模型。
if __name__ == "__main__":
x_text, y = load_data_and_labels(r'C:\Users\12967\Desktop\sentiment_analysis_textcnn-master\chineseStopWords.txt')
print (len(x_text))
作为小白的我刚刚开始找了半天主函数在哪里,不然就像一个线球一样找不到头。python中和C语言不同,不会直接明了的写出main(),它通过__name__ == "main"语句表示当运行python文件的时候,这个是我的入口。接下来定义了x_text和y,在定义y的时候调用了load_data_and_labels()函数,下面我们就跳到def load_data_and_labels()查看这个函数实现了什么。最后的print语句输出了x_text的长度。
def load_data_and_labels(filepath,max_size = -1):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
# Load data from files
train_datas = []
with open(filepath, 'r', encoding='utf-8',errors='ignore') as f:
train_datas = f.readlines()
one_hot_labels = []
x_datas = []
for line in train_datas:
parts = line.split('\t',1)
if(len(parts[1].strip()) == 0):
continue
x_datas.append(parts[1])
if parts[0].startswith('0') :
one_hot_labels.append([0,1])
else:
one_hot_labels.append([1,0])
print (' data size = ' ,len(train_datas))
# Split by words
# x_text = [clean_str(sent) for sent in x_text]
return [x_datas, np.array(one_hot_labels)]
我们看到load_data_and_labels()中它要求传入两个量:filepath和max_size=-1(这个以及定义好,不需要传入),那么我们就理解了在上一部分__name__ == "main"中有一大串的文件地址(地址前面加r是防止\识别为转义字符),就是为了传入def load_data_and_labels()里面,这时的filepath就相当于是那个地址了。然后它定义了一个列表train_datas;with open()是读取文件的功能语句,它的意思是:打开filepath,用read(读)的方式,编码方式为utf-,如果打开错误(文件不存在)就忽略,我们把这个文件叫做f;在打开后有进行了一条语句的操作,readlines()函数是读取文档中的每一行数据,读完整个文件,这时train_datas列表里就变成了文档中每行内容;之后它定义了one_hot_labels列表和x_datas列表;用line遍历刚刚填满的train_datas,每一个line以制表符分隔,分成两个,并把分割结果交给parts;如果parts列表的最后一项为去除空格后如果是0,那就继续分割;将分割好的parts列表加到x_datas;如果parts的第一项是以0开头的,就在one_hot_labels列表后加入[0,1],否则就在后面加入[1,0]。最后打印出data size也就是train_datas的长度;最终返回x_datas(分割后的数据列表)与one_hot_labels矩阵。
那么在data_input_helper.py中的主函数调用部分就结束了,里面还有部分定义的函数没有说,将在调用的时候理解。
eval.py
这个文件的作用起初我也是很困惑,为什么多了一个这个文件?它是干嘛呢?经过查询,这个文件并不是空穴来风:
用tensorflow训练模型时,很自然的想到要同时验证模型的效果,得到mAP、loss等参数,从而判断什么时候可以终止训练,防止欠拟合或者过拟合。幸运的是,tensorflow官方已经给出了验证的脚本eval.py。
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_input_helper as data_helpers //导入分词的代码
from text_cnn import TextCNN //导入TextCNN模型
from tensorflow.contrib import learn //建立输入函数的方法
import csv //写入csv文件
这里先列出导入的包,值得注意的时它导入了data_input_helper。
if __name__ == "__main__":
w2v_wr = data_helpers.w2v_wrapper(FLAGS.w2v_file)
eval(w2v_wr.model)
老规矩,我还是先找到了_name_=“main”,它定义了w2r_wr,调用了data_helpers代码中的w2v_wrapper定义的函数,把FLAGS.w2v_file传传递给函数,我们先看它传了个什么东西?
# Data Parameters
tf.flags.DEFINE_string("valid_data_file", "../data/cutclean_label_corpus10000.txt", "Data source for the positive data.")
tf.flags.DEFINE_string("w2v_file", "../data/vectors.bin", "w2v_file path") //条到这条语句
这就不得不说以下Tensorflow中FLAGS函数的总用:它是用来统一更改代码中的参数的。FLAGS有三种基本参数:flags.DEFINE_integer、flags.DEFINE_float、flags.DEFINE_boolean;在函数中,第一个是参数名,第二个是参数默认值,第三个是参数描述。那么在上面语句的意思为:它定义了w2v_file的参数名,它的默认值是data/vectors.bin,对它的描述是w2v_file的路径。我们可以理解为:w2v_file=/data/vectors.bin。将这个路径传递给了data_helpers中的w2v_wappers函数:
class w2v_wrapper:
def __init__(self,file_path):
# w2v_file = os.path.join(base_path, "vectors_poem.bin")
self.model = word2vec.load(file_path)
if 'unknown' not in self.model.vocab_hash:
unknown_vec = np.random.uniform(-0.1,0.1,size=128)
self.model.vocab_hash['unknown'] = len(self.model.vocab)
self.model.vectors = np.row_stack((self.model.vectors,unknown_vec))
将地址传递给file_path,那么它的值就是w2v_file一样,都为/data/vectors.bin。那么接下来就是word2vec的模型加载。
将加载好的模型传给w2v_wr,执行下一条语句:
if __name__ == "__main__":
w2v_wr = data_helpers.w2v_wrapper(FLAGS.w2v_file)
eval(w2v_wr.model)
这里将word2vec模型传给了eval()函数:
def eval(w2v_model):
# Evaluation
# ==================================================
checkpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)
graph = tf.Graph()
with graph.as_default():
session_conf = tf.ConfigProto(
allow_soft_placement=FLAGS.allow_soft_placement,
log_device_placement=FLAGS.log_device_placement)
sess = tf.Session(config=session_conf)
with sess.as_default():
# Load the saved meta graph and restore variables
saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file))
saver.restore(sess, checkpoint_file)
# Get the placeholders from the graph by name
input_x = graph.get_operation_by_name("input_x").outputs[0]
dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0]
# Tensors we want to evaluate
predictions = graph.get_operation_by_name("output/predictions").outputs[0]
x_test, y_test = load_data(w2v_model,1290)
# Generate batches for one epoch
batches = data_helpers.batch_iter(list(x_test), FLAGS.batch_size, 1, shuffle=False)
# Collect the predictions here
all_predictions = []
for x_test_batch in batches:
batch_predictions = sess.run(predictions, {input_x: x_test_batch, dropout_keep_prob: 1.0})
all_predictions = np.concatenate([all_predictions, batch_predictions])
# Print accuracy if y_test is defined
if y_test is not None:
correct_predictions = float(sum(all_predictions == y_test))
print("Total number of test examples: {}".format(len(y_test)))
print("Accuracy: {:g}".format(correct_predictions/float(len(y_test))))
# Save the evaluation to a csv
predictions_human_readable = np.column_stack(all_predictions)
out_path = os.path.join(FLAGS.checkpoint_dir, "..", "prediction.csv")
print("Saving evaluation to {0}".format(out_path))
with open(out_path, 'w') as f:
csv.writer(f).writerows(predictions_human_readable)
text_cnn.py
这时cnn模型,整个代码的核心。
import tensorflow as tf
import numpy as np
首先导入了tensorflow和numpy包。
class TextCNN(object):
"""
A CNN for text classification.
Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.
"""
def __init__(
self,w2v_model, sequence_length, num_classes, vocab_size,
embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0):
首先定了TextCNN类,在类中又定义了_init_进行初始化:
w2v_model:预训练模型
sequence_length:这是指句子的规定长度,在CNN中每个句子的长度是一致的,如果出现不一致的情况会取最长句子为规定长度,较短句子用0补齐。
num_classes:输出文本类别的个数。
vocab_size:文中出现了多少词。
embedding_size:词向量长度用一个多大维的向量来表示词语。
filter_sizes:卷积核的大小list
num_filters:每个卷积核对应的卷积核个数。
# Placeholders for input, output and dropout
self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x")
self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y")
self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")
# Keeping track of l2 regularization loss (optional)
l2_loss = tf.constant(0.0)
这里定义了输入和输出和drop_out比例的占位符,设立了L2这个损失变量,每当计算出现误差后就用当时的L2×权值加入到l2_loss中。
# Embedding layer
with tf.device('/cpu:0'), tf.name_scope("embedding"):
if w2v_model is None:
self.W = tf.Variable(
tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),
name="word_embeddings")
else:
self.W = tf.get_variable("word_embeddings",
initializer=w2v_model.vectors.astype(np.float32))
self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)
self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)
这里我们使用的word2vec进行预训练生成词向量;同时我还寻找了一个没有用word2vec模型训练的模块,进行对比:
#Embedding layer
with tf.device('/cpu:0'),tf.name_scope("embedding")
w=tf.Variable(
tf.random_uniform([vocab_size,embedding_size],-1.0,-1.0),name="w")
self.embedded_chars=tf.nn.embedding_lookup(W,self.input_x)
self.embedded_chars_expanded=tf.expand_dims(self.embedded_chars,-1)
对比这两端代码,不同之处就在于word_vec模块引入了if语句,如果满足word2_vec=none,那么就用word2vec进行预训练分词。
# Create a convolution + maxpool layer for each filter size
pooled_outputs = []
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),dtype=tf.float32, name="W")
b = tf.Variable(tf.constant(0.1, shape=[num_filters]),dtype=tf.float32, 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")
# Maxpooling over the outputs
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)
这部分是实现在论文中的增加一个维度,适应在卷积中匹配CNN的输入。
# Combine all the pooled features
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])
# 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(b)
self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores")
self.predictions = tf.argmax(self.scores, 1, name="predictions")
建立了一个pooled_outputs来保存每次卷积结果,在不同的卷积核大小进行卷积、relu激活函数和max_pool的操作后得到pooled,需要注意的是这里的几个设置,池化和卷积中的padding和strides,这里设置的池化和卷积保证了每段文本输出为num_filterslen(filters_sizes)个数字。
然后将pooled_outputs中的值全部取出来然后reshape成[len(input_x),num_filterslen(filters_size)],然后进行了dropout层防止过拟合,最后再添加了一层全连接层与softmax层将特征映射成不同类别上的概率。(引用)
# CalculateMean cross-entropy loss
with tf.name_scope("loss"):
losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)
self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss
# Accuracy
with tf.name_scope("accuracy"):
correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
最后就是损失函数使用的交叉熵加上L2损失,和准确度。
train.py
我们先来看一下导入的包:
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_input_helper as data_helpers
from text_cnn import TextCNN
import math
from tensorflow.contrib import learn
这里将data_input_helper和模型text_cnn导入。
从主函数开始:
if __name__ == "__main__":
w2v_wr = data_helpers.w2v_wrapper(FLAGS.w2v_file)
train(w2v_wr.model)
首先对w2v_wr定义,再嵌套里有一个FLAGS,我们先看看这个的意义:
tf.flags.DEFINE_string("w2v_file", "../data/vectors.bin", "w2v_file path")
这里就是对w2v_file进行了一个定义,并解释了它是w2v_file的路径。那么它将这个地址传给了data_helpers下定义的w2v_wrapper(),之前说过了w2v_wrapper的功能是:加载word2vec模型
参考文献
eval.py使用方法:https://blog.csdn.net/zong596568821xp/article/details/84842688
tf.FLAGS的简介:https://blog.csdn.net/qq_41185868/article/details/82913886?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
word2vec中Vocab_hash介绍:https://blog.csdn.net/juanjuan1314/article/details/51971563
Text_cnn代码解析:http://www.voidcn.com/article/p-taekwagd-brb.html