【问题标题】:Best way to handle negative sampling in Tensorflow 2.0 with Keras使用 Keras 在 Tensorflow 2.0 中处理负采样的最佳方法
【发布时间】:2023-04-04 21:05:01
【问题描述】:

Tensorflow 发布了在 TF 2.0 Keras 中实现 word2vec 的官方指南

https://www.tensorflow.org/tutorials/text/word_embeddings

但是,它缺少负采样,这在 word2vec 中非常重要,这是不幸的,因为原始 tensorflow 有一些很棒的候选采样函数。

我最好的猜测是增强模型,

model = keras.Sequential([
  layers.Embedding(encoder.vocab_size, embedding_dim),
  layers.GlobalAveragePooling1D(),
  layers.Dense(1, activation='sigmoid')
])

也许使用函数式 API 而不是顺序式 API。

我看到 c++ TF 2.0 有候选采样操作https://www.tensorflow.org/api_docs/cc/group/candidate-sampling-ops

这些可以合并到 Keras 中吗?

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    Negative Sampling 是一种技术,其中不在 Context 中的值只是对其中的一小部分进行采样,而不是减少它们的 Weights 的值。

    因此,在我们的实现中,我们使用“Sigmoid”而不是“Softmax”的激活。因此,对于Context 中的单词,我们希望我们的NetworkOutput 10 对于不在Context 中的单词。

    是的,您的观察是正确的,我们需要使用Functional API 而不是Sequential API

    Keras中实现Negative Sampling的代码如下所示:

    # create some input variables
    input_target = Input((1,))
    input_context = Input((1,))
    
    embedding = Embedding(vocab_size, vector_dim, input_length=1, name='embedding')
    
    target = embedding(input_target)
    target = Reshape((vector_dim, 1))(target)
    context = embedding(input_context)
    context = Reshape((vector_dim, 1))(context)
    
    # setup a cosine similarity operation which will be output in a secondary model
    similarity = merge([target, context], mode='cos', dot_axes=0)
    
    # now perform the dot product operation to get a similarity measure
    dot_product = merge([target, context], mode='dot', dot_axes=1)
    dot_product = Reshape((1,))(dot_product)
    # add the sigmoid output layer
    output = Dense(1, activation='sigmoid')(dot_product)
    
    # create the primary training model
    model = Model(input=[input_target, input_context], output=output)
    model.compile(loss='binary_crossentropy', optimizer='rmsprop')
    
    # create a secondary validation model to run our similarity checks during training
    validation_model = Model(input=[input_target, input_context], output=similarity)
    

    更多信息请参考Awesome Article

    希望这会有所帮助。快乐学习!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      • 2017-09-08
      • 2010-11-15
      • 1970-01-01
      相关资源
      最近更新 更多