gpt4 book ai didi

python - TensorFlow 中的最大 margin 损失

转载 作者:太空狗 更新时间:2023-10-29 21:33:46 26 4
gpt4 key购买 nike

我正在尝试在 TensorFlow 中实现最大利润损失。这个想法是我有一些积极的例子,我对一些消极的例子进行了采样,并想计算类似的东西

\sum_{b}^{B} \sum_{n}^{N}max(0, 1 - score(p_b) + score(p_n))

其中 B 是我的批处理大小,N 是我要使用的负样本数。

我是 tensorflow 的新手,我发现实现它很棘手。我的模型计算了一个维度为 B * (N + 1) 的向量,我在其中交替使用正样本和负样本。例如,对于批量大小为 2 和 2 个负示例的向量,我有一个大小为 6 的向量,第一个正示例的分数在索引 0 处,第二个正示例在位置 3 的分数,负示例的分数在位置 1、2、 4 和 5。理想的情况是获取像 [1, 0, 0, 1, 0, 0] 这样的值。

我能想到的是以下,使用 while 和条件:

# Function for computing max margin inner loop
def max_margin_inner(i, batch_examples_t, j, scores, loss):
idx_pos = tf.mul(i, batch_examples_t)
score_pos = tf.gather(scores, idx_pos)
idx_neg = tf.add_n([tf.mul(i, batch_examples_t), j, 1])
score_neg = tf.gather(scores, idx_neg)
loss = tf.add(loss, tf.maximum(0.0, 1.0 - score_pos + score_neg))
tf.add(j, 1)
return [i, batch_examples_t, j, scores, loss]

# Function for computing max margin outer loop
def max_margin_outer(i, batch_examples_t, scores, loss):
j = tf.constant(0)
pos_idx = tf.mul(i, batch_examples_t)
length = tf.gather(tf.shape(scores), 0)
neg_smp_t = tf.constant(num_negative_samples)
cond = lambda i, b, j, bi, lo: tf.logical_and(
tf.less(j, neg_smp_t),
tf.less(pos_idx, length))
tf.while_loop(cond, max_margin_inner, [i, batch_examples_t, j, scores, loss])
tf.add(i, 1)
return [i, batch_examples_t, scores, loss]

# compute the loss
with tf.name_scope('max_margin'):
loss = tf.Variable(0.0, name="loss")
i = tf.constant(0)
batch_examples_t = tf.constant(batch_examples)
condition = lambda i, b, bi, lo: tf.less(i, b)
max_margin = tf.while_loop(
condition,
max_margin_outer,
[i, batch_examples_t, scores, loss])

代码有两个循环,一个用于外部求和,另一个用于内部求和。我面临的问题是损失变量在每次迭代中不断累积错误,而不会在每次迭代后重置。所以它实际上根本不起作用。

而且,好像真的不符合tensorflow的实现方式。我想可能有更好的方法,更矢量化的方法来实现它,希望有人会建议选项或指出示例。

最佳答案

首先我们需要清理输入:

  • 我们想要一个正分数数组,形状为 [B, 1]
  • 我们想要一个负分矩阵,形状为 [B, N]
import tensorflow as tf

B = 2
N = 2
scores = tf.constant([0.5, 0.2, -0.1, 1., -0.5, 0.3]) # shape B * (N+1)

scores = tf.reshape(scores, [B, N+1])

scores_pos = tf.slice(scores, [0, 0], [B, 1])

scores_neg = tf.slice(scores, [0, 1], [B, N])

现在我们只需计算损失矩阵,即每对(正、负)的所有个体损失,并计算其总和。

loss_matrix = tf.maximum(0., 1. - scores_pos + scores_neg)  # we could also use tf.nn.relu here
loss = tf.reduce_sum(loss_matrix)

关于python - TensorFlow 中的最大 margin 损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37689632/

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