代码之家  ›  专栏  ›  技术社区  ›  konstantin_doncov

将其他层添加到Huggingface transformers

  •  0
  • konstantin_doncov  · 技术社区  · 6 年前

    我想补充一点 Dense 预训练后分层 TFDistilBertModel TFXLNetModel TFRobertaModel 拥抱面孔的模特。我已经看到了如何使用 TFBertModel ,例如。 in this notebook :

    output = bert_model([input_ids,attention_masks])
    output = output[1]
    output = tf.keras.layers.Dense(32,activation='relu')(output)
    

    因此,这里我需要使用第二项(即带有索引的项) 1 )的 BERT 输出元组。根据 docs tfbert模型 pooler_output 在这个元组索引中。但是其他三种型号没有 pooler_输出

    那么,如何向其他三个模型输出添加其他层?

    0 回复  |  直到 6 年前
        1
  •  5
  •   konstantin_doncov    5 年前

    看起来像 pooler_output 是一个 Roberta Bert 具体产出。

    而不是使用 pooler_输出 hidden_states (所以,不仅是最后一个隐藏状态)对于所有模型,我们希望使用它们,因为 papers report 那个 隐藏状态 last_hidden_state .

    # Import the needed model(Bert, Roberta or DistilBert) with output_hidden_states=True
    transformer_model = TFBertForSequenceClassification.from_pretrained('bert-large-cased', output_hidden_states=True)
    
    input_ids = tf.keras.Input(shape=(128, ),dtype='int32')
    attention_mask = tf.keras.Input(shape=(128, ), dtype='int32')
    
    transformer = transformer_model([input_ids, attention_mask])    
    hidden_states = transformer[1] # get output_hidden_states
    
    hidden_states_size = 4 # count of the last states 
    hiddes_states_ind = list(range(-hidden_states_size, 0, 1))
    
    selected_hiddes_states = tf.keras.layers.concatenate(tuple([hidden_states[i] for i in hiddes_states_ind]))
    
    # Now we can use selected_hiddes_states as we want
    output = tf.keras.layers.Dense(128, activation='relu')(selected_hiddes_states)
    output = tf.keras.layers.Dense(1, activation='sigmoid')(output)
    model = tf.keras.models.Model(inputs = [input_ids, attention_mask], outputs = output)
    model.compile(tf.keras.optimizers.Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])
    
    推荐文章