如何将Bert嵌入提供给LSTM [英] How to feed Bert embeddings to LSTM

查看:752
本文介绍了如何将Bert嵌入提供给LSTM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究用于文本分类问题的Bert + MLP模型.本质上,我试图用基本的LSTM模型代替MLP模型.

I am working on a Bert + MLP model for text classification problem. Essentially, I am trying to replace the MLP model with a basic LSTM model.

是否可以创建带有嵌入的LSTM?还是最好创建一个具有嵌入式层的LSTM?

Is it possible to create a LSTM with embedding? Or, is best to create a LSTM with embedded layer?

更具体地说,我很难创建嵌入式矩阵,因此可以使用Bert嵌入来创建嵌入层.

More specifically, I am having a hard time trying to create embedded matrix so I can create embedding layer using Bert embedding.

def get_bert_embeddings(dataset='gap_corrected_train',
                        dataset_path=TRAIN_PATH,
                        bert_path=BERT_UNCASED_LARGE_PATH,
                        bert_layers=BERT_LAYERS):
    """Get BERT embeddings for all files in dataset_path and specified BERT layers and write them to file."""
    df = None
    for file in os.listdir(dataset_path):
        if df is None:
            df = pd.read_csv(dataset_path+'/'+file, sep='\t')
        else:
            next_df = pd.read_csv(dataset_path+'/'+file, sep='\t')
            df = pd.concat([df, next_df], axis=0)
            df.reset_index(inplace=True, drop=True)

    for i, layer in enumerate(bert_layers):
        embeddings_file = INTERIM_PATH + 'emb_bert' + str(layer) + '_' + dataset + '.h5'
        if not os.path.exists(embeddings_file):
            print('Embeddings file: ', embeddings_file)
            print('Extracting BERT Layer {0} embeddings for {1}...'.format(layer, dataset))
            print("Started at ", time.ctime())

            emb = get_bert_token_embeddings(df, bert_path, layer)
            emb.to_hdf(embeddings_file, 'table')

            print("Finished at ", time.ctime())

def build_mlp_model(input_shape):
    input_layer = layers.Input(input_shape)



    input_features = layers.Input((len(FEATURES),))
    x = layers.Concatenate(axis=1, name="concate_layer")([input_layer, input_features]) 


    x = layers.Dense(HIDDEN_SIZE, name='dense1')(x)
    x = layers.BatchNormalization()(x)
    x = layers.Activation('relu')(x)
    x = layers.Dropout(DROPOUT, seed=RANDOM)(x)

    x = layers.Dense(HIDDEN_SIZE//2, name='dense2')(x)
    x = layers.BatchNormalization()(x)
    x = layers.Activation('relu')(x)
    x = layers.Dropout(DROPOUT//2, seed=RANDOM)(x)

    x = layers.Dense(HIDDEN_SIZE//4, name='dense3')(x)
    x = layers.BatchNormalization()(x)
    x = layers.Activation('relu')(x)
    x = layers.Dropout(DROPOUT//2, seed=RANDOM)(x)

    output_layer = layers.Dense(3, name='output', kernel_regularizer = regularizers.l2(LAMBDA))(x)
    output_layer = layers.Activation('softmax')(output_layer)

    model = models.Model(input=[input_layer, input_features], output=output_layer, name="mlp")
    return model

推荐答案

您可以创建模型,该模型首先使用Embedding层,然后使用LSTM,然后使用Dense. 如此处:

You can create model that uses first the Embedding layer which is followed by LSTM and then Dense. Such as here:

deep_inputs = Input(shape=(length_of_your_data,))
embedding_layer = Embedding(vocab_size, output_dim = 3000, trainable=True)(deep_inputs)
LSTM_Layer_1 = LSTM(512)(embedding_layer) 
dense_layer_1 = Dense(number_of_classes, activation='softmax')(LSTM_Layer_1) 
model_AdGroups = Model(inputs=deep_inputs, outputs=dense_layer_1) 

这篇关于如何将Bert嵌入提供给LSTM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆