gpt4 book ai didi

python - 只训练一些词嵌入(Keras)

转载 作者:太空狗 更新时间:2023-10-29 20:15:02 25 4
gpt4 key购买 nike

在我的模型中,我使用 GloVe 预训练嵌入。我希望让它们不可训练,以减少模型参数的数量并避免过度拟合。但是,我有一个特殊符号,我确实想要训练其嵌入。

使用提供的嵌入层,我只能使用参数“trainable”来设置所有嵌入的可训练性,方法如下:

embedding_layer = Embedding(voc_size,
emb_dim,
weights=[embedding_matrix],
input_length=MAX_LEN,
trainable=False)

是否有仅训练嵌入子集的 Keras 级解决方案?

请注意:

  1. 没有足够的数据来为所有单词生成新的嵌入。
  2. These答案仅与原生 TensorFlow 相关。

最佳答案

在 Keith 的两个嵌入层的启发下,找到了一些不错的解决方法。

主要思想:

分配具有最高 ID 的特殊 token (和 OOV)。生成一个仅包含特殊标记的“句子”,在其他地方用 0 填充。然后将不可训练的嵌入应用于“正常”句子,并将可训练的嵌入应用于特殊标记。最后,添加两者。

对我来说很好。

    # Normal embs - '+2' for empty token and OOV token
embedding_matrix = np.zeros((vocab_len + 2, emb_dim))
# Special embs
special_embedding_matrix = np.zeros((special_tokens_len + 2, emb_dim))

# Here we may apply pre-trained embeddings to embedding_matrix

embedding_layer = Embedding(vocab_len + 2,
emb_dim,
mask_zero = True,
weights = [embedding_matrix],
input_length = MAX_SENT_LEN,
trainable = False)

special_embedding_layer = Embedding(special_tokens_len + 2,
emb_dim,
mask_zero = True,
weights = [special_embedding_matrix],
input_length = MAX_SENT_LEN,
trainable = True)

valid_words = vocab_len - special_tokens_len

sentence_input = Input(shape=(MAX_SENT_LEN,), dtype='int32')

# Create a vector of special tokens, e.g: [0,0,1,0,3,0,0]
special_tokens_input = Lambda(lambda x: x - valid_words)(sentence_input)
special_tokens_input = Activation('relu')(special_tokens_input)

# Apply both 'normal' embeddings and special token embeddings
embedded_sequences = embedding_layer(sentence_input)
embedded_special = special_embedding_layer(special_tokens_input)

# Add the matrices
embedded_sequences = Add()([embedded_sequences, embedded_special])

关于python - 只训练一些词嵌入(Keras),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49009386/

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