【问题标题】:Using BERT Embeddings in Keras Embedding layer在 Keras 嵌入层中使用 BERT 嵌入
【发布时间】:2020-10-27 12:13:37
【问题描述】:

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

【问题讨论】:

  • this 回答你的问题了吗?
  • 如果我有来自单个句子的词嵌入,它将起作用。如果我有几个句子组成的嵌入矩阵呢?
  • 嗯,我猜这取决于你想用网络做什么。
  • 请问您解决了吗
  • @user1 你可以参考这个解决方案stackoverflow.com/a/62466528/10097229

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


【解决方案1】:

希望这些链接对您有所帮助:

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)
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)

谢谢。

【讨论】:

  • 我认为您错过了第二个 sn-p 中的部分代码。你能完成吗?
  • 感谢您指出这一点!更新了第二个 sn-p。
  • 如果我使用你的第二个 sn-p 或句子转换器来生成 bert 嵌入,它应该如何应用于 keras 模型?我的想法是提供一个像 (number_of_instance, dimensions) Ex-: (2000,768) 作为 numpy 数组的输入
猜你喜欢
  • 2018-08-12
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 2019-11-13
  • 2019-10-29
  • 2021-05-12
  • 2018-09-23
  • 1970-01-01
相关资源
最近更新 更多