3

我有一个卷积神经网络,其中三个图像作为输入:

x_anchor = tf.placeholder('float', [None, 4900], name='x_anchor')
x_positive = tf.placeholder('float', [None, 4900], name='x_positive')
x_negative = tf.placeholder('float', [None, 4900], name='x_negative')

在一个train函数中,我为占位符提供实际图像:

 input1, input2, input3 = training.next_batch(start,end)
    ....some other operations...
loss_value  = sess.run([cost], feed_dict={x_anchor:input1, x_positive:input2, x_negative:input3})

我在这三个输入上使用了三元组损失函数(实际上是上面的成本变量):

def triplet_loss(d_pos, d_neg):

    margin = 0.2

    loss = tf.reduce_mean(tf.maximum(0., margin + d_pos - d_neg))

    return loss

如何过滤损失,因此只有 loss_value > 0 的图像将用于训练网络?

我怎样才能实现类似的东西:

if(loss_value for input1, input2, input3 > 0)
  use inputs to train network
else
 do nothing/try another input

到目前为止我已经尝试过:

我一张一张地拍摄图像(input1[0]、input2[0]、input3[0]),计算损失,如果损失为正,我将计算(并应用)梯度。但问题是我在我的模型中使用了dropout,我必须在我的输入上应用两次模型:

  1. 首先计算loss并验证是否大于0

  2. 其次运行优化器:这是出现问题的时候。前面提到过,我使用了dropout,所以模型在我的输入上的结果是不一样的,所以即使第1步确定的loss大于0,新的loss有时候也会为0。

我也尝试使用tf.py_func但卡住了。

4

1 回答 1

3

TensorFlow 有一个新功能,称为“AutoGraph”。AutoGraph 将 Python 代码(包括控制流、print() 和其他 Python 原生特性)转换为纯 TensorFlow 图形代码。例如:

@autograph.convert()
def huber_loss(a):
  if tf.abs(a) <= delta:
    loss = a * a / 2
  else:
    loss = delta * (tf.abs(a) - delta / 2)
  return loss

由于装饰器,在执行时变成了这段代码:

def tf__huber_loss(a):
  with tf.name_scope('huber_loss'):
    def if_true():
      with tf.name_scope('if_true'):
        loss = a * a / 2
        return loss,
    def if_false():
      with tf.name_scope('if_false'):
        loss = delta * (tf.abs(a) - delta / 2)
        return loss,
    loss = ag__.utils.run_cond(tf.less_equal(tf.abs(a), delta), if_true,
        if_false)
    return loss

您想要做的事情可能在使用tf.cond().

我通过这篇中型帖子了解到了这一点。

于 2018-07-19T10:57:37.707 回答