python-3.x - 在 Keras 嵌入层中使用 BERT 嵌入

标签 python-3.x keras nlp embedding bert-language-model

我想在 LSTM 的 Embeddings 层中使用 BERT Word Vector Embeddings 而不是通常的默认嵌入层。有什么办法可以做到吗?

最佳答案

希望这些链接有帮助:

  • Huggingface Transformers with Tf2.0 (TPU training) with embeddings: (https://www.kaggle.com/abhilash1910/nlp-workshop-2-ml-india)
  • 与 BERT 嵌入(Pytorch)的上下文相似性:
    https://github.com/abhilash1910/BERTSimilarity
  • 为了使用 BERT/BERT 变体生成独特的句子嵌入,建议选择正确的层。在某些情况下,可以考虑以下模式来确定嵌入(TF 2.0/Keras):

  • transformer_model = transformers.TFBertModel.from_pretrained('bert-large-uncased')
    
    input_ids = tf.keras.layers.Input(shape=(128,), name='input_token', dtype='int32')
    input_masks_ids = tf.keras.layers.Input(shape=(128,), name='masked_token', dtype='int32')
    X = transformer_model(input_ids, input_masks_ids)[0]
    X = tf.keras.layers.Dropout(0.2)(X)
    X = tf.keras.layers.Dense(6, activation='softmax')
    model = tf.keras.Model(inputs=[input_ids, input_masks_ids], outputs = X)
    
  • 如果这不起作用,那么请参阅 Huggingface 存储库中的“特征提取”以获取嵌入。(https://huggingface.co/transformers/main_classes/pipelines.html)
    提供 sample :

  • import numpy as np
    from transformers import AutoTokenizer, pipeline, TFDistilBertModel
    from scipy.spatial.distance import cosine
    def transformer_embedding(name,inp,model_name):
    
        model = model_name.from_pretrained(name)
        tokenizer = AutoTokenizer.from_pretrained(name)
        pipe = pipeline('feature-extraction', model=model, 
                    tokenizer=tokenizer)
        features = pipe(inp)
        features = np.squeeze(features)
        return features
    z=['The brown fox jumped over the dog','The ship sank in the Atlantic Ocean']
    embedding_features1=transformer_embedding('distilbert-base-uncased',z[0],TFDistilBertModel)
    embedding_features2=transformer_embedding('distilbert-base-uncased',z[1],TFDistilBertModel)
    distance=1-cosine(embedding_features1[0],embedding_features2[0])
    print(distance)
    
    谢谢。

    关于python-3.x - 在 Keras 嵌入层中使用 BERT 嵌入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62771845/

    相关文章:

    python - 如何在考虑其他列的同时计算 .value_count() 行?

    python - 在 kivy 标签上生成随机数

    python - 如何使用 Flask 为 keras 模型提供推理服务?

    python - 如何减少 keras 序列模型的损失

    python - 每个示例具有不同权重的 Keras 自定义损失函数

    nlp - 来自人类语音的电话号码和出生日期

    python - 如果所有列都为空字符串,则从 pandas 数据框中删除行

    python-2.7 - ifilter怎么了?

    java - 字典上的部分匹配

    nlp - 使用SpaCy时下载 'models'有什么意义?