【问题标题】:BERT sentence embeddings: how to obtain sentence embeddings vectorBERT 句子嵌入:如何获得句子嵌入向量
【发布时间】:2020-04-07 09:07:33
【问题描述】:

我正在使用模块 bert-for-tf2 将 BERT 模型包装为 Tensorflow 2.0 中的 Keras 层,我已按照您的指南将 BERT 模型实现为 Keras 层。 我正在尝试从句子中提取嵌入;就我而言,这句话是“你好”

我对模型预测的输出有疑问;我写了这个模型:

model_word_embedding = tf.keras.Sequential([
                tf.keras.layers.Input(shape=(4,), dtype='int32', name='input_ids'),
                bert_layer
])

model_word_embedding .build(input_shape=(None, 4))

然后我想提取上面写的句子的嵌入:

sentences = ["Hello"]
predict = model_word_embedding .predict(sentences)

对象 predict 包含 4 个数组,每个数组包含 768 个元素:

print(predict)
print(len(predict))
print(len(predict[0][0]))
...

[[[-0.02768866 -0.7341324   1.9084396  ... -0.65953904  0.26496622
    1.1610721 ]
  [-0.19322394 -1.3134469   0.10383344 ...  1.1250225  -0.2988368
   -0.2323082 ]
  [-1.4576151  -1.4579685   0.78580517 ... -0.8898649  -1.1016986
    0.6008501 ]
  [ 1.41647    -0.92478925 -1.3651332  ... -0.9197768  -1.5469263
    0.03305872]]]
4
768

我知道这 4 个数组中的每个数组都代表我的原始句子,但我想获得一个数组作为原始句子的嵌入。 所以,我的问题是:如何获得句子的嵌入?

在 BERT 源代码中我读到了这个:

对于分类任务,使用第一个向量(对应[CLS])作为“句子向量”。请注意,这只有意义,因为整个模型都经过了微调。

所以我必须从预测输出中取出第一个数组,因为它代表我的句子向量?

感谢您的支持

【问题讨论】:

    标签: keras nlp embedding word-embedding sentence


    【解决方案1】:

    我们应该使用来自最后隐藏状态的 [CLS] 作为 BERT 的句子嵌入。根据 BERT 论文 [CLS] 表示维度 768 的编码句子。下图更详细地表示了 [CLS] 的使用。考虑到你有 2000 个句子。

    #input_ids consist of all sentences padded to max_len. 
    last_hidden_states = model(input_ids)
    features = last_hidden_states[0][:,0,:].numpy() # considering o only the [CLS] for each sentences 
    features.shape
    # (2000, 768) dimension
    

    【讨论】:

    • 谢谢你,非常有用。你知道为什么通过模型运行单行数据总是会产生相同的 CLS 令牌,而不管我传递给它的哪一行?运行多个工作正常,但一个总是给出确切的数组[ 0.35013607, -0.5340336 , 0.28577858, ..., -0.03405955, -0.0165604 , -0.36481357]]
    • 我认为你应该小心使用[CLS]作为句子句子表示:bert-as-service.readthedocs.io/en/latest/section/…
    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多