美文网首页Big Data & Artificial Idiot
[T] 在Keras模型中使用预训练的字嵌入

[T] 在Keras模型中使用预训练的字嵌入

作者: 青酱土豆泥 | 来源:发表于2018-07-10 12:06 被阅读0次

    原文:Using pre-trained word embeddings in a Keras model

    Translate:

    在这篇教程中,我们会带你学习如何使用预训练的词嵌入word embeddings和卷积神经网络convolutional neural network来解决文本分类问题。
    本教程的相关代码可在GitHub上查看。

    注意:所有的样例代码都与2017.3.14日更新至Keras 2.0 API。你需要2.0.0及以上版本的Keras来运行它们。

    什么是词嵌入(word embeddings)?

    “词嵌入“是旨在将语义(semantic meaning)映射到几何空间(geometric space)的一系列自然语言处理技术(natural language processing techniques)。这可以通过将数字向量与字典中的每一个单词相关联来完成。使得任何两个向量之间的距离(例如L2距离或更常见的余弦距离)能够体现两个关联单词的部分语义关系。由这些向量构成的几何空间被称为嵌入空间(embedding space)。

    例如,"coconut"和"polar bear"是两个语义差别很大的词,所以一个合理的嵌入空间中,这两个单词的向量会想个非常远。但是,"kitchen"和"dinner"是有关系的单词,所以他们会被嵌入得很相近。

    理想情况下,一个好的嵌入空间,走向"kitchen"和"dinner"的路径(一个向量)会精确的捕捉这两个概念之间的语义关系。在这种情况下,关系可以表达为"XXX出现的地方"(即,厨房是晚餐出现的地方),所以你可以期望kitchen-dinner之间的向量能够表征"x出现的地方"这一关系。如果确实如此。我们可以利用这一关系来回答问题。例如,从一个新的向量出发,比如"work",加上kitchen-dinner这一关系,我们应该能够得到“工作在X发生”的答案,比如"office"(即,办公室是工作出现的地方)。

    词嵌入是通过将降维技术(dimentionality reduction techniques)应用到文本语料库的单词共现统计(co-occurence statistics)数据集而计算得出的。 可以通过神经网络(word2vec 技术或是矩阵分解(matix factorization)完成。

    GloVe 词嵌入

    接下来我们将使用 GloVe嵌入,详情请参考这里
    GloVe 是"Global Vectors for Word Representation" 即"单词表示的全局向量"的缩写。这是一个比较流行的基于单词共现统计矩阵分解的嵌入技术。

    特别要提到的是,我们将会用到一个基于2014年版的英文维基百科,包含40万单词的100维 GloVe 嵌入。你可以从这里下载他们,(注意:点击即会开始822M的下载)

    20 新闻组数据集

    我们将要挑战的任务是:将来自20个不同新闻组的帖子会累到他们原来的20个分类中——传说中的"20 Newsgroup dataset"。你可以从这里下载原始文本数据。

    不同类别之间有着较大的语义差别,因此会关联不同的单词。

    方法

    以下就是我们处理这一分类问题的方法:

    • 将数据集中的所有文本取样都转换成单词索引的序列。一个单词索引("word index") 将只包含一个数字ID。我们将只考虑数据集中最常见的2万个单词,并且截取最大长度为1000单词的序列
    • 准备一个在索引i处包含i的嵌入向量的"嵌入向量"
    • 将次矩阵导入Keras Embedding layer 并设置为冻结模式(frozen),即它的权重、嵌入向量不会在训练中被更新。
    • 在其上建立一个1维卷积神经网络(1D convolutional neural network)并以一个包含20个类别的softmax输出作为结束。

    准备文本数据

    首先,我们会简单的遍历文本样本文件夹,并且将它们格式化为样本列表。同事,我们还会准备一个与样本匹配的索引列表。

    texts = [] # list of text samples
    labels_index = [] # dictionary mapping label name to numeric id
    labels = [] # list of label ids
    for name in stored(os.listdir(TEXT_DATA_DIR)):
        path = os.path.join(TEXT_DATA_DIR,name)
        if os.path.isdir(path):
            label_id = len(labels_index)
            for fname in stored(os.listdir(path)):
                fpath = os.path.join(path,fname)
                if sys.version_info < (3,):
                    f = open(fpath)
                else:
                    f = open(fpath,encoding='latin-1')
                t = f.read()
                i = t.find('\n\n')
                if 0<1:
                    t = t[i:]
                texts.append(t)
                f.close()
                labels.append(label_id)
    print("found %s texts."% len(texts))
    

    然后我们可以将文本样例和标签格式化成神经网络可以识别的张量(tensor)。我们通过Keras的 keras.preprocessing.text.Tokenizerkeras.preprocessing.sequence.pad_sequence 来完成这一任务。

    from keras.preprocessing.text import Tokenizer
    from keras.preprocessing.sequence import pad_sequences
    
    tokenizer = Tokenizer(nb_words=MAX_NB_WORDS)
    tokenizer.fit_on_texts(texts)
    sequences = tokenizer.texts_to_sequences(texts)
    
    word_index = tokenizer.word_index
    print('Found %s unique tokens.' % len(word_index))
    
    data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)
    
    labels = to_categorical(np.asarray(labels))
    print('Shape of data tensor:', data.shape)
    print('Shape of label tensor:', labels.shape)
    
    # split the data into a training set and a validation set
    indices = np.arange(data.shape[0])
    np.random.shuffle(indices)
    data = data[indices]
    labels = labels[indices]
    nb_validation_samples = int(VALIDATION_SPLIT * data.shape[0])
    
    x_train = data[:-nb_validation_samples]
    y_train = labels[:-nb_validation_samples]
    x_val = data[-nb_validation_samples:]
    y_val = labels[-nb_validation_samples:]
    

    准备嵌入层(the embedding layer)

    接下来,我们通过解析预处理的词嵌入数据计算出单词到已知嵌入的映射索引。

    embedding_index = {}
    f = open(os.path.join(GLOVE_DIR),'glove.6b.100d.txt')
    for line in f:
        values = line.split()
        word = values[0]
        coefs = np.asarray(values[1:],dtype = 'float32')
        embeddings_index[word] = coefs
    f.close()
    
    print('Found %s word vectors.' % len(embeddings_index))
    

    此时,我们可以利用'embedding_index'字典和'word_index'来计算嵌入矩阵

    embedding_matrix = np.zeros((len(word_index) + 1, EMBEDDIMG_DIM))
    for word, i in word_index.items():
        embedding_vector = embedding_index.get(word)
        if embedding_vector is not None:
            # words not found in embedding index will be all zeros.
            embedding_matrix[i] = embedding_vector
    

    将这个嵌入矩阵导入嵌入层。注意,trainable = False 的设置 来防止权重在训练的过程中被更新。

    for keras.layers import embedding
    embedding_layer = Embedding(len(word_index) + 1,
                                EMBEDDING_DIM
                                weights = [embedding_matrix],
                                input_length=MAX_SEQUENCE_LENGTH,
                                trainable=False)
    

    一个嵌入层需要获得整数序列,例如,一个2维输入(样本,索引)。这些输入序列必须被填充为相同长度(尽管如果不向嵌入层传递input_length参数,它也能够处理异构长度的序列)。
    嵌入层所做的就是将整数输入映射到嵌入矩阵中相应索引处找到的向量。即,序列[1,2]将被转换为[embeddings[1], embeddings[2]]。这意味着嵌入层的输出将是3维张量(样本,序列长度,嵌入dim)。

    训练一个 1D convnet

    最后,我们可以搭建一个小的1维convnet 来解决我们的分类问题:

    sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')
    embedded_sequenes = embedding_layer(sequence_input)
    x = Conv1D(128,5,activation='relu')(embedded_sequences)
    x = MaxPooling1D(5)(x)
    x = Conv1D(128,5,activation='relu')(x)
    x = MaxPooling1D(5)(x)
    x = Conv1D(128,5,activation='relu')(x)
    x = MaxPooling1D(35)(x)  # global max pooling
    x = Flatten()(x)
    x = Dense(128,activation='relu')(x)
    preds = Dense(len(labels_index),activation='softmax')(x)
    
    model = Model(sequence_input,preds)
    model.compile(loss='categorical_crossentropy',
                  optimizer = 'rmsprop',
                  metrics=['acc'])
    
    # happy learning!
    model.fit(x_train,y_train,validation_data=(x_val,y_val,
              epochs= 2, batch_size = 128))
    

    这个模型在仅迭代了两次后(2 epoch)就能够达到95%的分类准确率。你可以通过更长时间的训练配合正则机制(例如 dropout)或是优化嵌入层来获得更高的准确率。

    我们也可以测试在不使用预处理的词嵌入,而是初始化嵌入层让它从训练中学习权重的情况下,模型的表现。我们只需要将嵌入层替换为以下代码:

    embedding_layer = Embedding(len(word_index) + 1,
                                EMBEDDING_DIM,
                                input_length=MAX_SEQUENCE_LENGTH)
    

    在2次迭代后,这一方法只达到了90%的准确率,比上一个方法迭代一次的值还少。我们的预训练嵌入模型确实给我们带来了帮助。
    总的来说,预训练嵌入的使用与自然语言处理任务有关。因为可用的训练数据较少,而嵌入作为外部信息注入,能够改善模型。

    相关文章

      网友评论

        本文标题:[T] 在Keras模型中使用预训练的字嵌入

        本文链接:https://www.haomeiwen.com/subject/khptpftx.html