gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:09:11 25 4
gpt4 key购买 nike

我想在 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com