首页 文章

Tensorflow中的成对排序损失函数

提问于
浏览
1

我在Tensorflow CR-CNN中实现了这篇论文 . 本文中使用的损失函数具有取决于张量和真实标签的运行时间值的术语 . 据我所知,Tensorflow会创建一个静态计算图,然后在会话中执行它 . 我发现很难实现本文中提到的预测和丢失功能,因为它们都在运行时动态变化 . 我尝试在我的代码中使用tf.cond(),但结果是'None'为渐变 . 因此,我的网络根本没有接受过培训 .

class_scores = tf.matmul(pooled, W_classes)

n_correct = tf.Variable(0, trainable=True)

for t in xrange(batch_size):
    max_arg = tf.cast(tf.argmax(class_scores[t], 1), tf.int32)
    #true_class = tf.constant(0)
    true_class = tf.cast(tf.argmax(Y[t], 1), tf.int32)

    pred_class = tf.Variable(0,trainable=True)
    value = class_scores[t][max_arg]
    tf.cond(value <= 0, lambda: tf.assign(pred_class, 0), lambda: tf.assign(pred_class, max_arg + 1))
    tf.cond(tf.equal(true_class, pred_class), lambda: tf.add(n_correct, 1), lambda: tf.add(n_correct, 0))

    #print(value)

accuracy = tf.cast(n_correct, tf.float32)/tf.cast(batch_size, tf.float32)

在这里,我通过计算正确预测的数量来计算准确性 .

类似的损失函数方法:

gamma = tf.constant(2.0) 
m_plus = tf.constant(2.5)   
m_minus = tf.constant(0.5)

batch_loss = tf.Variable(0.0, trainable=True)


for t in xrange(batch_size):
    max_arg = tf.cast(tf.argmax(class_scores[t], 1), tf.int32)
    true_class = tf.cast(tf.argmax(Y[t], 1), tf.int32)

    top2_val, top2_i = tf.nn.top_k(class_scores[t], 2, sorted=True)  

    pred_class = tf.Variable(0, trainable=True)
    true_score = tf.Variable(0.0, trainable=True)
    neg_score = tf.Variable(0.0, trainable=True)

    value = class_scores[t][max_arg]

    tf.cond(value <= 0, lambda: tf.assign(pred_class, 0), lambda: tf.assign(pred_class, max_arg + 1))

    tf.cond(tf.equal(true_class, 0), lambda: tf.assign(true_score, 0), lambda: tf.assign(true_score, class_scores[t][true_class-1]))

    tf.cond(tf.equal(true_class, 0), lambda: tf.assign(neg_score, value), lambda: tf.cond(tf.equal(true_class, pred_class), 
                lambda: tf.assign(neg_score, top2_val[1]), lambda: tf.assign(neg_score, value)))

    example_loss = tf.Variable(0.0, trainable=True) 

    tf.cond(tf.equal(true_class, 0), lambda: tf.assign(example_loss, tf.log(1 + tf.exp(tf.multiply(gamma, m_minus + neg_score)))), 
                    lambda: tf.assign(example_loss, tf.log(1 + tf.exp(tf.multiply(gamma, m_plus - true_score))) + tf.log(1 + tf.exp(tf.multiply(gamma, m_minus + neg_score)))))
    batch_loss = tf.add(batch_loss, example_loss)

    #print(neg_score)

batch_loss = batch_loss/batch_size
train_step = tf.train.GradientDescentOptimizer(learning_rate=lambda_t).minimize(batch_loss)

但网络没有受到培训 . 任何人都可以建议如何在张量流中做到这一点?

1 回答

  • 1

    这段代码存在一些问题,因为它只是不起作用 . 我建议你尝试使用tensorflow急切执行,因为你在这里存在的概念问题不存在(例如,你不需要tf.cond或tf.Variable来解决你的问题) .

    这个代码示例如何使用tf.cond的问题是tf.cond本质上是有效的(它将操作添加到图形中,只有在使用tf.cond的返回值时才会执行) . 因此,您的代码需要以某种方式链接tf.conds(可能通过tf.control_dependencies)以使它们执行 .

    但是,您也可以在训练示例中使用tf.Variables . Tensorflow无法通过赋值给tf.Variable来支持,所以你需要将你对tf.assign和friends的调用替换为返回变量的新值并从python中使用它 .

相关问题