如何在tensorflow中实现过滤器?

时间:2017-10-22 16:22:02

标签: 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函数中,我使用实际图像提供占位符:

 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. 首先计算损失并验证其是否大于0

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

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

1 个答案:

答案 0 :(得分: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()之前实现了。

我通过这篇medium帖子发现了这一点。

相关问题