gpt4 book ai didi

python - Keras中WARP loss的实现

转载 作者:太空狗 更新时间:2023-10-30 01:36:34 25 4
gpt4 key购买 nike

我正在尝试使用 Keras API 实现扭曲损失(成对排序函数的类型)。我有点卡住这怎么能成功。

warp loss 的定义取自 lightFM doc .:

For a given (user, positive item pair), sample a negative item at random from all the remaining items. Compute predictions for both items; if the negative item’s prediction exceeds that of the positive item plus a margin, perform a gradient update to rank the positive item higher and the negative item lower. If there is no rank violation, continue sampling negative items until a violation is found.

Warp 函数在 semantic embeddings of #hashtags 中使用的例子,一篇来自 facebook AI research 的论文。在这篇论文中,他们试图预测短文本最具代表性的主题标签。其中 'user' 被认为是短文本,'positive item' 是短文本的标签,negative items 是一些随机标签从“标签查找”中统一采样。

我正在按照另一个三元组损失的实现来创建扭曲损失:github

我的理解是,对于每个数据点,我将有 3 个输入。嵌入示例('semi' 伪代码):

sequence_input = Input(shape=(100, ), dtype='int32') # 100 features per data point
positive_example = Input(shape=(1, ), dtype='int32', name="positive") # the one positive example
negative_examples = Input(shape=(1000,), dtype='int32', name="random_negative_examples") # 1000 random negative examples.

#map data points to already created embeddings
embedded_seq_input = embedded_layer(sequence_input)
embedded_positive = embedded_layer(positive_example)
embedded_negatives = embedded_layer(negative_examples)

conv1 = Convolution1D(...)(embeddded_seq_input)
.
.
.
z = Dense(vector_size_of_embedding,activation="linear")(convN)

loss = merge([z, embedded_positive, embedded_negatives],mode=warp_loss)
.
.
.

warp_loss 在哪里(我假设得到 1000 个随机负数而不是全部取负数,分数来自余弦相似度):

def warp_loss(X):
# pseudocode
z, positive, negatives = X
positive_score = cosinus_similatiry(z, positive)
counts = 1
loss = 0
for negative in negatives:
score = cosinus_similatiry(z, negative)
if score > positive_score:
loss = ((number_of_labels - 1) / counts) * (score + 1 - positive_score
else:
counts += 1
return loss

很好地描述了如何计算扭曲:post

我不确定这样做是否正确,但我找不到实现 warp_loss 伪函数的方法。我可以使用 merge([x,u],mode='cos') 计算余弦,但这假设维度相同。所以我不确定如何对多个负面示例使用 merge 模式 cos,所以我尝试创建自己的 warp_loss

任何见解、实现的类似示例、评论都是有用的。

最佳答案

首先,我认为不可能在批量训练范例中实现 WARP。因此你不能在 Keras 中实现 WARP。这是因为 WARP 本质上是顺序的,所以它不能像 Keras 那样处理分成批处理的数据。我想如果你做完全随机的批处理,你可以成功。

通常对于 WARP,您包括 1 的边距,但正如在论文中您可以将其视为超参数:

if neg_score > pos_score-1: #margin of 1
loss = log(num_items / counts) #loss weighted by sample count
loss = max(1, loss) #this looks like same thing you were doing in diff way

这优于它的前身 BPR,因为它优化了前 k 个精度而不是平均精度。

关于python - Keras中WARP loss的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46299554/

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