Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Keras 如何将BERT嵌入转换为张量,以便输入LSTM?_Keras_Deep Learning_Nlp_Lstm_Word Embedding - Fatal编程技术网

Keras 如何将BERT嵌入转换为张量,以便输入LSTM?

Keras 如何将BERT嵌入转换为张量,以便输入LSTM?,keras,deep-learning,nlp,lstm,word-embedding,Keras,Deep Learning,Nlp,Lstm,Word Embedding,我试图用BERT在暹罗LSTM网络()中的句子嵌入替换Word2Vec单词嵌入。然而,我的BERT嵌入是(1768)形状的矩阵,而不是可以馈送到keras层的张量。我想知道是否有可能转换它 我找到了一种用通用语句嵌入替换单词嵌入的方法(),我试图修改LSTM的代码,以使用来自以下服务()的BERT语句嵌入 我收到以下错误消息TypeError:“Tensor(“lambda_3/squence:0”,dtype=string)”必须是,但收到的类是“tensorflow.python.frame

我试图用BERT在暹罗LSTM网络()中的句子嵌入替换Word2Vec单词嵌入。然而,我的BERT嵌入是(1768)形状的矩阵,而不是可以馈送到keras层的张量。我想知道是否有可能转换它

我找到了一种用通用语句嵌入替换单词嵌入的方法(),我试图修改LSTM的代码,以使用来自以下服务()的BERT语句嵌入


我收到以下错误消息TypeError:“Tensor(“lambda_3/squence:0”,dtype=string)”必须是,但收到的类是“tensorflow.python.framework.ops.Tensor”

LSTM接受三维输入
[批量大小、序列长度、特征尺寸]

从bert可以得到两种类型的嵌入:

  • 每个序列的令牌表示
  • “CLS”标记表示[其中“CLS”表示“分类]
    • 如果您使用令牌“CLS”表示,则它将是
      [1768]
      ,但如果 您获取所有序列输出,它将是
      [len of sequence,768]

      现在,如果您批量训练模型,它将成为

      [批量大小,句子长度,768]
      这就是LSTM编码器的功能

    • 另一种方法是,您可以添加一个额外的尺寸
      [批量大小,768,1]
      并将其输入LSTM

      在序列长度中添加额外的dim没有意义,因为LSTM 按照顺序展开

    可能的副本
    # Model variables for LSTM 
    n_hidden = 50
    gradient_clipping_norm = 1.25
    batch_size = 64
    n_epoch = 25
    
    def BERTEmbedding(x): 
       #x is an input tensor
        encoded= bc.encode(tf.squeeze(tf.cast(x, tf.string)))
        return encoded
    
    def exponent_neg_manhattan_distance(left, right):
        ''' Helper function for the similarity estimate of the LSTMs outputs'''
        return K.exp(-K.sum(K.abs(left-right), axis=1, keepdims=True))
    
    left_input_text = Input(shape=(1,), dtype=tf.string)
    right_input_text = Input(shape=(1,), dtype=tf.string)
    
    encoded_left = Lambda(BERTEmbedding, output_shape=(768, ))(left_input_text)
    encoded_right = Lambda(BERTEmbedding, output_shape=(768, ))(right_input_text)
    
    # Since this is a siamese network, both sides share the same LSTM
    shared_lstm = LSTM(n_hidden)
    
    left_output = shared_lstm(encoded_left)
    right_output = shared_lstm(encoded_right)