实体命名识别详解(三)

train_data.py

老规矩,先放代码。

from model.config import Config
from model.data_utils import CoNLLDataset, get_vocabs, UNK, NUM, \
    get_glove_vocab, write_vocab, load_vocab, get_char_vocab, \
    export_trimmed_glove_vectors, get_processing_word


def main():
    """Procedure to build data

    You MUST RUN this procedure. It iterates over the whole dataset (train,
    dev and test) and extract the vocabularies in terms of words, tags, and
    characters. Having built the vocabularies it writes them in a file. The
    writing of vocabulary in a file assigns an id (the line #) to each word.
    It then extract the relevant GloVe vectors and stores them in a np array
    such that the i-th entry corresponds to the i-th word in the vocabulary.


    Args:
        config: (instance of Config) has attributes like hyper-params...

    """
    # get config and processing of words
    config = Config(load=False)
    processing_word = get_processing_word(lowercase=True)

    # Generators
    # 获取训练集、测试集、开发集
    dev   = CoNLLDataset(config.filename_dev, processing_word)
    test  = CoNLLDataset(config.filename_test, processing_word)
    train = CoNLLDataset(config.filename_train, processing_word)

    # Build Word and Tag vocab
    vocab_words, vocab_tags = get_vocabs([train, dev, test])
    vocab_glove = get_glove_vocab(config.filename_glove)

    vocab = vocab_words & vocab_glove
    vocab.add(UNK)
    vocab.add(NUM)

    # Save vocab
    write_vocab(vocab, config.filename_words)
    write_vocab(vocab_tags, config.filename_tags)

    # Trim GloVe Vectors
    vocab = load_vocab(config.filename_words)
    export_trimmed_glove_vectors(vocab, config.filename_glove,
                                config.filename_trimmed, config.dim_word)

    # Build and save char vocab
    train = CoNLLDataset(config.filename_train)
    vocab_chars = get_char_vocab(train)
    write_vocab(vocab_chars, config.filename_chars)


if __name__ == "__main__":
    main()

这是一个封装好各个模块的main函数。
首先这里引用了model文件夹下的config.py和data_utils.py文件下的几个类、变量和函数。
看一下整体介绍。

    """Procedure to build data

    You MUST RUN this procedure. It iterates over the whole dataset (train,
    dev and test) and extract the vocabularies in terms of words, tags, and
    characters. Having built the vocabularies it writes them in a file. The
    writing of vocabulary in a file assigns an id (the line #) to each word.
    It then extract the relevant GloVe vectors and stores them in a np array
    such that the i-th entry corresponds to the i-th word in the vocabulary.


    Args:
        config: (instance of Config) has attributes like hyper-params...

    """

 这是一个建立数据的过程。你必须执行这个过程,它遍历整个数据集(训练集、开发集和测试集),从words,tags,characters中提取词汇集【这句什么意思不太懂,具体看了代码才知道】。并将建立好的词汇集存储到文件中。该词汇集给其中的每一个word分配一个id,然后提取其中的Glove向量将其存储到numpy数组中去,使第i项对应于词汇表中第i个单词。
参数:config,这是Config类的一个实例,具有一些属性如超参数。

    # get config and processing of words
    config = Config(load=False)
    processing_word = get_processing_word(lowercase=True)

获取配置和对words进行处理。

  • 第一句,实例化一个Config类,并将load参数设为False。
    Config这个类有些复杂,我们先看一下它的大致介绍,具体函数等先往后稍稍。
class Config():
    def __init__(self, load=True):
        """Initialize hyperparameters and load vocabs

        Args:
            load_embeddings: (bool) if True, load embeddings into
                np array, else None

        """
        # directory for training outputs
        if not os.path.exists(self.dir_output):
            os.makedirs(self.dir_output)

        # create instance of logger
        self.logger = get_logger(self.path_log)

        # load if requested (default)
        if load:
            self.load()

这是Config类的初始化函数,看一下介绍,初始化超参数,并且加载vocabs。
类有一个布尔类型的超参数load,如果为True,加载词向量到numpy数组中,否则的话就不用了。
这里由于我们是初次创建,很明显还没有词向量,故config = Condig(load=False)
所以简而言之,这一句话就是加载我们模型需要的全部超参数。。。emmm目前来看是这个意思。

  • 第二句
    get_processing_word()函数,获得加工后的数据,我们进这个函数看一下。
    这是data_utils.py下的一个函数。
def get_processing_word(vocab_words=None, vocab_chars=None,
                    lowercase=False, chars=False, allow_unk=True):
    """Return lambda function that transform a word (string) into list,
    or tuple of (list, id) of int corresponding to the ids of the word and
    its corresponding characters.

    Args:
        vocab: dict[word] = idx

    Returns:
        f("cat") = ([12, 4, 32], 12345)
                 = (list of char ids, word id)

    """
    def f(word):
        # 0. get chars of words
        if vocab_chars is not None and chars == True:
            char_ids = []
            for char in word:
                # ignore chars out of vocabulary
                if char in vocab_chars:
                    char_ids += [vocab_chars[char]]

        # 1. preprocess word
        if lowercase:
            word = word.lower()
        if word.isdigit():
            word = NUM

        # 2. get id of word
        if vocab_words is not None:
            if word in vocab_words:
                word = vocab_words[word]
            else:
                if allow_unk:
                    word = vocab_words[UNK]
                else:
                    raise Exception("Unknow key is not allowed. Check that "\
                                    "your vocab (tags?) is correct")

        # 3. return tuple char ids, word id
        if vocab_chars is not None and chars == True:
            return char_ids, word
        else:
            return word

    return f

emmm,很奇怪的一种格式,函数里面嵌套了一个函数,并且返回值也是这个函数。
查了一下,这是Python的闭包函数,函数中嵌套函数,外包函数返回的是内包函数的引用。
关于闭包函数,这里有一篇文章讲的很好,今后我也会针对闭包函数专门出一章讲解。
先看这个函数的介绍,它返回的是一个lambda function,即一个匿名函数。也就是说,这个函数返回的是另一个内嵌函数的引用。我们看到它里面定义了一个形参为word的函数f,返回值也是f,这就是说它返回了一个引用。
再来看看之前这句话

    processing_word = get_processing_word(lowercase=True)

所以processing_word不是一个变量,而是一个函数的引用!!
所以看一下f(word)函数体:

    def f(word):
        # 0. get chars of words
        if vocab_chars is not None and chars == True:
            char_ids = []
            for char in word:
                # ignore chars out of vocabulary
                if char in vocab_chars:
                    char_ids += [vocab_chars[char]]

        # 1. preprocess word
        if lowercase:
            word = word.lower()
        if word.isdigit():
            word = NUM

        # 2. get id of word
        if vocab_words is not None:
            if word in vocab_words:
                word = vocab_words[word]
            else:
                if allow_unk:
                    word = vocab_words[UNK]
                else:
                    raise Exception("Unknow key is not allowed. Check that "\
                                    "your vocab (tags?) is correct")

        # 3. return tuple char ids, word id
        if vocab_chars is not None and chars == True:
            return char_ids, word
        else:
            return word
  • 如果vocab_chars非空且chars == True(如果字符表非空且字符非空??),于是建立了一个char_ids列表。然后遍历整个单词,以字符为单位,如果该字符在字符表中呢,就往char_ids列表里增加该字符的位置。
    我貌似懂了,这个其实就是对单词进行数据清洗:扔掉那些特殊符号的字符,并且给每个单词构建一个以字符为单位的映射!,把每个单词用向量的形式表现出来,如dog,映射为【4,15,7】(这是自己瞎举个栗子哈,假设a-z分别对应1-24)
  • 如果lower_case为TRUE,那么就把word全转为小写。这个函数里我们可以看到,lower_case设置为了True。
  • 如果word.isdigit()为True:如果该词为数字,那就把该词变为NUM,其中NUM在data_utils.py中定义过了,是个全局变量。
import numpy as np
import os


# shared global variables to be imported from model also
UNK = "$UNK$"
NUM = "$NUM$"
NONE = "O"

所以就是把数字转成$NUM$,这就和我们之前CNN用于文本分类中把不够长的字符串变成'PAD'一样。

再看下一段。

        # 2. get id of word
        if vocab_words is not None:
            if word in vocab_words:
                word = vocab_words[word]
            else:
                if allow_unk:
                    word = vocab_words[UNK]
                else:
                    raise Exception("Unknow key is not allowed. Check that "\
                                    "your vocab (tags?) is correct")

得到每个word的id值。如果wovab_words是非空的,在这个列表里寻找单词word,如果找到了,那么就把该单词变成vocab_words[word],也就是变成了一个数值。
else:如果没有找到,如果allow_unk为True(这个也是在Config类中的设置参数)那么把word替换为vocab[unk]所在的位置。。。UNK是啥呢?UNK是Unknown的意思,这个单词在词汇表中没有收录到,所以索引变为UNK的索引。
else:如果allow_unk为FALSE,也就是不允许存储为UnknownKey,这时弹出Exception提示。

小结

主函数的两句话我们花了一篇文章来讲解,收货还是很大的,主要是配置了一些参数,处理了一下数据。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。