首页 文章

如何在tensorflow中实现过滤器?

提问于
浏览
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})

我'm using a triplet loss function on these three inputs (that'实际上是上面的 cost 变量):

def triplet_loss(d_pos, d_neg):

    margin = 0.2

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

    return loss

How can I filter the losses, so only the images with loss_value > 0 will be used to train the network?

我该如何实现以下内容:

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

What I have tried so far:

我逐个拍摄了图像(input1 [0],input2 [0],input3 [0]),计算了损失,如果损失是正的,我会计算(并应用)渐变 . 但问题是我在我的模型中使用 dropout 并且我必须在我的输入上应用模型两次:

  • 首先计算损失并验证它是否大于0

  • 第二个运行优化器:这是出错的时候 . 正如我之前提到的,我使用了dropout,因此我的输入模型的结果是不同的,所以即使在步骤1中确定的损失大于0,新的损失有时也会为0 .

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

1 回答

  • 3

    有一个名为“AutoGraph”的新TensorFlow功能 . 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() 之前,您可能已经实现了您想要做的事情 .

    我通过这个帖子找到了这个 .

相关问题