TensorFlow中的最大保证金损失

w4n*_*ust 7 python machine-learning tensorflow

我正试图在TensorFlow中实现最大保证金损失.我的想法是,我有一些积极的例子,我会对一些负面的例子进行抽样,并希望计算类似的东西

\ sum_ {b} ^ {B}\sum_ {n} ^ {N} max(0,1  - 得分(p_b)+得分(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])
Run Code Online (Sandbox Code Playgroud)

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

而且,它似乎真的不符合tensorflow实现方式.我想可能有更好的方法,更多的矢量化方式来实现它,希望有人会建议选项或指向我的例子.

Oli*_*rot 10

首先我们需要清理输入:

  • 我们想要一系列积极的分数,形状 [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])
Run Code Online (Sandbox Code Playgroud)

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

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