TextCNN代码解析

  最近在做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_filters
len(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

以下是一个简单的 TextCNN 模型的代码示例: ```python import tensorflow as tf class TextCNN(object): def __init__(self, sequence_length, num_classes, vocab_size, embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0): 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") l2_loss = tf.constant(0.0) # Embedding layer with tf.device('/cpu:0'), tf.name_scope("embedding"): self.W = tf.Variable(tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0), name="W") self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x) self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1) # Convolution + maxpool layer 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), 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") # 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) # 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(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") # Calculate mean 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 ``` 注释: - `sequence_length`:句子的最大长度。 - `num_classes`:分类的类别数。 - `vocab_size`:词汇表的大小。 - `embedding_size`:嵌入层的维度。 - `filter_sizes`:卷积核的大小列表。 - `num_filters`:每个卷积核的数量。 - `l2_reg_lambda`:L2 正则化系数。 该模型包括以下步骤: 1. 嵌入层:将输入的整数序列转换为嵌入向量。使用 `tf.nn.embedding_lookup()` 函数查找嵌入矩阵中的对应嵌入向量。 2. 卷积层:使用不同大小的卷积核对嵌入向量进行卷积操作。每个卷积核产生一个特征图,表示在句子中找到的某种模式。 3. 池化层:对于每个特征图,使用 max-pooling 操作来提取最显著的特征。 4. Dropout:在全连接层之前,使用 dropout 操作来减少过拟合。 5. 全连接层:将所有特征图连接起来,然后进行分类。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值