如何在tensorflow中实现过滤器?

如何在tensorflow中实现过滤器?,tensorflow,conv-neural-network,triplet,Tensorflow,Conv Neural Network,Triplet,我有一个卷积神经网络,有三幅图像作为输入: 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函数中,我向占位符提供实际图像

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

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})
我在这三个输入上使用了三重损失函数(实际上是上面的成本变量):

如何过滤损耗,以便仅使用损耗值>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]),计算损失,如果损失为正,我将计算(并应用)梯度。但问题是,我在模型中使用了辍学,我必须对输入应用两次模型:

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

  • 第二步是运行优化器:这是出现问题的时候。正如我前面提到的,我使用了dropout,因此模型对我输入的结果不同,因此,即使在步骤1确定的损耗大于0,新损耗有时也将为0


  • 我还尝试使用
    tf.py_func
    ,但被卡住了。

    有一个新的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
    
    您想要做的事情可以在使用
    tf.cond()之前实现


    我通过这篇文章了解到了这一点。

    你的体重相对于批次零损失部分的梯度应该是零,对吗?所以,在计算如何使损失正常化时,你最多需要计算它们,除非我遗漏了什么。不过,您可以使用
    tf.cond
    有条件地运行optimizer ops(在batch size one设置中)。
    @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