如何將Bert句向量應用于深度神經(jīng)網(wǎng)絡中

Bert開源了預訓練的中文模型,如果你想直接使用Bert模型生成句子向量(當做一個黑盒),并用于深度學習模型中,本文將給出一個作者親自實踐的實例.本文內(nèi)容只針對于實踐,并不會對Bert的模型和理論進行任何介紹.

首先我們準備深度學習模型:
https://github.com/gaussic/text-classification-cnn-rnn
以該項目中的字符級CNN模型為例,下載數(shù)據(jù)后并根據(jù)Readme指導,模型很容易就能跑的通.

接下來準備Bert生成句子向量的模型,選用調(diào)用比較簡單的這個項目:
https://github.com/terrifyzhao/bert-utils
Bert中文模型的下載地址為:
https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip

一切準備就緒后,開始改造模型.必須明確的思路為,我們需要改的是網(wǎng)絡的輸入層和數(shù)據(jù)的預處理部分
text-classification-cnn-rnn中的cnn_model.py定義了網(wǎng)絡的結構,我們先看網(wǎng)絡的前幾層

    def cnn(self):
        """CNN模型"""
        # 詞向量映射
        with tf.device('/cpu:0'):
            embedding = tf.get_variable('embedding', [self.config.vocab_size, self.config.embedding_dim])
            embedding_inputs = tf.nn.embedding_lookup(embedding, self.input_x)

        with tf.name_scope("cnn"):
            # CNN layer
            conv = tf.layers.conv1d(embedding_inputs, self.config.num_filters, self.config.kernel_size, name='conv')
            # global max pooling layer
            gmp = tf.reduce_max(conv, reduction_indices=[1], name='gmp')

其中的輸入層為:
embedding = tf.get_variable('embedding', [self.config.vocab_size, self.config.embedding_dim])
用于創(chuàng)建一個新的變量embedding,隨機生成self.config.vocab_size*self.config.embedding_dim尺寸的詞嵌入張量
embedding_inputs = tf.nn.embedding_lookup(embedding, self.input_x)
用于將input_x映射為詞向量的形式
我們需要重新定義網(wǎng)絡的輸入,所以需要對這部分進行修改.

        with tf.device('/cpu:0'):
            # self.embedding = tf.get_variable('embedding', [self.config.vocab_size, self.config.embedding_dim])
            # self.embedding_inputs = tf.nn.embedding_lookup(self.embedding, self.input_x)
            self.embedding_inputs = tf.reshape(self.input_x, [-1,32,24])

由于bert對于每一句話,生成768維的向量,我們將768維的向量分解為3224的形式(或者2432或者其他乘積為768的分解形式),第一個維度是由input_x的batch決定的,所以設為-1,讓reshape自己進行計算(注意,tf.reshape中最多只有一個維度能被設置為-1)
模型結構處理完之后,我們進行改造數(shù)據(jù)的預處理部分
數(shù)據(jù)的預處理在text-classification-cnn-rnn項目cnews文件夾下的cnews_loader中

from bert_utils.extract_feature import BertVector
bert = BertVector()

首先在cnews_loader中引入bert生成詞向量的函數(shù)
之后對 process_file函數(shù)進行改造

def process_file(filename, word_to_id, cat_to_id, max_length=600):
    """將文件轉換為id表示"""
    contents, labels = read_file(filename)
    x_pad = bert.encode(contents)
    data_id, label_id = [], []
    for i in range(len(contents)):
        # data_id.append([word_to_id[x] for x in contents[i] if x in word_to_id])
        label_id.append(cat_to_id[labels[i]])

    # 使用keras提供的pad_sequences來將文本pad為固定長度
    # x_pad = kr.preprocessing.sequence.pad_sequences(data_id, max_length)
    y_pad = kr.utils.to_categorical(label_id, num_classes=len(cat_to_id))  # 將標簽轉換為one-hot表示

    return x_pad, y_pad

舍棄之前的字典映射方式,將x_pad改為bert生成詞向量的形式
之后對文件的讀取函數(shù)進行改造

def read_file(filename):
    """讀取文件數(shù)據(jù)"""
    contents, labels = [], []
    with open_file(filename) as f:
        for line in f:
            try:
                label = line.strip().split('\t')[0]
                content = line.strip().split('\t')[2]
                if content:
                    # normal
                    # contents.append(list(native_content(content)))
                    # bert
                    contents.append(content)
                    labels.append(native_content(label))
            except:
                pass
    return contents, labels

這樣的話,數(shù)據(jù)預處理和模型結構就都改造完成了,整個項目就可以跑起來了

Training and evaluating...
Epoch: 1
Iter:      0, Train Loss:    1.7, Train Acc:  28.12%, Val Loss:    1.7, Val Acc:  21.73%, Time: 0:00:01 *
Iter:     40, Train Loss:    1.4, Train Acc:  41.41%, Val Loss:    1.4, Val Acc:  42.78%, Time: 0:00:02 *

我也是第一次做這種嘗試,經(jīng)驗就是,要一步一步查看原有網(wǎng)絡的每一層的輸出的張量格式.遇到錯誤不要放棄,去谷歌查找錯誤的來源,有耐心得去不斷調(diào)試.

\color{red}{(涉及公司機密,完整代碼和數(shù)據(jù)無法提供,請見諒,純原創(chuàng),轉載請注明來源)}

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 本文上兩篇系列 NLP的巨人肩膀(上) NLP的巨人肩膀(中) 4.6 Bidirectional Encoder...
    weizier閱讀 6,834評論 1 22
  • 本文另兩篇系列 NLP的巨人肩膀(上) NLP的巨人肩膀(下) 3. 梯子的一級半 除了在word級別的embed...
    weizier閱讀 6,852評論 0 18
  • 2018年5月25日星期五晴 這個星期和小女兒約定中午睡午覺,下午在小飯桌寫作業(yè)時不隨便說話,星...
    人生茶滋味閱讀 258評論 2 1

友情鏈接更多精彩內(nèi)容